...

Source file src/pkg/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		// BoolVar, IntVar, Float64Var, and StringVar define new flags referencing
    96		// a given pointer, like the functions of the same name in package flag.
    97		BoolVar(pointer *bool, name string, def bool, usage string)
    98		IntVar(pointer *int, name string, def int, usage string)
    99		Float64Var(pointer *float64, name string, def float64, usage string)
   100		StringVar(pointer *string, name string, def string, usage string)
   101	
   102		// StringList is similar to String but allows multiple values for a
   103		// single flag
   104		StringList(name string, def string, usage string) *[]*string
   105	
   106		// ExtraUsage returns any additional text that should be printed after the
   107		// standard usage message. The extra usage message returned includes all text
   108		// added with AddExtraUsage().
   109		// The typical use of ExtraUsage is to show any custom flags defined by the
   110		// specific pprof plugins being used.
   111		ExtraUsage() string
   112	
   113		// AddExtraUsage appends additional text to the end of the extra usage message.
   114		AddExtraUsage(eu string)
   115	
   116		// Parse initializes the flags with their values for this run
   117		// and returns the non-flag command line arguments.
   118		// If an unknown flag is encountered or there are no arguments,
   119		// Parse should call usage and return nil.
   120		Parse(usage func()) []string
   121	}
   122	
   123	// A Fetcher reads and returns the profile named by src, using
   124	// the specified duration and timeout. It returns the fetched
   125	// profile and a string indicating a URL from where the profile
   126	// was fetched, which may be different than src.
   127	type Fetcher interface {
   128		Fetch(src string, duration, timeout time.Duration) (*profile.Profile, string, error)
   129	}
   130	
   131	// A Symbolizer introduces symbol information into a profile.
   132	type Symbolizer interface {
   133		Symbolize(mode string, srcs MappingSources, prof *profile.Profile) error
   134	}
   135	
   136	// MappingSources map each profile.Mapping to the source of the profile.
   137	// The key is either Mapping.File or Mapping.BuildId.
   138	type MappingSources map[string][]struct {
   139		Source string // URL of the source the mapping was collected from
   140		Start  uint64 // delta applied to addresses from this source (to represent Merge adjustments)
   141	}
   142	
   143	// An ObjTool inspects shared libraries and executable files.
   144	type ObjTool interface {
   145		// Open opens the named object file. If the object is a shared
   146		// library, start/limit/offset are the addresses where it is mapped
   147		// into memory in the address space being inspected.
   148		Open(file string, start, limit, offset uint64) (ObjFile, error)
   149	
   150		// Disasm disassembles the named object file, starting at
   151		// the start address and stopping at (before) the end address.
   152		Disasm(file string, start, end uint64) ([]Inst, error)
   153	}
   154	
   155	// An Inst is a single instruction in an assembly listing.
   156	type Inst struct {
   157		Addr     uint64 // virtual address of instruction
   158		Text     string // instruction text
   159		Function string // function name
   160		File     string // source file
   161		Line     int    // source line
   162	}
   163	
   164	// An ObjFile is a single object file: a shared library or executable.
   165	type ObjFile interface {
   166		// Name returns the underlying file name, if available.
   167		Name() string
   168	
   169		// Base returns the base address to use when looking up symbols in the file.
   170		Base() uint64
   171	
   172		// BuildID returns the GNU build ID of the file, or an empty string.
   173		BuildID() string
   174	
   175		// SourceLine reports the source line information for a given
   176		// address in the file. Due to inlining, the source line information
   177		// is in general a list of positions representing a call stack,
   178		// with the leaf function first.
   179		SourceLine(addr uint64) ([]Frame, error)
   180	
   181		// Symbols returns a list of symbols in the object file.
   182		// If r is not nil, Symbols restricts the list to symbols
   183		// with names matching the regular expression.
   184		// If addr is not zero, Symbols restricts the list to symbols
   185		// containing that address.
   186		Symbols(r *regexp.Regexp, addr uint64) ([]*Sym, error)
   187	
   188		// Close closes the file, releasing associated resources.
   189		Close() error
   190	}
   191	
   192	// A Frame describes a single line in a source file.
   193	type Frame struct {
   194		Func string // name of function
   195		File string // source file name
   196		Line int    // line in file
   197	}
   198	
   199	// A Sym describes a single symbol in an object file.
   200	type Sym struct {
   201		Name  []string // names of symbol (many if symbol was dedup'ed)
   202		File  string   // object file containing symbol
   203		Start uint64   // start virtual address
   204		End   uint64   // virtual address of last byte in sym (Start+size-1)
   205	}
   206	
   207	// A UI manages user interactions.
   208	type UI interface {
   209		// Read returns a line of text (a command) read from the user.
   210		// prompt is printed before reading the command.
   211		ReadLine(prompt string) (string, error)
   212	
   213		// Print shows a message to the user.
   214		// It formats the text as fmt.Print would and adds a final \n if not already present.
   215		// For line-based UI, Print writes to standard error.
   216		// (Standard output is reserved for report data.)
   217		Print(...interface{})
   218	
   219		// PrintErr shows an error message to the user.
   220		// It formats the text as fmt.Print would and adds a final \n if not already present.
   221		// For line-based UI, PrintErr writes to standard error.
   222		PrintErr(...interface{})
   223	
   224		// IsTerminal returns whether the UI is known to be tied to an
   225		// interactive terminal (as opposed to being redirected to a file).
   226		IsTerminal() bool
   227	
   228		// WantBrowser indicates whether browser should be opened with the -http option.
   229		WantBrowser() bool
   230	
   231		// SetAutoComplete instructs the UI to call complete(cmd) to obtain
   232		// the auto-completion of cmd, if the UI supports auto-completion at all.
   233		SetAutoComplete(complete func(string) string)
   234	}
   235	
   236	// internalObjTool is a wrapper to map from the pprof external
   237	// interface to the internal interface.
   238	type internalObjTool struct {
   239		ObjTool
   240	}
   241	
   242	func (o *internalObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
   243		f, err := o.ObjTool.Open(file, start, limit, offset)
   244		if err != nil {
   245			return nil, err
   246		}
   247		return &internalObjFile{f}, err
   248	}
   249	
   250	type internalObjFile struct {
   251		ObjFile
   252	}
   253	
   254	func (f *internalObjFile) SourceLine(frame uint64) ([]plugin.Frame, error) {
   255		frames, err := f.ObjFile.SourceLine(frame)
   256		if err != nil {
   257			return nil, err
   258		}
   259		var pluginFrames []plugin.Frame
   260		for _, f := range frames {
   261			pluginFrames = append(pluginFrames, plugin.Frame(f))
   262		}
   263		return pluginFrames, nil
   264	}
   265	
   266	func (f *internalObjFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
   267		syms, err := f.ObjFile.Symbols(r, addr)
   268		if err != nil {
   269			return nil, err
   270		}
   271		var pluginSyms []*plugin.Sym
   272		for _, s := range syms {
   273			ps := plugin.Sym(*s)
   274			pluginSyms = append(pluginSyms, &ps)
   275		}
   276		return pluginSyms, nil
   277	}
   278	
   279	func (o *internalObjTool) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
   280		insts, err := o.ObjTool.Disasm(file, start, end)
   281		if err != nil {
   282			return nil, err
   283		}
   284		var pluginInst []plugin.Inst
   285		for _, inst := range insts {
   286			pluginInst = append(pluginInst, plugin.Inst(inst))
   287		}
   288		return pluginInst, nil
   289	}
   290	
   291	// internalSymbolizer is a wrapper to map from the pprof external
   292	// interface to the internal interface.
   293	type internalSymbolizer struct {
   294		Symbolizer
   295	}
   296	
   297	func (s *internalSymbolizer) Symbolize(mode string, srcs plugin.MappingSources, prof *profile.Profile) error {
   298		isrcs := MappingSources{}
   299		for m, s := range srcs {
   300			isrcs[m] = s
   301		}
   302		return s.Symbolizer.Symbolize(mode, isrcs, prof)
   303	}
   304	

View as plain text