Source file src/runtime/pprof/proto.go

     1  // Copyright 2016 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  	"bytes"
     9  	"compress/gzip"
    10  	"fmt"
    11  	"internal/abi"
    12  	"io"
    13  	"os"
    14  	"runtime"
    15  	"strconv"
    16  	"strings"
    17  	"time"
    18  	"unsafe"
    19  )
    20  
    21  // lostProfileEvent is the function to which lost profiling
    22  // events are attributed.
    23  // (The name shows up in the pprof graphs.)
    24  func lostProfileEvent() { lostProfileEvent() }
    25  
    26  // A profileBuilder writes a profile incrementally from a
    27  // stream of profile samples delivered by the runtime.
    28  type profileBuilder struct {
    29  	start      time.Time
    30  	end        time.Time
    31  	havePeriod bool
    32  	period     int64
    33  	m          profMap
    34  
    35  	// encoding state
    36  	w         io.Writer
    37  	zw        *gzip.Writer
    38  	pb        protobuf
    39  	strings   []string
    40  	stringMap map[string]int
    41  	locs      map[uintptr]locInfo // list of locInfo starting with the given PC.
    42  	funcs     map[string]int      // Package path-qualified function name to Function.ID
    43  	mem       []memMap
    44  	deck      pcDeck
    45  }
    46  
    47  type memMap struct {
    48  	// initialized as reading mapping
    49  	start         uintptr
    50  	end           uintptr
    51  	offset        uint64
    52  	file, buildID string
    53  
    54  	funcs symbolizeFlag
    55  	fake  bool // map entry was faked; /proc/self/maps wasn't available
    56  }
    57  
    58  // symbolizeFlag keeps track of symbolization result.
    59  //   0                  : no symbol lookup was performed
    60  //   1<<0 (lookupTried) : symbol lookup was performed
    61  //   1<<1 (lookupFailed): symbol lookup was performed but failed
    62  type symbolizeFlag uint8
    63  
    64  const (
    65  	lookupTried  symbolizeFlag = 1 << iota
    66  	lookupFailed symbolizeFlag = 1 << iota
    67  )
    68  
    69  const (
    70  	// message Profile
    71  	tagProfile_SampleType        = 1  // repeated ValueType
    72  	tagProfile_Sample            = 2  // repeated Sample
    73  	tagProfile_Mapping           = 3  // repeated Mapping
    74  	tagProfile_Location          = 4  // repeated Location
    75  	tagProfile_Function          = 5  // repeated Function
    76  	tagProfile_StringTable       = 6  // repeated string
    77  	tagProfile_DropFrames        = 7  // int64 (string table index)
    78  	tagProfile_KeepFrames        = 8  // int64 (string table index)
    79  	tagProfile_TimeNanos         = 9  // int64
    80  	tagProfile_DurationNanos     = 10 // int64
    81  	tagProfile_PeriodType        = 11 // ValueType (really optional string???)
    82  	tagProfile_Period            = 12 // int64
    83  	tagProfile_Comment           = 13 // repeated int64
    84  	tagProfile_DefaultSampleType = 14 // int64
    85  
    86  	// message ValueType
    87  	tagValueType_Type = 1 // int64 (string table index)
    88  	tagValueType_Unit = 2 // int64 (string table index)
    89  
    90  	// message Sample
    91  	tagSample_Location = 1 // repeated uint64
    92  	tagSample_Value    = 2 // repeated int64
    93  	tagSample_Label    = 3 // repeated Label
    94  
    95  	// message Label
    96  	tagLabel_Key = 1 // int64 (string table index)
    97  	tagLabel_Str = 2 // int64 (string table index)
    98  	tagLabel_Num = 3 // int64
    99  
   100  	// message Mapping
   101  	tagMapping_ID              = 1  // uint64
   102  	tagMapping_Start           = 2  // uint64
   103  	tagMapping_Limit           = 3  // uint64
   104  	tagMapping_Offset          = 4  // uint64
   105  	tagMapping_Filename        = 5  // int64 (string table index)
   106  	tagMapping_BuildID         = 6  // int64 (string table index)
   107  	tagMapping_HasFunctions    = 7  // bool
   108  	tagMapping_HasFilenames    = 8  // bool
   109  	tagMapping_HasLineNumbers  = 9  // bool
   110  	tagMapping_HasInlineFrames = 10 // bool
   111  
   112  	// message Location
   113  	tagLocation_ID        = 1 // uint64
   114  	tagLocation_MappingID = 2 // uint64
   115  	tagLocation_Address   = 3 // uint64
   116  	tagLocation_Line      = 4 // repeated Line
   117  
   118  	// message Line
   119  	tagLine_FunctionID = 1 // uint64
   120  	tagLine_Line       = 2 // int64
   121  
   122  	// message Function
   123  	tagFunction_ID         = 1 // uint64
   124  	tagFunction_Name       = 2 // int64 (string table index)
   125  	tagFunction_SystemName = 3 // int64 (string table index)
   126  	tagFunction_Filename   = 4 // int64 (string table index)
   127  	tagFunction_StartLine  = 5 // int64
   128  )
   129  
   130  // stringIndex adds s to the string table if not already present
   131  // and returns the index of s in the string table.
   132  func (b *profileBuilder) stringIndex(s string) int64 {
   133  	id, ok := b.stringMap[s]
   134  	if !ok {
   135  		id = len(b.strings)
   136  		b.strings = append(b.strings, s)
   137  		b.stringMap[s] = id
   138  	}
   139  	return int64(id)
   140  }
   141  
   142  func (b *profileBuilder) flush() {
   143  	const dataFlush = 4096
   144  	if b.pb.nest == 0 && len(b.pb.data) > dataFlush {
   145  		b.zw.Write(b.pb.data)
   146  		b.pb.data = b.pb.data[:0]
   147  	}
   148  }
   149  
   150  // pbValueType encodes a ValueType message to b.pb.
   151  func (b *profileBuilder) pbValueType(tag int, typ, unit string) {
   152  	start := b.pb.startMessage()
   153  	b.pb.int64(tagValueType_Type, b.stringIndex(typ))
   154  	b.pb.int64(tagValueType_Unit, b.stringIndex(unit))
   155  	b.pb.endMessage(tag, start)
   156  }
   157  
   158  // pbSample encodes a Sample message to b.pb.
   159  func (b *profileBuilder) pbSample(values []int64, locs []uint64, labels func()) {
   160  	start := b.pb.startMessage()
   161  	b.pb.int64s(tagSample_Value, values)
   162  	b.pb.uint64s(tagSample_Location, locs)
   163  	if labels != nil {
   164  		labels()
   165  	}
   166  	b.pb.endMessage(tagProfile_Sample, start)
   167  	b.flush()
   168  }
   169  
   170  // pbLabel encodes a Label message to b.pb.
   171  func (b *profileBuilder) pbLabel(tag int, key, str string, num int64) {
   172  	start := b.pb.startMessage()
   173  	b.pb.int64Opt(tagLabel_Key, b.stringIndex(key))
   174  	b.pb.int64Opt(tagLabel_Str, b.stringIndex(str))
   175  	b.pb.int64Opt(tagLabel_Num, num)
   176  	b.pb.endMessage(tag, start)
   177  }
   178  
   179  // pbLine encodes a Line message to b.pb.
   180  func (b *profileBuilder) pbLine(tag int, funcID uint64, line int64) {
   181  	start := b.pb.startMessage()
   182  	b.pb.uint64Opt(tagLine_FunctionID, funcID)
   183  	b.pb.int64Opt(tagLine_Line, line)
   184  	b.pb.endMessage(tag, start)
   185  }
   186  
   187  // pbMapping encodes a Mapping message to b.pb.
   188  func (b *profileBuilder) pbMapping(tag int, id, base, limit, offset uint64, file, buildID string, hasFuncs bool) {
   189  	start := b.pb.startMessage()
   190  	b.pb.uint64Opt(tagMapping_ID, id)
   191  	b.pb.uint64Opt(tagMapping_Start, base)
   192  	b.pb.uint64Opt(tagMapping_Limit, limit)
   193  	b.pb.uint64Opt(tagMapping_Offset, offset)
   194  	b.pb.int64Opt(tagMapping_Filename, b.stringIndex(file))
   195  	b.pb.int64Opt(tagMapping_BuildID, b.stringIndex(buildID))
   196  	// TODO: we set HasFunctions if all symbols from samples were symbolized (hasFuncs).
   197  	// Decide what to do about HasInlineFrames and HasLineNumbers.
   198  	// Also, another approach to handle the mapping entry with
   199  	// incomplete symbolization results is to dupliace the mapping
   200  	// entry (but with different Has* fields values) and use
   201  	// different entries for symbolized locations and unsymbolized locations.
   202  	if hasFuncs {
   203  		b.pb.bool(tagMapping_HasFunctions, true)
   204  	}
   205  	b.pb.endMessage(tag, start)
   206  }
   207  
   208  func allFrames(addr uintptr) ([]runtime.Frame, symbolizeFlag) {
   209  	// Expand this one address using CallersFrames so we can cache
   210  	// each expansion. In general, CallersFrames takes a whole
   211  	// stack, but in this case we know there will be no skips in
   212  	// the stack and we have return PCs anyway.
   213  	frames := runtime.CallersFrames([]uintptr{addr})
   214  	frame, more := frames.Next()
   215  	if frame.Function == "runtime.goexit" {
   216  		// Short-circuit if we see runtime.goexit so the loop
   217  		// below doesn't allocate a useless empty location.
   218  		return nil, 0
   219  	}
   220  
   221  	symbolizeResult := lookupTried
   222  	if frame.PC == 0 || frame.Function == "" || frame.File == "" || frame.Line == 0 {
   223  		symbolizeResult |= lookupFailed
   224  	}
   225  
   226  	if frame.PC == 0 {
   227  		// If we failed to resolve the frame, at least make up
   228  		// a reasonable call PC. This mostly happens in tests.
   229  		frame.PC = addr - 1
   230  	}
   231  	ret := []runtime.Frame{frame}
   232  	for frame.Function != "runtime.goexit" && more == true {
   233  		frame, more = frames.Next()
   234  		ret = append(ret, frame)
   235  	}
   236  	return ret, symbolizeResult
   237  }
   238  
   239  type locInfo struct {
   240  	// location id assigned by the profileBuilder
   241  	id uint64
   242  
   243  	// sequence of PCs, including the fake PCs returned by the traceback
   244  	// to represent inlined functions
   245  	// https://github.com/golang/go/blob/d6f2f833c93a41ec1c68e49804b8387a06b131c5/src/runtime/traceback.go#L347-L368
   246  	pcs []uintptr
   247  }
   248  
   249  // newProfileBuilder returns a new profileBuilder.
   250  // CPU profiling data obtained from the runtime can be added
   251  // by calling b.addCPUData, and then the eventual profile
   252  // can be obtained by calling b.finish.
   253  func newProfileBuilder(w io.Writer) *profileBuilder {
   254  	zw, _ := gzip.NewWriterLevel(w, gzip.BestSpeed)
   255  	b := &profileBuilder{
   256  		w:         w,
   257  		zw:        zw,
   258  		start:     time.Now(),
   259  		strings:   []string{""},
   260  		stringMap: map[string]int{"": 0},
   261  		locs:      map[uintptr]locInfo{},
   262  		funcs:     map[string]int{},
   263  	}
   264  	b.readMapping()
   265  	return b
   266  }
   267  
   268  // addCPUData adds the CPU profiling data to the profile.
   269  //
   270  // The data must be a whole number of records, as delivered by the runtime.
   271  // len(tags) must be equal to the number of records in data.
   272  func (b *profileBuilder) addCPUData(data []uint64, tags []unsafe.Pointer) error {
   273  	if !b.havePeriod {
   274  		// first record is period
   275  		if len(data) < 3 {
   276  			return fmt.Errorf("truncated profile")
   277  		}
   278  		if data[0] != 3 || data[2] == 0 {
   279  			return fmt.Errorf("malformed profile")
   280  		}
   281  		// data[2] is sampling rate in Hz. Convert to sampling
   282  		// period in nanoseconds.
   283  		b.period = 1e9 / int64(data[2])
   284  		b.havePeriod = true
   285  		data = data[3:]
   286  		// Consume tag slot. Note that there isn't a meaningful tag
   287  		// value for this record.
   288  		tags = tags[1:]
   289  	}
   290  
   291  	// Parse CPU samples from the profile.
   292  	// Each sample is 3+n uint64s:
   293  	//	data[0] = 3+n
   294  	//	data[1] = time stamp (ignored)
   295  	//	data[2] = count
   296  	//	data[3:3+n] = stack
   297  	// If the count is 0 and the stack has length 1,
   298  	// that's an overflow record inserted by the runtime
   299  	// to indicate that stack[0] samples were lost.
   300  	// Otherwise the count is usually 1,
   301  	// but in a few special cases like lost non-Go samples
   302  	// there can be larger counts.
   303  	// Because many samples with the same stack arrive,
   304  	// we want to deduplicate immediately, which we do
   305  	// using the b.m profMap.
   306  	for len(data) > 0 {
   307  		if len(data) < 3 || data[0] > uint64(len(data)) {
   308  			return fmt.Errorf("truncated profile")
   309  		}
   310  		if data[0] < 3 || tags != nil && len(tags) < 1 {
   311  			return fmt.Errorf("malformed profile")
   312  		}
   313  		if len(tags) < 1 {
   314  			return fmt.Errorf("mismatched profile records and tags")
   315  		}
   316  		count := data[2]
   317  		stk := data[3:data[0]]
   318  		data = data[data[0]:]
   319  		tag := tags[0]
   320  		tags = tags[1:]
   321  
   322  		if count == 0 && len(stk) == 1 {
   323  			// overflow record
   324  			count = uint64(stk[0])
   325  			stk = []uint64{
   326  				// gentraceback guarantees that PCs in the
   327  				// stack can be unconditionally decremented and
   328  				// still be valid, so we must do the same.
   329  				uint64(abi.FuncPCABIInternal(lostProfileEvent) + 1),
   330  			}
   331  		}
   332  		b.m.lookup(stk, tag).count += int64(count)
   333  	}
   334  
   335  	if len(tags) != 0 {
   336  		return fmt.Errorf("mismatched profile records and tags")
   337  	}
   338  	return nil
   339  }
   340  
   341  // build completes and returns the constructed profile.
   342  func (b *profileBuilder) build() {
   343  	b.end = time.Now()
   344  
   345  	b.pb.int64Opt(tagProfile_TimeNanos, b.start.UnixNano())
   346  	if b.havePeriod { // must be CPU profile
   347  		b.pbValueType(tagProfile_SampleType, "samples", "count")
   348  		b.pbValueType(tagProfile_SampleType, "cpu", "nanoseconds")
   349  		b.pb.int64Opt(tagProfile_DurationNanos, b.end.Sub(b.start).Nanoseconds())
   350  		b.pbValueType(tagProfile_PeriodType, "cpu", "nanoseconds")
   351  		b.pb.int64Opt(tagProfile_Period, b.period)
   352  	}
   353  
   354  	values := []int64{0, 0}
   355  	var locs []uint64
   356  
   357  	for e := b.m.all; e != nil; e = e.nextAll {
   358  		values[0] = e.count
   359  		values[1] = e.count * b.period
   360  
   361  		var labels func()
   362  		if e.tag != nil {
   363  			labels = func() {
   364  				for k, v := range *(*labelMap)(e.tag) {
   365  					b.pbLabel(tagSample_Label, k, v, 0)
   366  				}
   367  			}
   368  		}
   369  
   370  		locs = b.appendLocsForStack(locs[:0], e.stk)
   371  
   372  		b.pbSample(values, locs, labels)
   373  	}
   374  
   375  	for i, m := range b.mem {
   376  		hasFunctions := m.funcs == lookupTried // lookupTried but not lookupFailed
   377  		b.pbMapping(tagProfile_Mapping, uint64(i+1), uint64(m.start), uint64(m.end), m.offset, m.file, m.buildID, hasFunctions)
   378  	}
   379  
   380  	// TODO: Anything for tagProfile_DropFrames?
   381  	// TODO: Anything for tagProfile_KeepFrames?
   382  
   383  	b.pb.strings(tagProfile_StringTable, b.strings)
   384  	b.zw.Write(b.pb.data)
   385  	b.zw.Close()
   386  }
   387  
   388  // appendLocsForStack appends the location IDs for the given stack trace to the given
   389  // location ID slice, locs. The addresses in the stack are return PCs or 1 + the PC of
   390  // an inline marker as the runtime traceback function returns.
   391  //
   392  // It may emit to b.pb, so there must be no message encoding in progress.
   393  func (b *profileBuilder) appendLocsForStack(locs []uint64, stk []uintptr) (newLocs []uint64) {
   394  	b.deck.reset()
   395  
   396  	// The last frame might be truncated. Recover lost inline frames.
   397  	stk = runtime_expandFinalInlineFrame(stk)
   398  
   399  	for len(stk) > 0 {
   400  		addr := stk[0]
   401  		if l, ok := b.locs[addr]; ok {
   402  			// first record the location if there is any pending accumulated info.
   403  			if id := b.emitLocation(); id > 0 {
   404  				locs = append(locs, id)
   405  			}
   406  
   407  			// then, record the cached location.
   408  			locs = append(locs, l.id)
   409  
   410  			// Skip the matching pcs.
   411  			//
   412  			// Even if stk was truncated due to the stack depth
   413  			// limit, expandFinalInlineFrame above has already
   414  			// fixed the truncation, ensuring it is long enough.
   415  			stk = stk[len(l.pcs):]
   416  			continue
   417  		}
   418  
   419  		frames, symbolizeResult := allFrames(addr)
   420  		if len(frames) == 0 { // runtime.goexit.
   421  			if id := b.emitLocation(); id > 0 {
   422  				locs = append(locs, id)
   423  			}
   424  			stk = stk[1:]
   425  			continue
   426  		}
   427  
   428  		if added := b.deck.tryAdd(addr, frames, symbolizeResult); added {
   429  			stk = stk[1:]
   430  			continue
   431  		}
   432  		// add failed because this addr is not inlined with the
   433  		// existing PCs in the deck. Flush the deck and retry handling
   434  		// this pc.
   435  		if id := b.emitLocation(); id > 0 {
   436  			locs = append(locs, id)
   437  		}
   438  
   439  		// check cache again - previous emitLocation added a new entry
   440  		if l, ok := b.locs[addr]; ok {
   441  			locs = append(locs, l.id)
   442  			stk = stk[len(l.pcs):] // skip the matching pcs.
   443  		} else {
   444  			b.deck.tryAdd(addr, frames, symbolizeResult) // must succeed.
   445  			stk = stk[1:]
   446  		}
   447  	}
   448  	if id := b.emitLocation(); id > 0 { // emit remaining location.
   449  		locs = append(locs, id)
   450  	}
   451  	return locs
   452  }
   453  
   454  // pcDeck is a helper to detect a sequence of inlined functions from
   455  // a stack trace returned by the runtime.
   456  //
   457  // The stack traces returned by runtime's trackback functions are fully
   458  // expanded (at least for Go functions) and include the fake pcs representing
   459  // inlined functions. The profile proto expects the inlined functions to be
   460  // encoded in one Location message.
   461  // https://github.com/google/pprof/blob/5e965273ee43930341d897407202dd5e10e952cb/proto/profile.proto#L177-L184
   462  //
   463  // Runtime does not directly expose whether a frame is for an inlined function
   464  // and looking up debug info is not ideal, so we use a heuristic to filter
   465  // the fake pcs and restore the inlined and entry functions. Inlined functions
   466  // have the following properties:
   467  //   Frame's Func is nil (note: also true for non-Go functions), and
   468  //   Frame's Entry matches its entry function frame's Entry (note: could also be true for recursive calls and non-Go functions), and
   469  //   Frame's Name does not match its entry function frame's name (note: inlined functions cannot be directly recursive).
   470  //
   471  // As reading and processing the pcs in a stack trace one by one (from leaf to the root),
   472  // we use pcDeck to temporarily hold the observed pcs and their expanded frames
   473  // until we observe the entry function frame.
   474  type pcDeck struct {
   475  	pcs             []uintptr
   476  	frames          []runtime.Frame
   477  	symbolizeResult symbolizeFlag
   478  }
   479  
   480  func (d *pcDeck) reset() {
   481  	d.pcs = d.pcs[:0]
   482  	d.frames = d.frames[:0]
   483  	d.symbolizeResult = 0
   484  }
   485  
   486  // tryAdd tries to add the pc and Frames expanded from it (most likely one,
   487  // since the stack trace is already fully expanded) and the symbolizeResult
   488  // to the deck. If it fails the caller needs to flush the deck and retry.
   489  func (d *pcDeck) tryAdd(pc uintptr, frames []runtime.Frame, symbolizeResult symbolizeFlag) (success bool) {
   490  	if existing := len(d.pcs); existing > 0 {
   491  		// 'd.frames' are all expanded from one 'pc' and represent all
   492  		// inlined functions so we check only the last one.
   493  		newFrame := frames[0]
   494  		last := d.frames[existing-1]
   495  		if last.Func != nil { // the last frame can't be inlined. Flush.
   496  			return false
   497  		}
   498  		if last.Entry == 0 || newFrame.Entry == 0 { // Possibly not a Go function. Don't try to merge.
   499  			return false
   500  		}
   501  
   502  		if last.Entry != newFrame.Entry { // newFrame is for a different function.
   503  			return false
   504  		}
   505  		if last.Function == newFrame.Function { // maybe recursion.
   506  			return false
   507  		}
   508  	}
   509  	d.pcs = append(d.pcs, pc)
   510  	d.frames = append(d.frames, frames...)
   511  	d.symbolizeResult |= symbolizeResult
   512  	return true
   513  }
   514  
   515  // emitLocation emits the new location and function information recorded in the deck
   516  // and returns the location ID encoded in the profile protobuf.
   517  // It emits to b.pb, so there must be no message encoding in progress.
   518  // It resets the deck.
   519  func (b *profileBuilder) emitLocation() uint64 {
   520  	if len(b.deck.pcs) == 0 {
   521  		return 0
   522  	}
   523  	defer b.deck.reset()
   524  
   525  	addr := b.deck.pcs[0]
   526  	firstFrame := b.deck.frames[0]
   527  
   528  	// We can't write out functions while in the middle of the
   529  	// Location message, so record new functions we encounter and
   530  	// write them out after the Location.
   531  	type newFunc struct {
   532  		id         uint64
   533  		name, file string
   534  	}
   535  	newFuncs := make([]newFunc, 0, 8)
   536  
   537  	id := uint64(len(b.locs)) + 1
   538  	b.locs[addr] = locInfo{id: id, pcs: append([]uintptr{}, b.deck.pcs...)}
   539  
   540  	start := b.pb.startMessage()
   541  	b.pb.uint64Opt(tagLocation_ID, id)
   542  	b.pb.uint64Opt(tagLocation_Address, uint64(firstFrame.PC))
   543  	for _, frame := range b.deck.frames {
   544  		// Write out each line in frame expansion.
   545  		funcID := uint64(b.funcs[frame.Function])
   546  		if funcID == 0 {
   547  			funcID = uint64(len(b.funcs)) + 1
   548  			b.funcs[frame.Function] = int(funcID)
   549  			newFuncs = append(newFuncs, newFunc{funcID, frame.Function, frame.File})
   550  		}
   551  		b.pbLine(tagLocation_Line, funcID, int64(frame.Line))
   552  	}
   553  	for i := range b.mem {
   554  		if b.mem[i].start <= addr && addr < b.mem[i].end || b.mem[i].fake {
   555  			b.pb.uint64Opt(tagLocation_MappingID, uint64(i+1))
   556  
   557  			m := b.mem[i]
   558  			m.funcs |= b.deck.symbolizeResult
   559  			b.mem[i] = m
   560  			break
   561  		}
   562  	}
   563  	b.pb.endMessage(tagProfile_Location, start)
   564  
   565  	// Write out functions we found during frame expansion.
   566  	for _, fn := range newFuncs {
   567  		start := b.pb.startMessage()
   568  		b.pb.uint64Opt(tagFunction_ID, fn.id)
   569  		b.pb.int64Opt(tagFunction_Name, b.stringIndex(fn.name))
   570  		b.pb.int64Opt(tagFunction_SystemName, b.stringIndex(fn.name))
   571  		b.pb.int64Opt(tagFunction_Filename, b.stringIndex(fn.file))
   572  		b.pb.endMessage(tagProfile_Function, start)
   573  	}
   574  
   575  	b.flush()
   576  	return id
   577  }
   578  
   579  // readMapping reads /proc/self/maps and writes mappings to b.pb.
   580  // It saves the address ranges of the mappings in b.mem for use
   581  // when emitting locations.
   582  func (b *profileBuilder) readMapping() {
   583  	data, _ := os.ReadFile("/proc/self/maps")
   584  	parseProcSelfMaps(data, b.addMapping)
   585  	if len(b.mem) == 0 { // pprof expects a map entry, so fake one.
   586  		b.addMappingEntry(0, 0, 0, "", "", true)
   587  		// TODO(hyangah): make addMapping return *memMap or
   588  		// take a memMap struct, and get rid of addMappingEntry
   589  		// that takes a bunch of positional arguments.
   590  	}
   591  }
   592  
   593  var space = []byte(" ")
   594  var newline = []byte("\n")
   595  
   596  func parseProcSelfMaps(data []byte, addMapping func(lo, hi, offset uint64, file, buildID string)) {
   597  	// $ cat /proc/self/maps
   598  	// 00400000-0040b000 r-xp 00000000 fc:01 787766                             /bin/cat
   599  	// 0060a000-0060b000 r--p 0000a000 fc:01 787766                             /bin/cat
   600  	// 0060b000-0060c000 rw-p 0000b000 fc:01 787766                             /bin/cat
   601  	// 014ab000-014cc000 rw-p 00000000 00:00 0                                  [heap]
   602  	// 7f7d76af8000-7f7d7797c000 r--p 00000000 fc:01 1318064                    /usr/lib/locale/locale-archive
   603  	// 7f7d7797c000-7f7d77b36000 r-xp 00000000 fc:01 1180226                    /lib/x86_64-linux-gnu/libc-2.19.so
   604  	// 7f7d77b36000-7f7d77d36000 ---p 001ba000 fc:01 1180226                    /lib/x86_64-linux-gnu/libc-2.19.so
   605  	// 7f7d77d36000-7f7d77d3a000 r--p 001ba000 fc:01 1180226                    /lib/x86_64-linux-gnu/libc-2.19.so
   606  	// 7f7d77d3a000-7f7d77d3c000 rw-p 001be000 fc:01 1180226                    /lib/x86_64-linux-gnu/libc-2.19.so
   607  	// 7f7d77d3c000-7f7d77d41000 rw-p 00000000 00:00 0
   608  	// 7f7d77d41000-7f7d77d64000 r-xp 00000000 fc:01 1180217                    /lib/x86_64-linux-gnu/ld-2.19.so
   609  	// 7f7d77f3f000-7f7d77f42000 rw-p 00000000 00:00 0
   610  	// 7f7d77f61000-7f7d77f63000 rw-p 00000000 00:00 0
   611  	// 7f7d77f63000-7f7d77f64000 r--p 00022000 fc:01 1180217                    /lib/x86_64-linux-gnu/ld-2.19.so
   612  	// 7f7d77f64000-7f7d77f65000 rw-p 00023000 fc:01 1180217                    /lib/x86_64-linux-gnu/ld-2.19.so
   613  	// 7f7d77f65000-7f7d77f66000 rw-p 00000000 00:00 0
   614  	// 7ffc342a2000-7ffc342c3000 rw-p 00000000 00:00 0                          [stack]
   615  	// 7ffc34343000-7ffc34345000 r-xp 00000000 00:00 0                          [vdso]
   616  	// ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
   617  
   618  	var line []byte
   619  	// next removes and returns the next field in the line.
   620  	// It also removes from line any spaces following the field.
   621  	next := func() []byte {
   622  		var f []byte
   623  		f, line, _ = bytes.Cut(line, space)
   624  		line = bytes.TrimLeft(line, " ")
   625  		return f
   626  	}
   627  
   628  	for len(data) > 0 {
   629  		line, data, _ = bytes.Cut(data, newline)
   630  		addr := next()
   631  		loStr, hiStr, ok := strings.Cut(string(addr), "-")
   632  		if !ok {
   633  			continue
   634  		}
   635  		lo, err := strconv.ParseUint(loStr, 16, 64)
   636  		if err != nil {
   637  			continue
   638  		}
   639  		hi, err := strconv.ParseUint(hiStr, 16, 64)
   640  		if err != nil {
   641  			continue
   642  		}
   643  		perm := next()
   644  		if len(perm) < 4 || perm[2] != 'x' {
   645  			// Only interested in executable mappings.
   646  			continue
   647  		}
   648  		offset, err := strconv.ParseUint(string(next()), 16, 64)
   649  		if err != nil {
   650  			continue
   651  		}
   652  		next()          // dev
   653  		inode := next() // inode
   654  		if line == nil {
   655  			continue
   656  		}
   657  		file := string(line)
   658  
   659  		// Trim deleted file marker.
   660  		deletedStr := " (deleted)"
   661  		deletedLen := len(deletedStr)
   662  		if len(file) >= deletedLen && file[len(file)-deletedLen:] == deletedStr {
   663  			file = file[:len(file)-deletedLen]
   664  		}
   665  
   666  		if len(inode) == 1 && inode[0] == '0' && file == "" {
   667  			// Huge-page text mappings list the initial fragment of
   668  			// mapped but unpopulated memory as being inode 0.
   669  			// Don't report that part.
   670  			// But [vdso] and [vsyscall] are inode 0, so let non-empty file names through.
   671  			continue
   672  		}
   673  
   674  		// TODO: pprof's remapMappingIDs makes two adjustments:
   675  		// 1. If there is an /anon_hugepage mapping first and it is
   676  		// consecutive to a next mapping, drop the /anon_hugepage.
   677  		// 2. If start-offset = 0x400000, change start to 0x400000 and offset to 0.
   678  		// There's no indication why either of these is needed.
   679  		// Let's try not doing these and see what breaks.
   680  		// If we do need them, they would go here, before we
   681  		// enter the mappings into b.mem in the first place.
   682  
   683  		buildID, _ := elfBuildID(file)
   684  		addMapping(lo, hi, offset, file, buildID)
   685  	}
   686  }
   687  
   688  func (b *profileBuilder) addMapping(lo, hi, offset uint64, file, buildID string) {
   689  	b.addMappingEntry(lo, hi, offset, file, buildID, false)
   690  }
   691  
   692  func (b *profileBuilder) addMappingEntry(lo, hi, offset uint64, file, buildID string, fake bool) {
   693  	b.mem = append(b.mem, memMap{
   694  		start:   uintptr(lo),
   695  		end:     uintptr(hi),
   696  		offset:  offset,
   697  		file:    file,
   698  		buildID: buildID,
   699  		fake:    fake,
   700  	})
   701  }
   702  

View as plain text