Source file src/runtime/pprof/memory.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     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  // rssVirtualFrame is a virtual frame name used in the memory profile to represent
    18  // memory categories. The bracketed names cannot collide with real Go function names.
    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  		// pbSample encodes the locations before returning, so the slice can be reused.
   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  		// TODO: this is a kludge. The metrics behind m.HeapLive aren't
   189  		// updated until mark termination, so they'll be zero if we
   190  		// haven't seen one yet. Use the profiler's own estimate of the
   191  		// live heap here. Since m.HeapLive won't be included in
   192  		// goMemory, but live heap allocations will likely contribute to
   193  		// total RSS, add our estimation here to avoid double-counting
   194  		// the live heap size in the samples we emit and in the non-Go
   195  		// memory estimation.
   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  	// Distribute each heap total in proportion to the sampled weights.
   211  	// In words: The sampled values sum to W, and we want to scale them to
   212  	// sum to W'. We could just multiply every value by (W'/W). But we want
   213  	// to end up with an integer and can come up short of W' after rounding.
   214  	// Instead, if we say S_N is the sum of the first N values's weights,
   215  	// then we assign value N a new weight
   216  	//     floor(S_N * W' / W) - floor(S_{N-1} * W' / W)
   217  	// Note that if we drop the "floor"s in the expression we get exactly the
   218  	// weight we want for value N if we allowed fractional values.
   219  	// Since X - floor(X) is less than one, the absolute difference between
   220  	// the weight we assign and the ideal weight is at most one for each value.
   221  	// The last weight we assign is floor(W * W' / W) - floor(S_{N-1} * W' / W),
   222  	// or W' - floor(S_{N-1} * W' / W). Working backwards we see that the total
   223  	// weight assigned is W'.
   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  		// File-backed and shared memory pages are measured directly and
   253  		// are never Go memory, so we always report them in full.
   254  		// Anonymous non-Go memory is only an estimate: anonymous RSS
   255  		// minus Go memory. Go memory includes memory the runtime has
   256  		// mapped but that may not be resident, so the estimate can come
   257  		// out negative. As in the RSS < goMemory case below, we leave a
   258  		// comment rather than shrink measured values to fit RSS.
   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  // scaleHeapWeight returns floor(total * weight / weightTotal) using a 128-bit
   274  // product to avoid overflow. It requires total >= 0, 0 <= weight <= weightTotal,
   275  // and weightTotal > 0. The quotient is at most total, so it fits in int64.
   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