1
2
3
4
5 package pprof
6
7 import (
8 "errors"
9 "fmt"
10 "internal/profilerecord"
11 "io"
12 "math/bits"
13 "runtime"
14 "slices"
15 )
16
17
18
19 type rssVirtualFrame string
20
21 const (
22 rssFrameGoMemory rssVirtualFrame = "[Go Memory]"
23 rssFrameNonGoMemory rssVirtualFrame = "[Non-Go Memory]"
24 rssFrameFileShared rssVirtualFrame = "[File & Shared]"
25 rssFrameAnonymous rssVirtualFrame = "[Anonymous]"
26 rssFrameStacks rssVirtualFrame = "[Stacks]"
27 rssFrameGoroutineStacks rssVirtualFrame = "[Goroutine Stacks]"
28 rssFrameOSStacks rssVirtualFrame = "[OS Stacks]"
29 rssFrameRuntime rssVirtualFrame = "[Runtime]"
30 rssFrameMetadata rssVirtualFrame = "[Metadata]"
31 rssFrameMSpan rssVirtualFrame = "[MSpan]"
32 rssFrameInUseMSpans rssVirtualFrame = "[In-Use MSpans]"
33 rssFrameFreeMSpans rssVirtualFrame = "[Free MSpans]"
34 rssFrameMCache rssVirtualFrame = "[MCache]"
35 rssFrameInUseMCaches rssVirtualFrame = "[In-Use MCaches]"
36 rssFrameFreeMCaches rssVirtualFrame = "[Free MCaches]"
37 rssFrameOtherMetadata rssVirtualFrame = "[Other Metadata]"
38 rssFrameProfilingBuckets rssVirtualFrame = "[Profiling Buckets]"
39 rssFrameOtherRuntime rssVirtualFrame = "[Other Runtime]"
40 rssFrameHeap rssVirtualFrame = "[Heap]"
41 rssFrameLiveHeap rssVirtualFrame = "[Live Heap]"
42 rssFrameDeadHeap rssVirtualFrame = "[Dead Heap]"
43 rssFrameUnusedHeap rssVirtualFrame = "[Unused Heap]"
44 rssFrameFreeHeap rssVirtualFrame = "[Free Heap]"
45 )
46
47 var memoryProfile = &Profile{
48 name: "memory",
49 count: countMemory,
50 write: writeMemory,
51 }
52
53 func countMemory() int { return 0 }
54
55 func writeMemory(w io.Writer, debug int) error {
56 if debug != 0 {
57 return fmt.Errorf("memory profile: only debug=0 is supported")
58 }
59 if !pprof_memoryProfileEnabled() {
60 return errors.New("memory profile: disabled by GODEBUG=memoryprofile=0")
61 }
62 p, metrics := readMemProfileWithMetrics()
63 if err := validateRSSMetrics(&metrics); err != nil {
64 return fmt.Errorf("memory profile: %w", err)
65 }
66 return writeMemoryProto(w, p, int64(runtime.MemProfileRate), &metrics)
67 }
68
69 func readMemProfileWithMetrics() ([]profilerecord.MemProfileRecord, profilerecord.MemProfileMetrics) {
70 var p []profilerecord.MemProfileRecord
71 var metrics profilerecord.MemProfileMetrics
72 n, ok := pprof_memProfileInternal(nil, true, nil)
73 for {
74 p = make([]profilerecord.MemProfileRecord, n+50)
75 n, ok = pprof_memProfileInternal(p, true, &metrics)
76 if ok {
77 return p[:n], metrics
78 }
79 }
80 }
81
82 func validateRSSMetrics(m *profilerecord.MemProfileMetrics) error {
83 leafSum := m.MemoryClassesHeapStacks + m.MemoryClassesOSStacks +
84 m.MemoryClassesMetadataMSpanInuse + m.MemoryClassesMetadataMSpanFree +
85 m.MemoryClassesMetadataMCacheInuse + m.MemoryClassesMetadataMCacheFree +
86 m.MemoryClassesMetadataOther + m.MemoryClassesProfilingBuckets + m.MemoryClassesOther +
87 m.MemoryClassesHeapFree + m.MemoryClassesHeapObjects + m.MemoryClassesHeapUnused +
88 m.MemoryClassesHeapReleased
89 if leafSum != m.MemoryClassesTotal {
90 return fmt.Errorf("memory/classes leaf sum (%d) != total (%d)", leafSum, m.MemoryClassesTotal)
91 }
92 heapTotal := m.MemoryClassesHeapFree + m.MemoryClassesHeapObjects + m.MemoryClassesHeapUnused
93 if m.HeapLive > heapTotal {
94 return fmt.Errorf("heap live (%d) > heap total (%d)", m.HeapLive, heapTotal)
95 }
96 return nil
97 }
98
99 func writeMemoryProto(w io.Writer, p []profilerecord.MemProfileRecord, rate int64, m *profilerecord.MemProfileMetrics) error {
100 b := newProfileBuilder(w)
101 b.pbValueType(tagProfile_PeriodType, "space", "bytes")
102 b.pb.int64Opt(tagProfile_Period, 1)
103 b.pbValueType(tagProfile_SampleType, "memory_space", "bytes")
104
105 type heapWeights struct {
106 live, dead int64
107 }
108 weights := make([]heapWeights, len(p))
109 var liveWeightTotal, deadWeightTotal int64
110 for i, r := range p {
111 _, weights[i].live = scaleHeapSample(r.InUseObjects(), r.ObjectSize, rate)
112 _, weights[i].dead = scaleHeapSample(r.FreedLastGC, r.ObjectSize, rate)
113 if weights[i].live > 0 {
114 liveWeightTotal += weights[i].live
115 }
116 if weights[i].dead > 0 {
117 deadWeightTotal += weights[i].dead
118 }
119 }
120
121 frames := []rssVirtualFrame{
122 rssFrameGoMemory, rssFrameNonGoMemory, rssFrameFileShared, rssFrameAnonymous,
123 rssFrameStacks, rssFrameGoroutineStacks, rssFrameOSStacks,
124 rssFrameRuntime, rssFrameMetadata,
125 rssFrameMSpan, rssFrameInUseMSpans, rssFrameFreeMSpans,
126 rssFrameMCache, rssFrameInUseMCaches, rssFrameFreeMCaches,
127 rssFrameOtherMetadata, rssFrameProfilingBuckets, rssFrameOtherRuntime,
128 rssFrameHeap, rssFrameLiveHeap, rssFrameDeadHeap, rssFrameUnusedHeap, rssFrameFreeHeap,
129 }
130 vLoc := make(map[rssVirtualFrame]uint64, len(frames))
131 for _, frame := range frames {
132 name := string(frame)
133 funcID := b.reserveFuncID()
134 fStart := b.pb.startMessage()
135 b.pb.uint64Opt(tagFunction_ID, funcID)
136 b.pb.int64Opt(tagFunction_Name, b.stringIndex(name))
137 b.pb.int64Opt(tagFunction_SystemName, b.stringIndex(name))
138 b.pb.int64Opt(tagFunction_Filename, b.stringIndex("[memory profile]"))
139 b.pb.endMessage(tagProfile_Function, fStart)
140 locID := b.reserveLocID()
141 lStart := b.pb.startMessage()
142 b.pb.uint64Opt(tagLocation_ID, locID)
143 b.pbLine(tagLocation_Line, funcID, 0)
144 b.pb.endMessage(tagProfile_Location, lStart)
145 vLoc[frame] = locID
146 }
147
148 var sampleLocs []uint64
149 emitSample := func(value int64, vpath []rssVirtualFrame, realLocs []uint64, size int64) {
150 if value == 0 {
151 return
152 }
153 sampleLocs = append(sampleLocs[:0], realLocs...)
154 for _, v := range slices.Backward(vpath) {
155 sampleLocs = append(sampleLocs, vLoc[v])
156 }
157 var labels func()
158 if size > 0 {
159 labels = func() { b.pbLabel(tagSample_Label, "bytes", "", size) }
160 }
161
162 b.pbSample([]int64{value}, sampleLocs, labels)
163 }
164
165 fixed := []struct {
166 value uint64
167 path []rssVirtualFrame
168 }{
169 {m.MemoryClassesHeapStacks, []rssVirtualFrame{rssFrameGoMemory, rssFrameStacks, rssFrameGoroutineStacks}},
170 {m.MemoryClassesOSStacks, []rssVirtualFrame{rssFrameGoMemory, rssFrameStacks, rssFrameOSStacks}},
171 {m.MemoryClassesMetadataMSpanInuse, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameMetadata, rssFrameMSpan, rssFrameInUseMSpans}},
172 {m.MemoryClassesMetadataMSpanFree, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameMetadata, rssFrameMSpan, rssFrameFreeMSpans}},
173 {m.MemoryClassesMetadataMCacheInuse, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameMetadata, rssFrameMCache, rssFrameInUseMCaches}},
174 {m.MemoryClassesMetadataMCacheFree, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameMetadata, rssFrameMCache, rssFrameFreeMCaches}},
175 {m.MemoryClassesMetadataOther, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameMetadata, rssFrameOtherMetadata}},
176 {m.MemoryClassesProfilingBuckets, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameProfilingBuckets}},
177 {m.MemoryClassesOther, []rssVirtualFrame{rssFrameGoMemory, rssFrameRuntime, rssFrameOtherRuntime}},
178 }
179 for _, f := range fixed {
180 emitSample(int64(f.value), f.path, nil, 0)
181 }
182
183 livePath := []rssVirtualFrame{rssFrameGoMemory, rssFrameHeap, rssFrameLiveHeap}
184 deadPath := []rssVirtualFrame{rssFrameGoMemory, rssFrameHeap, rssFrameDeadHeap}
185 goMemory := m.MemoryClassesTotal - m.MemoryClassesHeapReleased
186 heapLive := int64(m.HeapLive)
187 if heapLive == 0 {
188
189
190
191
192
193
194
195
196 heapLive = liveWeightTotal
197 goMemory += uint64(heapLive)
198 }
199 heapDead := max(int64(m.MemoryClassesHeapObjects)-heapLive, 0)
200 if liveWeightTotal == 0 {
201 emitSample(heapLive, livePath, nil, 0)
202 }
203 if deadWeightTotal == 0 {
204 emitSample(heapDead, deadPath, nil, 0)
205 }
206
207 emitSample(int64(m.MemoryClassesHeapUnused), []rssVirtualFrame{rssFrameGoMemory, rssFrameHeap, rssFrameUnusedHeap}, nil, 0)
208 emitSample(int64(m.MemoryClassesHeapFree), []rssVirtualFrame{rssFrameGoMemory, rssFrameHeap, rssFrameFreeHeap}, nil, 0)
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224 var liveCumWeight, deadCumWeight, liveAssigned, deadAssigned int64
225 var realLocs []uint64
226 for i, w := range weights {
227 var liveValue, deadValue int64
228 if w.live > 0 {
229 liveCumWeight += w.live
230 target := scaleHeapWeight(heapLive, liveCumWeight, liveWeightTotal)
231 liveValue = target - liveAssigned
232 liveAssigned = target
233 }
234 if w.dead > 0 {
235 deadCumWeight += w.dead
236 target := scaleHeapWeight(heapDead, deadCumWeight, deadWeightTotal)
237 deadValue = target - deadAssigned
238 deadAssigned = target
239 }
240 if liveValue == 0 && deadValue == 0 {
241 continue
242 }
243 realLocs = b.appendLocsForStackWithoutRuntime(realLocs[:0], p[i].Stack)
244 emitSample(liveValue, livePath, realLocs, p[i].ObjectSize)
245 emitSample(deadValue, deadPath, realLocs, p[i].ObjectSize)
246 }
247
248 switch {
249 case m.RSS == 0:
250 b.pb.int64(tagProfile_Comment, b.stringIndex("RSS is unavailable on this system"))
251 case m.RSSHasShared:
252
253
254
255
256
257
258
259 emitSample(int64(m.RSSShared), []rssVirtualFrame{rssFrameNonGoMemory, rssFrameFileShared}, nil, 0)
260 if anon := m.RSS - m.RSSShared; anon >= goMemory {
261 emitSample(int64(anon-goMemory), []rssVirtualFrame{rssFrameNonGoMemory, rssFrameAnonymous}, nil, 0)
262 } else {
263 b.pb.int64(tagProfile_Comment, b.stringIndex(fmt.Sprintf("Some Go Memory is not resident: Go Memory (%d bytes) > Anonymous RSS (%d bytes). Anonymous Non-Go Memory not shown.", goMemory, anon)))
264 }
265 case m.RSS < goMemory:
266 b.pb.int64(tagProfile_Comment, b.stringIndex(fmt.Sprintf("Some Go Memory is not resident: Go Memory (%d bytes) > RSS (%d bytes). Non-Go Memory not shown.", goMemory, m.RSS)))
267 default:
268 emitSample(int64(m.RSS-goMemory), []rssVirtualFrame{rssFrameNonGoMemory}, nil, 0)
269 }
270 return b.build()
271 }
272
273
274
275
276 func scaleHeapWeight(total, weight, weightTotal int64) int64 {
277 hi, lo := bits.Mul64(uint64(total), uint64(weight))
278 q, _ := bits.Div64(hi, lo, uint64(weightTotal))
279 return int64(q)
280 }
281
View as plain text