Source file src/cmd/vendor/github.com/google/pprof/driver/driver.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  // Package driver provides an external entry point to the pprof driver.
    16  package driver
    17  
    18  import (
    19  	"io"
    20  	"net/http"
    21  	"regexp"
    22  	"time"
    23  
    24  	internaldriver "github.com/google/pprof/internal/driver"
    25  	"github.com/google/pprof/internal/plugin"
    26  	"github.com/google/pprof/profile"
    27  )
    28  
    29  // PProf acquires a profile, and symbolizes it using a profile
    30  // manager. Then it generates a report formatted according to the
    31  // options selected through the flags package.
    32  func PProf(o *Options) error {
    33  	return internaldriver.PProf(o.internalOptions())
    34  }
    35  
    36  func (o *Options) internalOptions() *plugin.Options {
    37  	var obj plugin.ObjTool
    38  	if o.Obj != nil {
    39  		obj = &internalObjTool{o.Obj}
    40  	}
    41  	var sym plugin.Symbolizer
    42  	if o.Sym != nil {
    43  		sym = &internalSymbolizer{o.Sym}
    44  	}
    45  	var httpServer func(args *plugin.HTTPServerArgs) error
    46  	if o.HTTPServer != nil {
    47  		httpServer = func(args *plugin.HTTPServerArgs) error {
    48  			return o.HTTPServer(((*HTTPServerArgs)(args)))
    49  		}
    50  	}
    51  	return &plugin.Options{
    52  		Writer:        o.Writer,
    53  		Flagset:       o.Flagset,
    54  		Fetch:         o.Fetch,
    55  		Sym:           sym,
    56  		Obj:           obj,
    57  		UI:            o.UI,
    58  		HTTPServer:    httpServer,
    59  		HTTPTransport: o.HTTPTransport,
    60  	}
    61  }
    62  
    63  // HTTPServerArgs contains arguments needed by an HTTP server that
    64  // is exporting a pprof web interface.
    65  type HTTPServerArgs plugin.HTTPServerArgs
    66  
    67  // Options groups all the optional plugins into pprof.
    68  type Options struct {
    69  	Writer        Writer
    70  	Flagset       FlagSet
    71  	Fetch         Fetcher
    72  	Sym           Symbolizer
    73  	Obj           ObjTool
    74  	UI            UI
    75  	HTTPServer    func(*HTTPServerArgs) error
    76  	HTTPTransport http.RoundTripper
    77  }
    78  
    79  // Writer provides a mechanism to write data under a certain name,
    80  // typically a filename.
    81  type Writer interface {
    82  	Open(name string) (io.WriteCloser, error)
    83  }
    84  
    85  // A FlagSet creates and parses command-line flags.
    86  // It is similar to the standard flag.FlagSet.
    87  type FlagSet interface {
    88  	// Bool, Int, Float64, and String define new flags,
    89  	// like the functions of the same name in package flag.
    90  	Bool(name string, def bool, usage string) *bool
    91  	Int(name string, def int, usage string) *int
    92  	Float64(name string, def float64, usage string) *float64
    93  	String(name string, def string, usage string) *string
    94  
    95  	// StringList is similar to String but allows multiple values for a
    96  	// single flag
    97  	StringList(name string, def string, usage string) *[]*string
    98  
    99  	// ExtraUsage returns any additional text that should be printed after the
   100  	// standard usage message. The extra usage message returned includes all text
   101  	// added with AddExtraUsage().
   102  	// The typical use of ExtraUsage is to show any custom flags defined by the
   103  	// specific pprof plugins being used.
   104  	ExtraUsage() string
   105  
   106  	// AddExtraUsage appends additional text to the end of the extra usage message.
   107  	AddExtraUsage(eu string)
   108  
   109  	// Parse initializes the flags with their values for this run
   110  	// and returns the non-flag command line arguments.
   111  	// If an unknown flag is encountered or there are no arguments,
   112  	// Parse should call usage and return nil.
   113  	Parse(usage func()) []string
   114  }
   115  
   116  // A Fetcher reads and returns the profile named by src, using
   117  // the specified duration and timeout. It returns the fetched
   118  // profile and a string indicating a URL from where the profile
   119  // was fetched, which may be different than src.
   120  type Fetcher interface {
   121  	Fetch(src string, duration, timeout time.Duration) (*profile.Profile, string, error)
   122  }
   123  
   124  // A Symbolizer introduces symbol information into a profile.
   125  type Symbolizer interface {
   126  	Symbolize(mode string, srcs MappingSources, prof *profile.Profile) error
   127  }
   128  
   129  // MappingSources map each profile.Mapping to the source of the profile.
   130  // The key is either Mapping.File or Mapping.BuildId.
   131  type MappingSources map[string][]struct {
   132  	Source string // URL of the source the mapping was collected from
   133  	Start  uint64 // delta applied to addresses from this source (to represent Merge adjustments)
   134  }
   135  
   136  // An ObjTool inspects shared libraries and executable files.
   137  type ObjTool interface {
   138  	// Open opens the named object file. If the object is a shared
   139  	// library, start/limit/offset are the addresses where it is mapped
   140  	// into memory in the address space being inspected. If the object
   141  	// is a linux kernel, relocationSymbol is the name of the symbol
   142  	// corresponding to the start address.
   143  	Open(file string, start, limit, offset uint64, relocationSymbol string) (ObjFile, error)
   144  
   145  	// Disasm disassembles the named object file, starting at
   146  	// the start address and stopping at (before) the end address.
   147  	Disasm(file string, start, end uint64, intelSyntax bool) ([]Inst, error)
   148  }
   149  
   150  // An Inst is a single instruction in an assembly listing.
   151  type Inst struct {
   152  	Addr     uint64 // virtual address of instruction
   153  	Text     string // instruction text
   154  	Function string // function name
   155  	File     string // source file
   156  	Line     int    // source line
   157  }
   158  
   159  // An ObjFile is a single object file: a shared library or executable.
   160  type ObjFile interface {
   161  	// Name returns the underlying file name, if available.
   162  	Name() string
   163  
   164  	// ObjAddr returns the objdump address corresponding to a runtime address.
   165  	ObjAddr(addr uint64) (uint64, error)
   166  
   167  	// BuildID returns the GNU build ID of the file, or an empty string.
   168  	BuildID() string
   169  
   170  	// SourceLine reports the source line information for a given
   171  	// address in the file. Due to inlining, the source line information
   172  	// is in general a list of positions representing a call stack,
   173  	// with the leaf function first.
   174  	SourceLine(addr uint64) ([]Frame, error)
   175  
   176  	// Symbols returns a list of symbols in the object file.
   177  	// If r is not nil, Symbols restricts the list to symbols
   178  	// with names matching the regular expression.
   179  	// If addr is not zero, Symbols restricts the list to symbols
   180  	// containing that address.
   181  	Symbols(r *regexp.Regexp, addr uint64) ([]*Sym, error)
   182  
   183  	// Close closes the file, releasing associated resources.
   184  	Close() error
   185  }
   186  
   187  // A Frame describes a single line in a source file.
   188  type Frame struct {
   189  	Func string // name of function
   190  	File string // source file name
   191  	Line int    // line in file
   192  }
   193  
   194  // A Sym describes a single symbol in an object file.
   195  type Sym struct {
   196  	Name  []string // names of symbol (many if symbol was dedup'ed)
   197  	File  string   // object file containing symbol
   198  	Start uint64   // start virtual address
   199  	End   uint64   // virtual address of last byte in sym (Start+size-1)
   200  }
   201  
   202  // A UI manages user interactions.
   203  type UI interface {
   204  	// Read returns a line of text (a command) read from the user.
   205  	// prompt is printed before reading the command.
   206  	ReadLine(prompt string) (string, error)
   207  
   208  	// Print shows a message to the user.
   209  	// It formats the text as fmt.Print would and adds a final \n if not already present.
   210  	// For line-based UI, Print writes to standard error.
   211  	// (Standard output is reserved for report data.)
   212  	Print(...interface{})
   213  
   214  	// PrintErr shows an error message to the user.
   215  	// It formats the text as fmt.Print would and adds a final \n if not already present.
   216  	// For line-based UI, PrintErr writes to standard error.
   217  	PrintErr(...interface{})
   218  
   219  	// IsTerminal returns whether the UI is known to be tied to an
   220  	// interactive terminal (as opposed to being redirected to a file).
   221  	IsTerminal() bool
   222  
   223  	// WantBrowser indicates whether browser should be opened with the -http option.
   224  	WantBrowser() bool
   225  
   226  	// SetAutoComplete instructs the UI to call complete(cmd) to obtain
   227  	// the auto-completion of cmd, if the UI supports auto-completion at all.
   228  	SetAutoComplete(complete func(string) string)
   229  }
   230  
   231  // internalObjTool is a wrapper to map from the pprof external
   232  // interface to the internal interface.
   233  type internalObjTool struct {
   234  	ObjTool
   235  }
   236  
   237  func (o *internalObjTool) Open(file string, start, limit, offset uint64, relocationSymbol string) (plugin.ObjFile, error) {
   238  	f, err := o.ObjTool.Open(file, start, limit, offset, relocationSymbol)
   239  	if err != nil {
   240  		return nil, err
   241  	}
   242  	return &internalObjFile{f}, err
   243  }
   244  
   245  type internalObjFile struct {
   246  	ObjFile
   247  }
   248  
   249  func (f *internalObjFile) SourceLine(frame uint64) ([]plugin.Frame, error) {
   250  	frames, err := f.ObjFile.SourceLine(frame)
   251  	if err != nil {
   252  		return nil, err
   253  	}
   254  	var pluginFrames []plugin.Frame
   255  	for _, f := range frames {
   256  		pluginFrames = append(pluginFrames, plugin.Frame(f))
   257  	}
   258  	return pluginFrames, nil
   259  }
   260  
   261  func (f *internalObjFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
   262  	syms, err := f.ObjFile.Symbols(r, addr)
   263  	if err != nil {
   264  		return nil, err
   265  	}
   266  	var pluginSyms []*plugin.Sym
   267  	for _, s := range syms {
   268  		ps := plugin.Sym(*s)
   269  		pluginSyms = append(pluginSyms, &ps)
   270  	}
   271  	return pluginSyms, nil
   272  }
   273  
   274  func (o *internalObjTool) Disasm(file string, start, end uint64, intelSyntax bool) ([]plugin.Inst, error) {
   275  	insts, err := o.ObjTool.Disasm(file, start, end, intelSyntax)
   276  	if err != nil {
   277  		return nil, err
   278  	}
   279  	var pluginInst []plugin.Inst
   280  	for _, inst := range insts {
   281  		pluginInst = append(pluginInst, plugin.Inst(inst))
   282  	}
   283  	return pluginInst, nil
   284  }
   285  
   286  // internalSymbolizer is a wrapper to map from the pprof external
   287  // interface to the internal interface.
   288  type internalSymbolizer struct {
   289  	Symbolizer
   290  }
   291  
   292  func (s *internalSymbolizer) Symbolize(mode string, srcs plugin.MappingSources, prof *profile.Profile) error {
   293  	isrcs := MappingSources{}
   294  	for m, s := range srcs {
   295  		isrcs[m] = s
   296  	}
   297  	return s.Symbolizer.Symbolize(mode, isrcs, prof)
   298  }
   299  

View as plain text