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  	Column int    // column in file
   193  }
   194  
   195  // A Sym describes a single symbol in an object file.
   196  type Sym struct {
   197  	Name  []string // names of symbol (many if symbol was dedup'ed)
   198  	File  string   // object file containing symbol
   199  	Start uint64   // start virtual address
   200  	End   uint64   // virtual address of last byte in sym (Start+size-1)
   201  }
   202  
   203  // A UI manages user interactions.
   204  type UI interface {
   205  	// ReadLine returns a line of text (a command) read from the user.
   206  	// prompt is printed before reading the command.
   207  	ReadLine(prompt string) (string, error)
   208  
   209  	// Print shows a message to the user.
   210  	// It formats the text as fmt.Print would and adds a final \n if not already present.
   211  	// For line-based UI, Print writes to standard error.
   212  	// (Standard output is reserved for report data.)
   213  	Print(...interface{})
   214  
   215  	// PrintErr shows an error message to the user.
   216  	// It formats the text as fmt.Print would and adds a final \n if not already present.
   217  	// For line-based UI, PrintErr writes to standard error.
   218  	PrintErr(...interface{})
   219  
   220  	// IsTerminal returns whether the UI is known to be tied to an
   221  	// interactive terminal (as opposed to being redirected to a file).
   222  	IsTerminal() bool
   223  
   224  	// WantBrowser indicates whether browser should be opened with the -http option.
   225  	WantBrowser() bool
   226  
   227  	// SetAutoComplete instructs the UI to call complete(cmd) to obtain
   228  	// the auto-completion of cmd, if the UI supports auto-completion at all.
   229  	SetAutoComplete(complete func(string) string)
   230  }
   231  
   232  // internalObjTool is a wrapper to map from the pprof external
   233  // interface to the internal interface.
   234  type internalObjTool struct {
   235  	ObjTool
   236  }
   237  
   238  func (o *internalObjTool) Open(file string, start, limit, offset uint64, relocationSymbol string) (plugin.ObjFile, error) {
   239  	f, err := o.ObjTool.Open(file, start, limit, offset, relocationSymbol)
   240  	if err != nil {
   241  		return nil, err
   242  	}
   243  	return &internalObjFile{f}, err
   244  }
   245  
   246  type internalObjFile struct {
   247  	ObjFile
   248  }
   249  
   250  func (f *internalObjFile) SourceLine(frame uint64) ([]plugin.Frame, error) {
   251  	frames, err := f.ObjFile.SourceLine(frame)
   252  	if err != nil {
   253  		return nil, err
   254  	}
   255  	var pluginFrames []plugin.Frame
   256  	for _, f := range frames {
   257  		pluginFrames = append(pluginFrames, plugin.Frame(f))
   258  	}
   259  	return pluginFrames, nil
   260  }
   261  
   262  func (f *internalObjFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
   263  	syms, err := f.ObjFile.Symbols(r, addr)
   264  	if err != nil {
   265  		return nil, err
   266  	}
   267  	var pluginSyms []*plugin.Sym
   268  	for _, s := range syms {
   269  		ps := plugin.Sym(*s)
   270  		pluginSyms = append(pluginSyms, &ps)
   271  	}
   272  	return pluginSyms, nil
   273  }
   274  
   275  func (o *internalObjTool) Disasm(file string, start, end uint64, intelSyntax bool) ([]plugin.Inst, error) {
   276  	insts, err := o.ObjTool.Disasm(file, start, end, intelSyntax)
   277  	if err != nil {
   278  		return nil, err
   279  	}
   280  	var pluginInst []plugin.Inst
   281  	for _, inst := range insts {
   282  		pluginInst = append(pluginInst, plugin.Inst(inst))
   283  	}
   284  	return pluginInst, nil
   285  }
   286  
   287  // internalSymbolizer is a wrapper to map from the pprof external
   288  // interface to the internal interface.
   289  type internalSymbolizer struct {
   290  	Symbolizer
   291  }
   292  
   293  func (s *internalSymbolizer) Symbolize(mode string, srcs plugin.MappingSources, prof *profile.Profile) error {
   294  	isrcs := MappingSources{}
   295  	for m, s := range srcs {
   296  		isrcs[m] = s
   297  	}
   298  	return s.Symbolizer.Symbolize(mode, isrcs, prof)
   299  }
   300  

View as plain text