Source file src/cmd/vendor/github.com/google/pprof/internal/report/stacks.go

     1  // Copyright 2022 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package report
    16  
    17  import (
    18  	"crypto/sha256"
    19  	"encoding/binary"
    20  	"fmt"
    21  	"regexp"
    22  
    23  	"github.com/google/pprof/internal/measurement"
    24  	"github.com/google/pprof/profile"
    25  )
    26  
    27  // StackSet holds a set of stacks corresponding to a profile.
    28  //
    29  // Slices in StackSet and the types it contains are always non-nil,
    30  // which makes Javascript code that uses the JSON encoding less error-prone.
    31  type StackSet struct {
    32  	Total   int64         // Total value of the profile.
    33  	Scale   float64       // Multiplier to generate displayed value
    34  	Type    string        // Profile type. E.g., "cpu".
    35  	Unit    string        // One of "B", "s", "GCU", or "" (if unknown)
    36  	Stacks  []Stack       // List of stored stacks
    37  	Sources []StackSource // Mapping from source index to info
    38  }
    39  
    40  // Stack holds a single stack instance.
    41  type Stack struct {
    42  	Value   int64 // Total value for all samples of this stack.
    43  	Sources []int // Indices in StackSet.Sources (callers before callees).
    44  }
    45  
    46  // StackSource holds function/location info for a stack entry.
    47  type StackSource struct {
    48  	FullName   string
    49  	FileName   string
    50  	UniqueName string // Disambiguates functions with same names
    51  	Inlined    bool   // If true this source was inlined into its caller
    52  
    53  	// Alternative names to display (with decreasing lengths) to make text fit.
    54  	// Guaranteed to be non-empty.
    55  	Display []string
    56  
    57  	// Regular expression (anchored) that matches exactly FullName.
    58  	RE string
    59  
    60  	// Places holds the list of stack slots where this source occurs.
    61  	// In particular, if [a,b] is an element in Places,
    62  	// StackSet.Stacks[a].Sources[b] points to this source.
    63  	//
    64  	// No stack will be referenced twice in the Places slice for a given
    65  	// StackSource. In case of recursion, Places will contain the outer-most
    66  	// entry in the recursive stack. E.g., if stack S has source X at positions
    67  	// 4,6,9,10, the Places entry for X will contain [S,4].
    68  	Places []StackSlot
    69  
    70  	// Combined count of stacks where this source is the leaf.
    71  	Self int64
    72  
    73  	// Color number to use for this source.
    74  	// Colors with high numbers than supported may be treated as zero.
    75  	Color int
    76  }
    77  
    78  // StackSlot identifies a particular StackSlot.
    79  type StackSlot struct {
    80  	Stack int // Index in StackSet.Stacks
    81  	Pos   int // Index in Stack.Sources
    82  }
    83  
    84  // Stacks returns a StackSet for the profile in rpt.
    85  func (rpt *Report) Stacks() StackSet {
    86  	// Get scale for converting to default unit of the right type.
    87  	scale, unit := measurement.Scale(1, rpt.options.SampleUnit, "default")
    88  	if unit == "default" {
    89  		unit = ""
    90  	}
    91  	if rpt.options.Ratio > 0 {
    92  		scale *= rpt.options.Ratio
    93  	}
    94  	s := &StackSet{
    95  		Total:   rpt.total,
    96  		Scale:   scale,
    97  		Type:    rpt.options.SampleType,
    98  		Unit:    unit,
    99  		Stacks:  []Stack{},       // Ensure non-nil
   100  		Sources: []StackSource{}, // Ensure non-nil
   101  	}
   102  	s.makeInitialStacks(rpt)
   103  	s.fillPlaces()
   104  	s.assignColors()
   105  	return *s
   106  }
   107  
   108  func (s *StackSet) makeInitialStacks(rpt *Report) {
   109  	type key struct {
   110  		line    profile.Line
   111  		inlined bool
   112  	}
   113  	srcs := map[key]int{} // Sources identified so far.
   114  	seenFunctions := map[string]bool{}
   115  	unknownIndex := 1
   116  	getSrc := func(line profile.Line, inlined bool) int {
   117  		k := key{line, inlined}
   118  		if i, ok := srcs[k]; ok {
   119  			return i
   120  		}
   121  		x := StackSource{Places: []StackSlot{}} // Ensure Places is non-nil
   122  		if fn := line.Function; fn != nil {
   123  			x.FullName = fn.Name
   124  			x.FileName = fn.Filename
   125  			if !seenFunctions[fn.Name] {
   126  				x.UniqueName = fn.Name
   127  				seenFunctions[fn.Name] = true
   128  			} else {
   129  				// Assign a different name so pivoting picks this function.
   130  				x.UniqueName = fmt.Sprint(fn.Name, "#", fn.ID)
   131  			}
   132  		} else {
   133  			x.FullName = fmt.Sprintf("?%d?", unknownIndex)
   134  			x.UniqueName = x.FullName
   135  			unknownIndex++
   136  		}
   137  		x.Inlined = inlined
   138  		x.RE = "^" + regexp.QuoteMeta(x.UniqueName) + "$"
   139  		x.Display = shortNameList(x.FullName)
   140  		s.Sources = append(s.Sources, x)
   141  		srcs[k] = len(s.Sources) - 1
   142  		return len(s.Sources) - 1
   143  	}
   144  
   145  	// Synthesized root location that will be placed at the beginning of each stack.
   146  	s.Sources = []StackSource{{
   147  		FullName: "root",
   148  		Display:  []string{"root"},
   149  		Places:   []StackSlot{},
   150  	}}
   151  
   152  	for _, sample := range rpt.prof.Sample {
   153  		value := rpt.options.SampleValue(sample.Value)
   154  		stack := Stack{Value: value, Sources: []int{0}} // Start with the root
   155  
   156  		// Note: we need to reverse the order in the produced stack.
   157  		for i := len(sample.Location) - 1; i >= 0; i-- {
   158  			loc := sample.Location[i]
   159  			for j := len(loc.Line) - 1; j >= 0; j-- {
   160  				line := loc.Line[j]
   161  				inlined := (j != len(loc.Line)-1)
   162  				stack.Sources = append(stack.Sources, getSrc(line, inlined))
   163  			}
   164  		}
   165  
   166  		leaf := stack.Sources[len(stack.Sources)-1]
   167  		s.Sources[leaf].Self += value
   168  		s.Stacks = append(s.Stacks, stack)
   169  	}
   170  }
   171  
   172  func (s *StackSet) fillPlaces() {
   173  	for i, stack := range s.Stacks {
   174  		seenSrcs := map[int]bool{}
   175  		for j, src := range stack.Sources {
   176  			if seenSrcs[src] {
   177  				continue
   178  			}
   179  			seenSrcs[src] = true
   180  			s.Sources[src].Places = append(s.Sources[src].Places, StackSlot{i, j})
   181  		}
   182  	}
   183  }
   184  
   185  func (s *StackSet) assignColors() {
   186  	// Assign different color indices to different packages.
   187  	const numColors = 1048576
   188  	for i, src := range s.Sources {
   189  		pkg := packageName(src.FullName)
   190  		h := sha256.Sum256([]byte(pkg))
   191  		index := binary.LittleEndian.Uint32(h[:])
   192  		s.Sources[i].Color = int(index % numColors)
   193  	}
   194  }
   195  

View as plain text