github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/internal/pprof/profile/legacy_profile.go (about)

     1  // Copyright 2014 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  // This file implements parsers to convert legacy profiles into the
     6  // profile.proto format.
     7  
     8  package profile
     9  
    10  import (
    11  	"bufio"
    12  	"bytes"
    13  	"fmt"
    14  	"io"
    15  	"math"
    16  	"regexp"
    17  	"strconv"
    18  	"strings"
    19  )
    20  
    21  var (
    22  	countStartRE = regexp.MustCompile(`\A(\w+) profile: total \d+\n\z`)
    23  	countRE      = regexp.MustCompile(`\A(\d+) @(( 0x[0-9a-f]+)+)\n\z`)
    24  
    25  	heapHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] *@ *(heap[_a-z0-9]*)/?(\d*)`)
    26  	heapSampleRE = regexp.MustCompile(`(-?\d+): *(-?\d+) *\[ *(\d+): *(\d+) *] @([ x0-9a-f]*)`)
    27  
    28  	contentionSampleRE = regexp.MustCompile(`(\d+) *(\d+) @([ x0-9a-f]*)`)
    29  
    30  	hexNumberRE = regexp.MustCompile(`0x[0-9a-f]+`)
    31  
    32  	growthHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] @ growthz`)
    33  
    34  	fragmentationHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] @ fragmentationz`)
    35  
    36  	threadzStartRE = regexp.MustCompile(`--- threadz \d+ ---`)
    37  	threadStartRE  = regexp.MustCompile(`--- Thread ([[:xdigit:]]+) \(name: (.*)/(\d+)\) stack: ---`)
    38  
    39  	procMapsRE = regexp.MustCompile(`([[:xdigit:]]+)-([[:xdigit:]]+)\s+([-rwxp]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+):([[:xdigit:]]+)\s+([[:digit:]]+)\s*(\S+)?`)
    40  
    41  	briefMapsRE = regexp.MustCompile(`\s*([[:xdigit:]]+)-([[:xdigit:]]+):\s*(\S+)(\s.*@)?([[:xdigit:]]+)?`)
    42  
    43  	// LegacyHeapAllocated instructs the heapz parsers to use the
    44  	// allocated memory stats instead of the default in-use memory. Note
    45  	// that tcmalloc doesn't provide all allocated memory, only in-use
    46  	// stats.
    47  	LegacyHeapAllocated bool
    48  )
    49  
    50  func isSpaceOrComment(line string) bool {
    51  	trimmed := strings.TrimSpace(line)
    52  	return len(trimmed) == 0 || trimmed[0] == '#'
    53  }
    54  
    55  // parseGoCount parses a Go count profile (e.g., threadcreate or
    56  // goroutine) and returns a new Profile.
    57  func parseGoCount(b []byte) (*Profile, error) {
    58  	r := bytes.NewBuffer(b)
    59  
    60  	var line string
    61  	var err error
    62  	for {
    63  		// Skip past comments and empty lines seeking a real header.
    64  		line, err = r.ReadString('\n')
    65  		if err != nil {
    66  			return nil, err
    67  		}
    68  		if !isSpaceOrComment(line) {
    69  			break
    70  		}
    71  	}
    72  
    73  	m := countStartRE.FindStringSubmatch(line)
    74  	if m == nil {
    75  		return nil, errUnrecognized
    76  	}
    77  	profileType := m[1]
    78  	p := &Profile{
    79  		PeriodType: &ValueType{Type: profileType, Unit: "count"},
    80  		Period:     1,
    81  		SampleType: []*ValueType{{Type: profileType, Unit: "count"}},
    82  	}
    83  	locations := make(map[uint64]*Location)
    84  	for {
    85  		line, err = r.ReadString('\n')
    86  		if err != nil {
    87  			if err == io.EOF {
    88  				break
    89  			}
    90  			return nil, err
    91  		}
    92  		if isSpaceOrComment(line) {
    93  			continue
    94  		}
    95  		if strings.HasPrefix(line, "---") {
    96  			break
    97  		}
    98  		m := countRE.FindStringSubmatch(line)
    99  		if m == nil {
   100  			return nil, errMalformed
   101  		}
   102  		n, err := strconv.ParseInt(m[1], 0, 64)
   103  		if err != nil {
   104  			return nil, errMalformed
   105  		}
   106  		fields := strings.Fields(m[2])
   107  		locs := make([]*Location, 0, len(fields))
   108  		for _, stk := range fields {
   109  			addr, err := strconv.ParseUint(stk, 0, 64)
   110  			if err != nil {
   111  				return nil, errMalformed
   112  			}
   113  			// Adjust all frames by -1 to land on the call instruction.
   114  			addr--
   115  			loc := locations[addr]
   116  			if loc == nil {
   117  				loc = &Location{
   118  					Address: addr,
   119  				}
   120  				locations[addr] = loc
   121  				p.Location = append(p.Location, loc)
   122  			}
   123  			locs = append(locs, loc)
   124  		}
   125  		p.Sample = append(p.Sample, &Sample{
   126  			Location: locs,
   127  			Value:    []int64{n},
   128  		})
   129  	}
   130  
   131  	if err = parseAdditionalSections(strings.TrimSpace(line), r, p); err != nil {
   132  		return nil, err
   133  	}
   134  	return p, nil
   135  }
   136  
   137  // remapLocationIDs ensures there is a location for each address
   138  // referenced by a sample, and remaps the samples to point to the new
   139  // location ids.
   140  func (p *Profile) remapLocationIDs() {
   141  	seen := make(map[*Location]bool, len(p.Location))
   142  	var locs []*Location
   143  
   144  	for _, s := range p.Sample {
   145  		for _, l := range s.Location {
   146  			if seen[l] {
   147  				continue
   148  			}
   149  			l.ID = uint64(len(locs) + 1)
   150  			locs = append(locs, l)
   151  			seen[l] = true
   152  		}
   153  	}
   154  	p.Location = locs
   155  }
   156  
   157  func (p *Profile) remapFunctionIDs() {
   158  	seen := make(map[*Function]bool, len(p.Function))
   159  	var fns []*Function
   160  
   161  	for _, l := range p.Location {
   162  		for _, ln := range l.Line {
   163  			fn := ln.Function
   164  			if fn == nil || seen[fn] {
   165  				continue
   166  			}
   167  			fn.ID = uint64(len(fns) + 1)
   168  			fns = append(fns, fn)
   169  			seen[fn] = true
   170  		}
   171  	}
   172  	p.Function = fns
   173  }
   174  
   175  // remapMappingIDs matches location addresses with existing mappings
   176  // and updates them appropriately. This is O(N*M), if this ever shows
   177  // up as a bottleneck, evaluate sorting the mappings and doing a
   178  // binary search, which would make it O(N*log(M)).
   179  func (p *Profile) remapMappingIDs() {
   180  	if len(p.Mapping) == 0 {
   181  		return
   182  	}
   183  
   184  	// Some profile handlers will incorrectly set regions for the main
   185  	// executable if its section is remapped. Fix them through heuristics.
   186  
   187  	// Remove the initial mapping if named '/anon_hugepage' and has a
   188  	// consecutive adjacent mapping.
   189  	if m := p.Mapping[0]; strings.HasPrefix(m.File, "/anon_hugepage") {
   190  		if len(p.Mapping) > 1 && m.Limit == p.Mapping[1].Start {
   191  			p.Mapping = p.Mapping[1:]
   192  		}
   193  	}
   194  
   195  	// Subtract the offset from the start of the main mapping if it
   196  	// ends up at a recognizable start address.
   197  	const expectedStart = 0x400000
   198  	if m := p.Mapping[0]; m.Start-m.Offset == expectedStart {
   199  		m.Start = expectedStart
   200  		m.Offset = 0
   201  	}
   202  
   203  	for _, l := range p.Location {
   204  		if a := l.Address; a != 0 {
   205  			for _, m := range p.Mapping {
   206  				if m.Start <= a && a < m.Limit {
   207  					l.Mapping = m
   208  					break
   209  				}
   210  			}
   211  		}
   212  	}
   213  
   214  	// Reset all mapping IDs.
   215  	for i, m := range p.Mapping {
   216  		m.ID = uint64(i + 1)
   217  	}
   218  }
   219  
   220  var cpuInts = []func([]byte) (uint64, []byte){
   221  	get32l,
   222  	get32b,
   223  	get64l,
   224  	get64b,
   225  }
   226  
   227  func get32l(b []byte) (uint64, []byte) {
   228  	if len(b) < 4 {
   229  		return 0, nil
   230  	}
   231  	return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24, b[4:]
   232  }
   233  
   234  func get32b(b []byte) (uint64, []byte) {
   235  	if len(b) < 4 {
   236  		return 0, nil
   237  	}
   238  	return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24, b[4:]
   239  }
   240  
   241  func get64l(b []byte) (uint64, []byte) {
   242  	if len(b) < 8 {
   243  		return 0, nil
   244  	}
   245  	return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56, b[8:]
   246  }
   247  
   248  func get64b(b []byte) (uint64, []byte) {
   249  	if len(b) < 8 {
   250  		return 0, nil
   251  	}
   252  	return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56, b[8:]
   253  }
   254  
   255  // ParseTracebacks parses a set of tracebacks and returns a newly
   256  // populated profile. It will accept any text file and generate a
   257  // Profile out of it with any hex addresses it can identify, including
   258  // a process map if it can recognize one. Each sample will include a
   259  // tag "source" with the addresses recognized in string format.
   260  func ParseTracebacks(b []byte) (*Profile, error) {
   261  	r := bytes.NewBuffer(b)
   262  
   263  	p := &Profile{
   264  		PeriodType: &ValueType{Type: "trace", Unit: "count"},
   265  		Period:     1,
   266  		SampleType: []*ValueType{
   267  			{Type: "trace", Unit: "count"},
   268  		},
   269  	}
   270  
   271  	var sources []string
   272  	var sloc []*Location
   273  
   274  	locs := make(map[uint64]*Location)
   275  	for {
   276  		l, err := r.ReadString('\n')
   277  		if err != nil {
   278  			if err != io.EOF {
   279  				return nil, err
   280  			}
   281  			if l == "" {
   282  				break
   283  			}
   284  		}
   285  		if sectionTrigger(l) == memoryMapSection {
   286  			break
   287  		}
   288  		if s, addrs := extractHexAddresses(l); len(s) > 0 {
   289  			for _, addr := range addrs {
   290  				// Addresses from stack traces point to the next instruction after
   291  				// each call. Adjust by -1 to land somewhere on the actual call.
   292  				addr--
   293  				loc := locs[addr]
   294  				if locs[addr] == nil {
   295  					loc = &Location{
   296  						Address: addr,
   297  					}
   298  					p.Location = append(p.Location, loc)
   299  					locs[addr] = loc
   300  				}
   301  				sloc = append(sloc, loc)
   302  			}
   303  
   304  			sources = append(sources, s...)
   305  		} else {
   306  			if len(sources) > 0 || len(sloc) > 0 {
   307  				addTracebackSample(sloc, sources, p)
   308  				sloc, sources = nil, nil
   309  			}
   310  		}
   311  	}
   312  
   313  	// Add final sample to save any leftover data.
   314  	if len(sources) > 0 || len(sloc) > 0 {
   315  		addTracebackSample(sloc, sources, p)
   316  	}
   317  
   318  	if err := p.ParseMemoryMap(r); err != nil {
   319  		return nil, err
   320  	}
   321  	return p, nil
   322  }
   323  
   324  func addTracebackSample(l []*Location, s []string, p *Profile) {
   325  	p.Sample = append(p.Sample,
   326  		&Sample{
   327  			Value:    []int64{1},
   328  			Location: l,
   329  			Label:    map[string][]string{"source": s},
   330  		})
   331  }
   332  
   333  // parseCPU parses a profilez legacy profile and returns a newly
   334  // populated Profile.
   335  //
   336  // The general format for profilez samples is a sequence of words in
   337  // binary format. The first words are a header with the following data:
   338  //   1st word -- 0
   339  //   2nd word -- 3
   340  //   3rd word -- 0 if a c++ application, 1 if a java application.
   341  //   4th word -- Sampling period (in microseconds).
   342  //   5th word -- Padding.
   343  func parseCPU(b []byte) (*Profile, error) {
   344  	var parse func([]byte) (uint64, []byte)
   345  	var n1, n2, n3, n4, n5 uint64
   346  	for _, parse = range cpuInts {
   347  		var tmp []byte
   348  		n1, tmp = parse(b)
   349  		n2, tmp = parse(tmp)
   350  		n3, tmp = parse(tmp)
   351  		n4, tmp = parse(tmp)
   352  		n5, tmp = parse(tmp)
   353  
   354  		if tmp != nil && n1 == 0 && n2 == 3 && n3 == 0 && n4 > 0 && n5 == 0 {
   355  			b = tmp
   356  			return cpuProfile(b, int64(n4), parse)
   357  		}
   358  	}
   359  	return nil, errUnrecognized
   360  }
   361  
   362  // cpuProfile returns a new Profile from C++ profilez data.
   363  // b is the profile bytes after the header, period is the profiling
   364  // period, and parse is a function to parse 8-byte chunks from the
   365  // profile in its native endianness.
   366  func cpuProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte)) (*Profile, error) {
   367  	p := &Profile{
   368  		Period:     period * 1000,
   369  		PeriodType: &ValueType{Type: "cpu", Unit: "nanoseconds"},
   370  		SampleType: []*ValueType{
   371  			{Type: "samples", Unit: "count"},
   372  			{Type: "cpu", Unit: "nanoseconds"},
   373  		},
   374  	}
   375  	var err error
   376  	if b, _, err = parseCPUSamples(b, parse, true, p); err != nil {
   377  		return nil, err
   378  	}
   379  
   380  	// If all samples have the same second-to-the-bottom frame, it
   381  	// strongly suggests that it is an uninteresting artifact of
   382  	// measurement -- a stack frame pushed by the signal handler. The
   383  	// bottom frame is always correct as it is picked up from the signal
   384  	// structure, not the stack. Check if this is the case and if so,
   385  	// remove.
   386  	if len(p.Sample) > 1 && len(p.Sample[0].Location) > 1 {
   387  		allSame := true
   388  		id1 := p.Sample[0].Location[1].Address
   389  		for _, s := range p.Sample {
   390  			if len(s.Location) < 2 || id1 != s.Location[1].Address {
   391  				allSame = false
   392  				break
   393  			}
   394  		}
   395  		if allSame {
   396  			for _, s := range p.Sample {
   397  				s.Location = append(s.Location[:1], s.Location[2:]...)
   398  			}
   399  		}
   400  	}
   401  
   402  	if err := p.ParseMemoryMap(bytes.NewBuffer(b)); err != nil {
   403  		return nil, err
   404  	}
   405  	return p, nil
   406  }
   407  
   408  // parseCPUSamples parses a collection of profilez samples from a
   409  // profile.
   410  //
   411  // profilez samples are a repeated sequence of stack frames of the
   412  // form:
   413  //    1st word -- The number of times this stack was encountered.
   414  //    2nd word -- The size of the stack (StackSize).
   415  //    3rd word -- The first address on the stack.
   416  //    ...
   417  //    StackSize + 2 -- The last address on the stack
   418  // The last stack trace is of the form:
   419  //   1st word -- 0
   420  //   2nd word -- 1
   421  //   3rd word -- 0
   422  //
   423  // Addresses from stack traces may point to the next instruction after
   424  // each call. Optionally adjust by -1 to land somewhere on the actual
   425  // call (except for the leaf, which is not a call).
   426  func parseCPUSamples(b []byte, parse func(b []byte) (uint64, []byte), adjust bool, p *Profile) ([]byte, map[uint64]*Location, error) {
   427  	locs := make(map[uint64]*Location)
   428  	for len(b) > 0 {
   429  		var count, nstk uint64
   430  		count, b = parse(b)
   431  		nstk, b = parse(b)
   432  		if b == nil || nstk > uint64(len(b)/4) {
   433  			return nil, nil, errUnrecognized
   434  		}
   435  		var sloc []*Location
   436  		addrs := make([]uint64, nstk)
   437  		for i := 0; i < int(nstk); i++ {
   438  			addrs[i], b = parse(b)
   439  		}
   440  
   441  		if count == 0 && nstk == 1 && addrs[0] == 0 {
   442  			// End of data marker
   443  			break
   444  		}
   445  		for i, addr := range addrs {
   446  			if adjust && i > 0 {
   447  				addr--
   448  			}
   449  			loc := locs[addr]
   450  			if loc == nil {
   451  				loc = &Location{
   452  					Address: addr,
   453  				}
   454  				locs[addr] = loc
   455  				p.Location = append(p.Location, loc)
   456  			}
   457  			sloc = append(sloc, loc)
   458  		}
   459  		p.Sample = append(p.Sample,
   460  			&Sample{
   461  				Value:    []int64{int64(count), int64(count) * p.Period},
   462  				Location: sloc,
   463  			})
   464  	}
   465  	// Reached the end without finding the EOD marker.
   466  	return b, locs, nil
   467  }
   468  
   469  // parseHeap parses a heapz legacy or a growthz profile and
   470  // returns a newly populated Profile.
   471  func parseHeap(b []byte) (p *Profile, err error) {
   472  	r := bytes.NewBuffer(b)
   473  	l, err := r.ReadString('\n')
   474  	if err != nil {
   475  		return nil, errUnrecognized
   476  	}
   477  
   478  	sampling := ""
   479  
   480  	if header := heapHeaderRE.FindStringSubmatch(l); header != nil {
   481  		p = &Profile{
   482  			SampleType: []*ValueType{
   483  				{Type: "objects", Unit: "count"},
   484  				{Type: "space", Unit: "bytes"},
   485  			},
   486  			PeriodType: &ValueType{Type: "objects", Unit: "bytes"},
   487  		}
   488  
   489  		var period int64
   490  		if len(header[6]) > 0 {
   491  			if period, err = strconv.ParseInt(header[6], 10, 64); err != nil {
   492  				return nil, errUnrecognized
   493  			}
   494  		}
   495  
   496  		switch header[5] {
   497  		case "heapz_v2", "heap_v2":
   498  			sampling, p.Period = "v2", period
   499  		case "heapprofile":
   500  			sampling, p.Period = "", 1
   501  		case "heap":
   502  			sampling, p.Period = "v2", period/2
   503  		default:
   504  			return nil, errUnrecognized
   505  		}
   506  	} else if header = growthHeaderRE.FindStringSubmatch(l); header != nil {
   507  		p = &Profile{
   508  			SampleType: []*ValueType{
   509  				{Type: "objects", Unit: "count"},
   510  				{Type: "space", Unit: "bytes"},
   511  			},
   512  			PeriodType: &ValueType{Type: "heapgrowth", Unit: "count"},
   513  			Period:     1,
   514  		}
   515  	} else if header = fragmentationHeaderRE.FindStringSubmatch(l); header != nil {
   516  		p = &Profile{
   517  			SampleType: []*ValueType{
   518  				{Type: "objects", Unit: "count"},
   519  				{Type: "space", Unit: "bytes"},
   520  			},
   521  			PeriodType: &ValueType{Type: "allocations", Unit: "count"},
   522  			Period:     1,
   523  		}
   524  	} else {
   525  		return nil, errUnrecognized
   526  	}
   527  
   528  	if LegacyHeapAllocated {
   529  		for _, st := range p.SampleType {
   530  			st.Type = "alloc_" + st.Type
   531  		}
   532  	} else {
   533  		for _, st := range p.SampleType {
   534  			st.Type = "inuse_" + st.Type
   535  		}
   536  	}
   537  
   538  	locs := make(map[uint64]*Location)
   539  	for {
   540  		l, err = r.ReadString('\n')
   541  		if err != nil {
   542  			if err != io.EOF {
   543  				return nil, err
   544  			}
   545  
   546  			if l == "" {
   547  				break
   548  			}
   549  		}
   550  
   551  		if isSpaceOrComment(l) {
   552  			continue
   553  		}
   554  		l = strings.TrimSpace(l)
   555  
   556  		if sectionTrigger(l) != unrecognizedSection {
   557  			break
   558  		}
   559  
   560  		value, blocksize, addrs, err := parseHeapSample(l, p.Period, sampling)
   561  		if err != nil {
   562  			return nil, err
   563  		}
   564  		var sloc []*Location
   565  		for _, addr := range addrs {
   566  			// Addresses from stack traces point to the next instruction after
   567  			// each call. Adjust by -1 to land somewhere on the actual call.
   568  			addr--
   569  			loc := locs[addr]
   570  			if locs[addr] == nil {
   571  				loc = &Location{
   572  					Address: addr,
   573  				}
   574  				p.Location = append(p.Location, loc)
   575  				locs[addr] = loc
   576  			}
   577  			sloc = append(sloc, loc)
   578  		}
   579  
   580  		p.Sample = append(p.Sample, &Sample{
   581  			Value:    value,
   582  			Location: sloc,
   583  			NumLabel: map[string][]int64{"bytes": {blocksize}},
   584  		})
   585  	}
   586  
   587  	if err = parseAdditionalSections(l, r, p); err != nil {
   588  		return nil, err
   589  	}
   590  	return p, nil
   591  }
   592  
   593  // parseHeapSample parses a single row from a heap profile into a new Sample.
   594  func parseHeapSample(line string, rate int64, sampling string) (value []int64, blocksize int64, addrs []uint64, err error) {
   595  	sampleData := heapSampleRE.FindStringSubmatch(line)
   596  	if len(sampleData) != 6 {
   597  		return value, blocksize, addrs, fmt.Errorf("unexpected number of sample values: got %d, want 6", len(sampleData))
   598  	}
   599  
   600  	// Use first two values by default; tcmalloc sampling generates the
   601  	// same value for both, only the older heap-profile collect separate
   602  	// stats for in-use and allocated objects.
   603  	valueIndex := 1
   604  	if LegacyHeapAllocated {
   605  		valueIndex = 3
   606  	}
   607  
   608  	var v1, v2 int64
   609  	if v1, err = strconv.ParseInt(sampleData[valueIndex], 10, 64); err != nil {
   610  		return value, blocksize, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
   611  	}
   612  	if v2, err = strconv.ParseInt(sampleData[valueIndex+1], 10, 64); err != nil {
   613  		return value, blocksize, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
   614  	}
   615  
   616  	if v1 == 0 {
   617  		if v2 != 0 {
   618  			return value, blocksize, addrs, fmt.Errorf("allocation count was 0 but allocation bytes was %d", v2)
   619  		}
   620  	} else {
   621  		blocksize = v2 / v1
   622  		if sampling == "v2" {
   623  			v1, v2 = scaleHeapSample(v1, v2, rate)
   624  		}
   625  	}
   626  
   627  	value = []int64{v1, v2}
   628  	addrs = parseHexAddresses(sampleData[5])
   629  
   630  	return value, blocksize, addrs, nil
   631  }
   632  
   633  // extractHexAddresses extracts hex numbers from a string and returns
   634  // them, together with their numeric value, in a slice.
   635  func extractHexAddresses(s string) ([]string, []uint64) {
   636  	hexStrings := hexNumberRE.FindAllString(s, -1)
   637  	var ids []uint64
   638  	for _, s := range hexStrings {
   639  		if id, err := strconv.ParseUint(s, 0, 64); err == nil {
   640  			ids = append(ids, id)
   641  		} else {
   642  			// Do not expect any parsing failures due to the regexp matching.
   643  			panic("failed to parse hex value:" + s)
   644  		}
   645  	}
   646  	return hexStrings, ids
   647  }
   648  
   649  // parseHexAddresses parses hex numbers from a string and returns them
   650  // in a slice.
   651  func parseHexAddresses(s string) []uint64 {
   652  	_, ids := extractHexAddresses(s)
   653  	return ids
   654  }
   655  
   656  // scaleHeapSample adjusts the data from a heapz Sample to
   657  // account for its probability of appearing in the collected
   658  // data. heapz profiles are a sampling of the memory allocations
   659  // requests in a program. We estimate the unsampled value by dividing
   660  // each collected sample by its probability of appearing in the
   661  // profile. heapz v2 profiles rely on a poisson process to determine
   662  // which samples to collect, based on the desired average collection
   663  // rate R. The probability of a sample of size S to appear in that
   664  // profile is 1-exp(-S/R).
   665  func scaleHeapSample(count, size, rate int64) (int64, int64) {
   666  	if count == 0 || size == 0 {
   667  		return 0, 0
   668  	}
   669  
   670  	if rate <= 1 {
   671  		// if rate==1 all samples were collected so no adjustment is needed.
   672  		// if rate<1 treat as unknown and skip scaling.
   673  		return count, size
   674  	}
   675  
   676  	avgSize := float64(size) / float64(count)
   677  	scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
   678  
   679  	return int64(float64(count) * scale), int64(float64(size) * scale)
   680  }
   681  
   682  // parseContention parses a mutex or contention profile. There are 2 cases:
   683  // "--- contentionz " for legacy C++ profiles (and backwards compatibility)
   684  // "--- mutex:" or "--- contention:" for profiles generated by the Go runtime.
   685  // This code converts the text output from runtime into a *Profile. (In the future
   686  // the runtime might write a serialized Profile directly making this unnecessary.)
   687  func parseContention(b []byte) (*Profile, error) {
   688  	r := bytes.NewBuffer(b)
   689  	l, err := r.ReadString('\n')
   690  	if err != nil {
   691  		return nil, errUnrecognized
   692  	}
   693  	if strings.HasPrefix(l, "--- contentionz ") {
   694  		return parseCppContention(r)
   695  	} else if strings.HasPrefix(l, "--- mutex:") {
   696  		return parseCppContention(r)
   697  	} else if strings.HasPrefix(l, "--- contention:") {
   698  		return parseCppContention(r)
   699  	}
   700  	return nil, errUnrecognized
   701  }
   702  
   703  // parseCppContention parses the output from synchronization_profiling.cc
   704  // for backward compatibility, and the compatible (non-debug) block profile
   705  // output from the Go runtime.
   706  func parseCppContention(r *bytes.Buffer) (*Profile, error) {
   707  	p := &Profile{
   708  		PeriodType: &ValueType{Type: "contentions", Unit: "count"},
   709  		Period:     1,
   710  		SampleType: []*ValueType{
   711  			{Type: "contentions", Unit: "count"},
   712  			{Type: "delay", Unit: "nanoseconds"},
   713  		},
   714  	}
   715  
   716  	var cpuHz int64
   717  	var l string
   718  	var err error
   719  	// Parse text of the form "attribute = value" before the samples.
   720  	const delimiter = "="
   721  	for {
   722  		l, err = r.ReadString('\n')
   723  		if err != nil {
   724  			if err != io.EOF {
   725  				return nil, err
   726  			}
   727  
   728  			if l == "" {
   729  				break
   730  			}
   731  		}
   732  
   733  		if l = strings.TrimSpace(l); l == "" {
   734  			continue
   735  		}
   736  
   737  		if strings.HasPrefix(l, "---") {
   738  			break
   739  		}
   740  
   741  		attr := strings.SplitN(l, delimiter, 2)
   742  		if len(attr) != 2 {
   743  			break
   744  		}
   745  		key, val := strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1])
   746  		var err error
   747  		switch key {
   748  		case "cycles/second":
   749  			if cpuHz, err = strconv.ParseInt(val, 0, 64); err != nil {
   750  				return nil, errUnrecognized
   751  			}
   752  		case "sampling period":
   753  			if p.Period, err = strconv.ParseInt(val, 0, 64); err != nil {
   754  				return nil, errUnrecognized
   755  			}
   756  		case "ms since reset":
   757  			ms, err := strconv.ParseInt(val, 0, 64)
   758  			if err != nil {
   759  				return nil, errUnrecognized
   760  			}
   761  			p.DurationNanos = ms * 1000 * 1000
   762  		case "format":
   763  			// CPP contentionz profiles don't have format.
   764  			return nil, errUnrecognized
   765  		case "resolution":
   766  			// CPP contentionz profiles don't have resolution.
   767  			return nil, errUnrecognized
   768  		case "discarded samples":
   769  		default:
   770  			return nil, errUnrecognized
   771  		}
   772  	}
   773  
   774  	locs := make(map[uint64]*Location)
   775  	for {
   776  		if l = strings.TrimSpace(l); strings.HasPrefix(l, "---") {
   777  			break
   778  		}
   779  		value, addrs, err := parseContentionSample(l, p.Period, cpuHz)
   780  		if err != nil {
   781  			return nil, err
   782  		}
   783  		var sloc []*Location
   784  		for _, addr := range addrs {
   785  			// Addresses from stack traces point to the next instruction after
   786  			// each call. Adjust by -1 to land somewhere on the actual call.
   787  			addr--
   788  			loc := locs[addr]
   789  			if locs[addr] == nil {
   790  				loc = &Location{
   791  					Address: addr,
   792  				}
   793  				p.Location = append(p.Location, loc)
   794  				locs[addr] = loc
   795  			}
   796  			sloc = append(sloc, loc)
   797  		}
   798  		p.Sample = append(p.Sample, &Sample{
   799  			Value:    value,
   800  			Location: sloc,
   801  		})
   802  
   803  		if l, err = r.ReadString('\n'); err != nil {
   804  			if err != io.EOF {
   805  				return nil, err
   806  			}
   807  			if l == "" {
   808  				break
   809  			}
   810  		}
   811  	}
   812  
   813  	if err = parseAdditionalSections(l, r, p); err != nil {
   814  		return nil, err
   815  	}
   816  
   817  	return p, nil
   818  }
   819  
   820  // parseContentionSample parses a single row from a contention profile
   821  // into a new Sample.
   822  func parseContentionSample(line string, period, cpuHz int64) (value []int64, addrs []uint64, err error) {
   823  	sampleData := contentionSampleRE.FindStringSubmatch(line)
   824  	if sampleData == nil {
   825  		return value, addrs, errUnrecognized
   826  	}
   827  
   828  	v1, err := strconv.ParseInt(sampleData[1], 10, 64)
   829  	if err != nil {
   830  		return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
   831  	}
   832  	v2, err := strconv.ParseInt(sampleData[2], 10, 64)
   833  	if err != nil {
   834  		return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
   835  	}
   836  
   837  	// Unsample values if period and cpuHz are available.
   838  	// - Delays are scaled to cycles and then to nanoseconds.
   839  	// - Contentions are scaled to cycles.
   840  	if period > 0 {
   841  		if cpuHz > 0 {
   842  			cpuGHz := float64(cpuHz) / 1e9
   843  			v1 = int64(float64(v1) * float64(period) / cpuGHz)
   844  		}
   845  		v2 = v2 * period
   846  	}
   847  
   848  	value = []int64{v2, v1}
   849  	addrs = parseHexAddresses(sampleData[3])
   850  
   851  	return value, addrs, nil
   852  }
   853  
   854  // parseThread parses a Threadz profile and returns a new Profile.
   855  func parseThread(b []byte) (*Profile, error) {
   856  	r := bytes.NewBuffer(b)
   857  
   858  	var line string
   859  	var err error
   860  	for {
   861  		// Skip past comments and empty lines seeking a real header.
   862  		line, err = r.ReadString('\n')
   863  		if err != nil {
   864  			return nil, err
   865  		}
   866  		if !isSpaceOrComment(line) {
   867  			break
   868  		}
   869  	}
   870  
   871  	if m := threadzStartRE.FindStringSubmatch(line); m != nil {
   872  		// Advance over initial comments until first stack trace.
   873  		for {
   874  			line, err = r.ReadString('\n')
   875  			if err != nil {
   876  				if err != io.EOF {
   877  					return nil, err
   878  				}
   879  
   880  				if line == "" {
   881  					break
   882  				}
   883  			}
   884  			if sectionTrigger(line) != unrecognizedSection || line[0] == '-' {
   885  				break
   886  			}
   887  		}
   888  	} else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
   889  		return nil, errUnrecognized
   890  	}
   891  
   892  	p := &Profile{
   893  		SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
   894  		PeriodType: &ValueType{Type: "thread", Unit: "count"},
   895  		Period:     1,
   896  	}
   897  
   898  	locs := make(map[uint64]*Location)
   899  	// Recognize each thread and populate profile samples.
   900  	for sectionTrigger(line) == unrecognizedSection {
   901  		if strings.HasPrefix(line, "---- no stack trace for") {
   902  			line = ""
   903  			break
   904  		}
   905  		if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
   906  			return nil, errUnrecognized
   907  		}
   908  
   909  		var addrs []uint64
   910  		line, addrs, err = parseThreadSample(r)
   911  		if err != nil {
   912  			return nil, errUnrecognized
   913  		}
   914  		if len(addrs) == 0 {
   915  			// We got a --same as previous threads--. Bump counters.
   916  			if len(p.Sample) > 0 {
   917  				s := p.Sample[len(p.Sample)-1]
   918  				s.Value[0]++
   919  			}
   920  			continue
   921  		}
   922  
   923  		var sloc []*Location
   924  		for _, addr := range addrs {
   925  			// Addresses from stack traces point to the next instruction after
   926  			// each call. Adjust by -1 to land somewhere on the actual call.
   927  			addr--
   928  			loc := locs[addr]
   929  			if locs[addr] == nil {
   930  				loc = &Location{
   931  					Address: addr,
   932  				}
   933  				p.Location = append(p.Location, loc)
   934  				locs[addr] = loc
   935  			}
   936  			sloc = append(sloc, loc)
   937  		}
   938  
   939  		p.Sample = append(p.Sample, &Sample{
   940  			Value:    []int64{1},
   941  			Location: sloc,
   942  		})
   943  	}
   944  
   945  	if err = parseAdditionalSections(line, r, p); err != nil {
   946  		return nil, err
   947  	}
   948  
   949  	return p, nil
   950  }
   951  
   952  // parseThreadSample parses a symbolized or unsymbolized stack trace.
   953  // Returns the first line after the traceback, the sample (or nil if
   954  // it hits a 'same-as-previous' marker) and an error.
   955  func parseThreadSample(b *bytes.Buffer) (nextl string, addrs []uint64, err error) {
   956  	var l string
   957  	sameAsPrevious := false
   958  	for {
   959  		if l, err = b.ReadString('\n'); err != nil {
   960  			if err != io.EOF {
   961  				return "", nil, err
   962  			}
   963  			if l == "" {
   964  				break
   965  			}
   966  		}
   967  		if l = strings.TrimSpace(l); l == "" {
   968  			continue
   969  		}
   970  
   971  		if strings.HasPrefix(l, "---") {
   972  			break
   973  		}
   974  		if strings.Contains(l, "same as previous thread") {
   975  			sameAsPrevious = true
   976  			continue
   977  		}
   978  
   979  		addrs = append(addrs, parseHexAddresses(l)...)
   980  	}
   981  
   982  	if sameAsPrevious {
   983  		return l, nil, nil
   984  	}
   985  	return l, addrs, nil
   986  }
   987  
   988  // parseAdditionalSections parses any additional sections in the
   989  // profile, ignoring any unrecognized sections.
   990  func parseAdditionalSections(l string, b *bytes.Buffer, p *Profile) (err error) {
   991  	for {
   992  		if sectionTrigger(l) == memoryMapSection {
   993  			break
   994  		}
   995  		// Ignore any unrecognized sections.
   996  		if l, err := b.ReadString('\n'); err != nil {
   997  			if err != io.EOF {
   998  				return err
   999  			}
  1000  			if l == "" {
  1001  				break
  1002  			}
  1003  		}
  1004  	}
  1005  	return p.ParseMemoryMap(b)
  1006  }
  1007  
  1008  // ParseMemoryMap parses a memory map in the format of
  1009  // /proc/self/maps, and overrides the mappings in the current profile.
  1010  // It renumbers the samples and locations in the profile correspondingly.
  1011  func (p *Profile) ParseMemoryMap(rd io.Reader) error {
  1012  	b := bufio.NewReader(rd)
  1013  
  1014  	var attrs []string
  1015  	var r *strings.Replacer
  1016  	const delimiter = "="
  1017  	for {
  1018  		l, err := b.ReadString('\n')
  1019  		if err != nil {
  1020  			if err != io.EOF {
  1021  				return err
  1022  			}
  1023  			if l == "" {
  1024  				break
  1025  			}
  1026  		}
  1027  		if l = strings.TrimSpace(l); l == "" {
  1028  			continue
  1029  		}
  1030  
  1031  		if r != nil {
  1032  			l = r.Replace(l)
  1033  		}
  1034  		m, err := parseMappingEntry(l)
  1035  		if err != nil {
  1036  			if err == errUnrecognized {
  1037  				// Recognize assignments of the form: attr=value, and replace
  1038  				// $attr with value on subsequent mappings.
  1039  				if attr := strings.SplitN(l, delimiter, 2); len(attr) == 2 {
  1040  					attrs = append(attrs, "$"+strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1]))
  1041  					r = strings.NewReplacer(attrs...)
  1042  				}
  1043  				// Ignore any unrecognized entries
  1044  				continue
  1045  			}
  1046  			return err
  1047  		}
  1048  		if m == nil || (m.File == "" && len(p.Mapping) != 0) {
  1049  			// In some cases the first entry may include the address range
  1050  			// but not the name of the file. It should be followed by
  1051  			// another entry with the name.
  1052  			continue
  1053  		}
  1054  		if len(p.Mapping) == 1 && p.Mapping[0].File == "" {
  1055  			// Update the name if this is the entry following that empty one.
  1056  			p.Mapping[0].File = m.File
  1057  			continue
  1058  		}
  1059  		p.Mapping = append(p.Mapping, m)
  1060  	}
  1061  	p.remapLocationIDs()
  1062  	p.remapFunctionIDs()
  1063  	p.remapMappingIDs()
  1064  	return nil
  1065  }
  1066  
  1067  func parseMappingEntry(l string) (*Mapping, error) {
  1068  	mapping := &Mapping{}
  1069  	var err error
  1070  	if me := procMapsRE.FindStringSubmatch(l); len(me) == 9 {
  1071  		if !strings.Contains(me[3], "x") {
  1072  			// Skip non-executable entries.
  1073  			return nil, nil
  1074  		}
  1075  		if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  1076  			return nil, errUnrecognized
  1077  		}
  1078  		if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  1079  			return nil, errUnrecognized
  1080  		}
  1081  		if me[4] != "" {
  1082  			if mapping.Offset, err = strconv.ParseUint(me[4], 16, 64); err != nil {
  1083  				return nil, errUnrecognized
  1084  			}
  1085  		}
  1086  		mapping.File = me[8]
  1087  		return mapping, nil
  1088  	}
  1089  
  1090  	if me := briefMapsRE.FindStringSubmatch(l); len(me) == 6 {
  1091  		if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  1092  			return nil, errUnrecognized
  1093  		}
  1094  		if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  1095  			return nil, errUnrecognized
  1096  		}
  1097  		mapping.File = me[3]
  1098  		if me[5] != "" {
  1099  			if mapping.Offset, err = strconv.ParseUint(me[5], 16, 64); err != nil {
  1100  				return nil, errUnrecognized
  1101  			}
  1102  		}
  1103  		return mapping, nil
  1104  	}
  1105  
  1106  	return nil, errUnrecognized
  1107  }
  1108  
  1109  type sectionType int
  1110  
  1111  const (
  1112  	unrecognizedSection sectionType = iota
  1113  	memoryMapSection
  1114  )
  1115  
  1116  var memoryMapTriggers = []string{
  1117  	"--- Memory map: ---",
  1118  	"MAPPED_LIBRARIES:",
  1119  }
  1120  
  1121  func sectionTrigger(line string) sectionType {
  1122  	for _, trigger := range memoryMapTriggers {
  1123  		if strings.Contains(line, trigger) {
  1124  			return memoryMapSection
  1125  		}
  1126  	}
  1127  	return unrecognizedSection
  1128  }
  1129  
  1130  func (p *Profile) addLegacyFrameInfo() {
  1131  	switch {
  1132  	case isProfileType(p, heapzSampleTypes) ||
  1133  		isProfileType(p, heapzInUseSampleTypes) ||
  1134  		isProfileType(p, heapzAllocSampleTypes):
  1135  		p.DropFrames, p.KeepFrames = allocRxStr, allocSkipRxStr
  1136  	case isProfileType(p, contentionzSampleTypes):
  1137  		p.DropFrames, p.KeepFrames = lockRxStr, ""
  1138  	default:
  1139  		p.DropFrames, p.KeepFrames = cpuProfilerRxStr, ""
  1140  	}
  1141  }
  1142  
  1143  var heapzSampleTypes = []string{"allocations", "size"} // early Go pprof profiles
  1144  var heapzInUseSampleTypes = []string{"inuse_objects", "inuse_space"}
  1145  var heapzAllocSampleTypes = []string{"alloc_objects", "alloc_space"}
  1146  var contentionzSampleTypes = []string{"contentions", "delay"}
  1147  
  1148  func isProfileType(p *Profile, t []string) bool {
  1149  	st := p.SampleType
  1150  	if len(st) != len(t) {
  1151  		return false
  1152  	}
  1153  
  1154  	for i := range st {
  1155  		if st[i].Type != t[i] {
  1156  			return false
  1157  		}
  1158  	}
  1159  	return true
  1160  }
  1161  
  1162  var allocRxStr = strings.Join([]string{
  1163  	// POSIX entry points.
  1164  	`calloc`,
  1165  	`cfree`,
  1166  	`malloc`,
  1167  	`free`,
  1168  	`memalign`,
  1169  	`do_memalign`,
  1170  	`(__)?posix_memalign`,
  1171  	`pvalloc`,
  1172  	`valloc`,
  1173  	`realloc`,
  1174  
  1175  	// TC malloc.
  1176  	`tcmalloc::.*`,
  1177  	`tc_calloc`,
  1178  	`tc_cfree`,
  1179  	`tc_malloc`,
  1180  	`tc_free`,
  1181  	`tc_memalign`,
  1182  	`tc_posix_memalign`,
  1183  	`tc_pvalloc`,
  1184  	`tc_valloc`,
  1185  	`tc_realloc`,
  1186  	`tc_new`,
  1187  	`tc_delete`,
  1188  	`tc_newarray`,
  1189  	`tc_deletearray`,
  1190  	`tc_new_nothrow`,
  1191  	`tc_newarray_nothrow`,
  1192  
  1193  	// Memory-allocation routines on OS X.
  1194  	`malloc_zone_malloc`,
  1195  	`malloc_zone_calloc`,
  1196  	`malloc_zone_valloc`,
  1197  	`malloc_zone_realloc`,
  1198  	`malloc_zone_memalign`,
  1199  	`malloc_zone_free`,
  1200  
  1201  	// Go runtime
  1202  	`runtime\..*`,
  1203  
  1204  	// Other misc. memory allocation routines
  1205  	`BaseArena::.*`,
  1206  	`(::)?do_malloc_no_errno`,
  1207  	`(::)?do_malloc_pages`,
  1208  	`(::)?do_malloc`,
  1209  	`DoSampledAllocation`,
  1210  	`MallocedMemBlock::MallocedMemBlock`,
  1211  	`_M_allocate`,
  1212  	`__builtin_(vec_)?delete`,
  1213  	`__builtin_(vec_)?new`,
  1214  	`__gnu_cxx::new_allocator::allocate`,
  1215  	`__libc_malloc`,
  1216  	`__malloc_alloc_template::allocate`,
  1217  	`allocate`,
  1218  	`cpp_alloc`,
  1219  	`operator new(\[\])?`,
  1220  	`simple_alloc::allocate`,
  1221  }, `|`)
  1222  
  1223  var allocSkipRxStr = strings.Join([]string{
  1224  	// Preserve Go runtime frames that appear in the middle/bottom of
  1225  	// the stack.
  1226  	`runtime\.panic`,
  1227  }, `|`)
  1228  
  1229  var cpuProfilerRxStr = strings.Join([]string{
  1230  	`ProfileData::Add`,
  1231  	`ProfileData::prof_handler`,
  1232  	`CpuProfiler::prof_handler`,
  1233  	`__pthread_sighandler`,
  1234  	`__restore`,
  1235  }, `|`)
  1236  
  1237  var lockRxStr = strings.Join([]string{
  1238  	`RecordLockProfileData`,
  1239  	`(base::)?RecordLockProfileData.*`,
  1240  	`(base::)?SubmitMutexProfileData.*`,
  1241  	`(base::)?SubmitSpinLockProfileData.*`,
  1242  	`(Mutex::)?AwaitCommon.*`,
  1243  	`(Mutex::)?Unlock.*`,
  1244  	`(Mutex::)?UnlockSlow.*`,
  1245  	`(Mutex::)?ReaderUnlock.*`,
  1246  	`(MutexLock::)?~MutexLock.*`,
  1247  	`(SpinLock::)?Unlock.*`,
  1248  	`(SpinLock::)?SlowUnlock.*`,
  1249  	`(SpinLockHolder::)?~SpinLockHolder.*`,
  1250  }, `|`)