Source file src/cmd/vendor/github.com/google/pprof/profile/prune.go

     1  // Copyright 2014 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  // Implements methods to remove frames from profiles.
    16  
    17  package profile
    18  
    19  import (
    20  	"fmt"
    21  	"regexp"
    22  	"strings"
    23  )
    24  
    25  var (
    26  	reservedNames = []string{"(anonymous namespace)", "operator()"}
    27  	bracketRx     = func() *regexp.Regexp {
    28  		var quotedNames []string
    29  		for _, name := range append(reservedNames, "(") {
    30  			quotedNames = append(quotedNames, regexp.QuoteMeta(name))
    31  		}
    32  		return regexp.MustCompile(strings.Join(quotedNames, "|"))
    33  	}()
    34  )
    35  
    36  // simplifyFunc does some primitive simplification of function names.
    37  func simplifyFunc(f string) string {
    38  	// Account for leading '.' on the PPC ELF v1 ABI.
    39  	funcName := strings.TrimPrefix(f, ".")
    40  	// Account for unsimplified names -- try  to remove the argument list by trimming
    41  	// starting from the first '(', but skipping reserved names that have '('.
    42  	for _, ind := range bracketRx.FindAllStringSubmatchIndex(funcName, -1) {
    43  		foundReserved := false
    44  		for _, res := range reservedNames {
    45  			if funcName[ind[0]:ind[1]] == res {
    46  				foundReserved = true
    47  				break
    48  			}
    49  		}
    50  		if !foundReserved {
    51  			funcName = funcName[:ind[0]]
    52  			break
    53  		}
    54  	}
    55  	return funcName
    56  }
    57  
    58  // Prune removes all nodes beneath a node matching dropRx, and not
    59  // matching keepRx. If the root node of a Sample matches, the sample
    60  // will have an empty stack.
    61  func (p *Profile) Prune(dropRx, keepRx *regexp.Regexp) {
    62  	prune := make(map[uint64]bool)
    63  	pruneBeneath := make(map[uint64]bool)
    64  
    65  	// simplifyFunc can be expensive, so cache results.
    66  	// Note that the same function name can be encountered many times due
    67  	// different lines and addresses in the same function.
    68  	pruneCache := map[string]bool{} // Map from function to whether or not to prune
    69  	pruneFromHere := func(s string) bool {
    70  		if r, ok := pruneCache[s]; ok {
    71  			return r
    72  		}
    73  		funcName := simplifyFunc(s)
    74  		if dropRx.MatchString(funcName) {
    75  			if keepRx == nil || !keepRx.MatchString(funcName) {
    76  				pruneCache[s] = true
    77  				return true
    78  			}
    79  		}
    80  		pruneCache[s] = false
    81  		return false
    82  	}
    83  
    84  	for _, loc := range p.Location {
    85  		var i int
    86  		for i = len(loc.Line) - 1; i >= 0; i-- {
    87  			if fn := loc.Line[i].Function; fn != nil && fn.Name != "" {
    88  				if pruneFromHere(fn.Name) {
    89  					break
    90  				}
    91  			}
    92  		}
    93  
    94  		if i >= 0 {
    95  			// Found matching entry to prune.
    96  			pruneBeneath[loc.ID] = true
    97  
    98  			// Remove the matching location.
    99  			if i == len(loc.Line)-1 {
   100  				// Matched the top entry: prune the whole location.
   101  				prune[loc.ID] = true
   102  			} else {
   103  				loc.Line = loc.Line[i+1:]
   104  			}
   105  		}
   106  	}
   107  
   108  	// Prune locs from each Sample
   109  	for _, sample := range p.Sample {
   110  		// Scan from the root to the leaves to find the prune location.
   111  		// Do not prune frames before the first user frame, to avoid
   112  		// pruning everything.
   113  		foundUser := false
   114  		for i := len(sample.Location) - 1; i >= 0; i-- {
   115  			id := sample.Location[i].ID
   116  			if !prune[id] && !pruneBeneath[id] {
   117  				foundUser = true
   118  				continue
   119  			}
   120  			if !foundUser {
   121  				continue
   122  			}
   123  			if prune[id] {
   124  				sample.Location = sample.Location[i+1:]
   125  				break
   126  			}
   127  			if pruneBeneath[id] {
   128  				sample.Location = sample.Location[i:]
   129  				break
   130  			}
   131  		}
   132  	}
   133  }
   134  
   135  // RemoveUninteresting prunes and elides profiles using built-in
   136  // tables of uninteresting function names.
   137  func (p *Profile) RemoveUninteresting() error {
   138  	var keep, drop *regexp.Regexp
   139  	var err error
   140  
   141  	if p.DropFrames != "" {
   142  		if drop, err = regexp.Compile("^(" + p.DropFrames + ")$"); err != nil {
   143  			return fmt.Errorf("failed to compile regexp %s: %v", p.DropFrames, err)
   144  		}
   145  		if p.KeepFrames != "" {
   146  			if keep, err = regexp.Compile("^(" + p.KeepFrames + ")$"); err != nil {
   147  				return fmt.Errorf("failed to compile regexp %s: %v", p.KeepFrames, err)
   148  			}
   149  		}
   150  		p.Prune(drop, keep)
   151  	}
   152  	return nil
   153  }
   154  
   155  // PruneFrom removes all nodes beneath the lowest node matching dropRx, not including itself.
   156  //
   157  // Please see the example below to understand this method as well as
   158  // the difference from Prune method.
   159  //
   160  // A sample contains Location of [A,B,C,B,D] where D is the top frame and there's no inline.
   161  //
   162  // PruneFrom(A) returns [A,B,C,B,D] because there's no node beneath A.
   163  // Prune(A, nil) returns [B,C,B,D] by removing A itself.
   164  //
   165  // PruneFrom(B) returns [B,C,B,D] by removing all nodes beneath the first B when scanning from the bottom.
   166  // Prune(B, nil) returns [D] because a matching node is found by scanning from the root.
   167  func (p *Profile) PruneFrom(dropRx *regexp.Regexp) {
   168  	pruneBeneath := make(map[uint64]bool)
   169  
   170  	for _, loc := range p.Location {
   171  		for i := 0; i < len(loc.Line); i++ {
   172  			if fn := loc.Line[i].Function; fn != nil && fn.Name != "" {
   173  				funcName := simplifyFunc(fn.Name)
   174  				if dropRx.MatchString(funcName) {
   175  					// Found matching entry to prune.
   176  					pruneBeneath[loc.ID] = true
   177  					loc.Line = loc.Line[i:]
   178  					break
   179  				}
   180  			}
   181  		}
   182  	}
   183  
   184  	// Prune locs from each Sample
   185  	for _, sample := range p.Sample {
   186  		// Scan from the bottom leaf to the root to find the prune location.
   187  		for i, loc := range sample.Location {
   188  			if pruneBeneath[loc.ID] {
   189  				sample.Location = sample.Location[i:]
   190  				break
   191  			}
   192  		}
   193  	}
   194  }
   195  

View as plain text