暂无描述

report.go 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. // Package report summarizes a performance profile into a
  15. // human-readable report.
  16. package report
  17. import (
  18. "fmt"
  19. "io"
  20. "math"
  21. "path/filepath"
  22. "regexp"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "text/tabwriter"
  27. "time"
  28. "github.com/google/pprof/internal/graph"
  29. "github.com/google/pprof/internal/measurement"
  30. "github.com/google/pprof/internal/plugin"
  31. "github.com/google/pprof/profile"
  32. )
  33. // Output formats.
  34. const (
  35. Callgrind = iota
  36. Comments
  37. Dis
  38. Dot
  39. List
  40. Proto
  41. Raw
  42. Tags
  43. Text
  44. TopProto
  45. Traces
  46. Tree
  47. WebList
  48. )
  49. // Options are the formatting and filtering options used to generate a
  50. // profile.
  51. type Options struct {
  52. OutputFormat int
  53. CumSort bool
  54. CallTree bool
  55. DropNegative bool
  56. PositivePercentages bool
  57. CompactLabels bool
  58. Ratio float64
  59. Title string
  60. ProfileLabels []string
  61. NodeCount int
  62. NodeFraction float64
  63. EdgeFraction float64
  64. SampleValue func(s []int64) int64
  65. SampleMeanDivisor func(s []int64) int64
  66. SampleType string
  67. SampleUnit string // Unit for the sample data from the profile.
  68. OutputUnit string // Units for data formatting in report.
  69. Symbol *regexp.Regexp // Symbols to include on disassembly report.
  70. SourcePath string // Search path for source files.
  71. }
  72. // Generate generates a report as directed by the Report.
  73. func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  74. o := rpt.options
  75. switch o.OutputFormat {
  76. case Comments:
  77. return printComments(w, rpt)
  78. case Dot:
  79. return printDOT(w, rpt)
  80. case Tree:
  81. return printTree(w, rpt)
  82. case Text:
  83. return printText(w, rpt)
  84. case Traces:
  85. return printTraces(w, rpt)
  86. case Raw:
  87. fmt.Fprint(w, rpt.prof.String())
  88. return nil
  89. case Tags:
  90. return printTags(w, rpt)
  91. case Proto:
  92. return rpt.prof.Write(w)
  93. case TopProto:
  94. return printTopProto(w, rpt)
  95. case Dis:
  96. return printAssembly(w, rpt, obj)
  97. case List:
  98. return printSource(w, rpt)
  99. case WebList:
  100. return printWebSource(w, rpt, obj)
  101. case Callgrind:
  102. return printCallgrind(w, rpt)
  103. }
  104. return fmt.Errorf("unexpected output format")
  105. }
  106. // newTrimmedGraph creates a graph for this report, trimmed according
  107. // to the report options.
  108. func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) {
  109. o := rpt.options
  110. // Build a graph and refine it. On each refinement step we must rebuild the graph from the samples,
  111. // as the graph itself doesn't contain enough information to preserve full precision.
  112. visualMode := o.OutputFormat == Dot
  113. cumSort := o.CumSort
  114. // The call_tree option is only honored when generating visual representations of the callgraph.
  115. callTree := o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind)
  116. // First step: Build complete graph to identify low frequency nodes, based on their cum weight.
  117. g = rpt.newGraph(nil)
  118. totalValue, _ := g.Nodes.Sum()
  119. nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction))
  120. edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction))
  121. // Filter out nodes with cum value below nodeCutoff.
  122. if nodeCutoff > 0 {
  123. if callTree {
  124. if nodesKept := g.DiscardLowFrequencyNodePtrs(nodeCutoff); len(g.Nodes) != len(nodesKept) {
  125. droppedNodes = len(g.Nodes) - len(nodesKept)
  126. g.TrimTree(nodesKept)
  127. }
  128. } else {
  129. if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) {
  130. droppedNodes = len(g.Nodes) - len(nodesKept)
  131. g = rpt.newGraph(nodesKept)
  132. }
  133. }
  134. }
  135. origCount = len(g.Nodes)
  136. // Second step: Limit the total number of nodes. Apply specialized heuristics to improve
  137. // visualization when generating dot output.
  138. g.SortNodes(cumSort, visualMode)
  139. if nodeCount := o.NodeCount; nodeCount > 0 {
  140. // Remove low frequency tags and edges as they affect selection.
  141. g.TrimLowFrequencyTags(nodeCutoff)
  142. g.TrimLowFrequencyEdges(edgeCutoff)
  143. if callTree {
  144. if nodesKept := g.SelectTopNodePtrs(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
  145. g.TrimTree(nodesKept)
  146. g.SortNodes(cumSort, visualMode)
  147. }
  148. } else {
  149. if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
  150. g = rpt.newGraph(nodesKept)
  151. g.SortNodes(cumSort, visualMode)
  152. }
  153. }
  154. }
  155. // Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter
  156. // the graph.
  157. g.TrimLowFrequencyTags(nodeCutoff)
  158. droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff)
  159. if visualMode {
  160. g.RemoveRedundantEdges()
  161. }
  162. return
  163. }
  164. func (rpt *Report) selectOutputUnit(g *graph.Graph) {
  165. o := rpt.options
  166. // Select best unit for profile output.
  167. // Find the appropriate units for the smallest non-zero sample
  168. if o.OutputUnit != "minimum" || len(g.Nodes) == 0 {
  169. return
  170. }
  171. var minValue int64
  172. for _, n := range g.Nodes {
  173. nodeMin := abs64(n.FlatValue())
  174. if nodeMin == 0 {
  175. nodeMin = abs64(n.CumValue())
  176. }
  177. if nodeMin > 0 && (minValue == 0 || nodeMin < minValue) {
  178. minValue = nodeMin
  179. }
  180. }
  181. maxValue := rpt.total
  182. if minValue == 0 {
  183. minValue = maxValue
  184. }
  185. if r := o.Ratio; r > 0 && r != 1 {
  186. minValue = int64(float64(minValue) * r)
  187. maxValue = int64(float64(maxValue) * r)
  188. }
  189. _, minUnit := measurement.Scale(minValue, o.SampleUnit, "minimum")
  190. _, maxUnit := measurement.Scale(maxValue, o.SampleUnit, "minimum")
  191. unit := minUnit
  192. if minUnit != maxUnit && minValue*100 < maxValue && o.OutputFormat != Callgrind {
  193. // Minimum and maximum values have different units. Scale
  194. // minimum by 100 to use larger units, allowing minimum value to
  195. // be scaled down to 0.01, except for callgrind reports since
  196. // they can only represent integer values.
  197. _, unit = measurement.Scale(100*minValue, o.SampleUnit, "minimum")
  198. }
  199. if unit != "" {
  200. o.OutputUnit = unit
  201. } else {
  202. o.OutputUnit = o.SampleUnit
  203. }
  204. }
  205. // newGraph creates a new graph for this report. If nodes is non-nil,
  206. // only nodes whose info matches are included. Otherwise, all nodes
  207. // are included, without trimming.
  208. func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph {
  209. o := rpt.options
  210. // Clean up file paths using heuristics.
  211. prof := rpt.prof
  212. for _, f := range prof.Function {
  213. f.Filename = trimPath(f.Filename)
  214. }
  215. // Remove numeric tags not recognized by pprof.
  216. for _, s := range prof.Sample {
  217. numLabels := make(map[string][]int64, len(s.NumLabel))
  218. for k, v := range s.NumLabel {
  219. if k == "bytes" {
  220. numLabels[k] = append(numLabels[k], v...)
  221. }
  222. }
  223. s.NumLabel = numLabels
  224. }
  225. formatTag := func(v int64, key string) string {
  226. return measurement.ScaledLabel(v, key, o.OutputUnit)
  227. }
  228. gopt := &graph.Options{
  229. SampleValue: o.SampleValue,
  230. SampleMeanDivisor: o.SampleMeanDivisor,
  231. FormatTag: formatTag,
  232. CallTree: o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind),
  233. DropNegative: o.DropNegative,
  234. KeptNodes: nodes,
  235. }
  236. // Only keep binary names for disassembly-based reports, otherwise
  237. // remove it to allow merging of functions across binaries.
  238. switch o.OutputFormat {
  239. case Raw, List, WebList, Dis, Callgrind:
  240. gopt.ObjNames = true
  241. }
  242. return graph.New(rpt.prof, gopt)
  243. }
  244. func printTopProto(w io.Writer, rpt *Report) error {
  245. p := rpt.prof
  246. o := rpt.options
  247. g, _, _, _ := rpt.newTrimmedGraph()
  248. rpt.selectOutputUnit(g)
  249. out := profile.Profile{
  250. SampleType: []*profile.ValueType{
  251. {Type: "cum", Unit: o.OutputUnit},
  252. {Type: "flat", Unit: o.OutputUnit},
  253. },
  254. TimeNanos: p.TimeNanos,
  255. DurationNanos: p.DurationNanos,
  256. PeriodType: p.PeriodType,
  257. Period: p.Period,
  258. }
  259. functionMap := make(functionMap)
  260. for i, n := range g.Nodes {
  261. f := functionMap.FindOrAdd(n.Info)
  262. flat, cum := n.FlatValue(), n.CumValue()
  263. l := &profile.Location{
  264. ID: uint64(i + 1),
  265. Address: n.Info.Address,
  266. Line: []profile.Line{
  267. {
  268. Line: int64(n.Info.Lineno),
  269. Function: f,
  270. },
  271. },
  272. }
  273. fv, _ := measurement.Scale(flat, o.SampleUnit, o.OutputUnit)
  274. cv, _ := measurement.Scale(cum, o.SampleUnit, o.OutputUnit)
  275. s := &profile.Sample{
  276. Location: []*profile.Location{l},
  277. Value: []int64{int64(cv), int64(fv)},
  278. }
  279. out.Function = append(out.Function, f)
  280. out.Location = append(out.Location, l)
  281. out.Sample = append(out.Sample, s)
  282. }
  283. return out.Write(w)
  284. }
  285. type functionMap map[string]*profile.Function
  286. func (fm functionMap) FindOrAdd(ni graph.NodeInfo) *profile.Function {
  287. fName := fmt.Sprintf("%q%q%q%d", ni.Name, ni.OrigName, ni.File, ni.StartLine)
  288. if f := fm[fName]; f != nil {
  289. return f
  290. }
  291. f := &profile.Function{
  292. ID: uint64(len(fm) + 1),
  293. Name: ni.Name,
  294. SystemName: ni.OrigName,
  295. Filename: ni.File,
  296. StartLine: int64(ni.StartLine),
  297. }
  298. fm[fName] = f
  299. return f
  300. }
  301. // printAssembly prints an annotated assembly listing.
  302. func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  303. o := rpt.options
  304. prof := rpt.prof
  305. g := rpt.newGraph(nil)
  306. // If the regexp source can be parsed as an address, also match
  307. // functions that land on that address.
  308. var address *uint64
  309. if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
  310. address = &hex
  311. }
  312. fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
  313. symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
  314. symNodes := nodesPerSymbol(g.Nodes, symbols)
  315. // Sort function names for printing.
  316. var syms objSymbols
  317. for s := range symNodes {
  318. syms = append(syms, s)
  319. }
  320. sort.Sort(syms)
  321. // Correlate the symbols from the binary with the profile samples.
  322. for _, s := range syms {
  323. sns := symNodes[s]
  324. // Gather samples for this symbol.
  325. flatSum, cumSum := sns.Sum()
  326. // Get the function assembly.
  327. insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
  328. if err != nil {
  329. return err
  330. }
  331. ns := annotateAssembly(insts, sns, s.base)
  332. fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
  333. for _, name := range s.sym.Name[1:] {
  334. fmt.Fprintf(w, " AKA ======================== %s\n", name)
  335. }
  336. fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
  337. rpt.formatValue(flatSum), rpt.formatValue(cumSum),
  338. percentage(cumSum, rpt.total))
  339. function, file, line := "", "", 0
  340. for _, n := range ns {
  341. locStr := ""
  342. // Skip loc information if it hasn't changed from previous instruction.
  343. if n.function != function || n.file != file || n.line != line {
  344. function, file, line = n.function, n.file, n.line
  345. if n.function != "" {
  346. locStr = n.function + " "
  347. }
  348. if n.file != "" {
  349. locStr += n.file
  350. if n.line != 0 {
  351. locStr += fmt.Sprintf(":%d", n.line)
  352. }
  353. }
  354. }
  355. switch {
  356. case locStr == "":
  357. // No location info, just print the instruction.
  358. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  359. valueOrDot(n.flatValue(), rpt),
  360. valueOrDot(n.cumValue(), rpt),
  361. n.address, n.instruction,
  362. )
  363. case len(n.instruction) < 40:
  364. // Short instruction, print loc on the same line.
  365. fmt.Fprintf(w, "%10s %10s %10x: %-40s;%s\n",
  366. valueOrDot(n.flatValue(), rpt),
  367. valueOrDot(n.cumValue(), rpt),
  368. n.address, n.instruction,
  369. locStr,
  370. )
  371. default:
  372. // Long instruction, print loc on a separate line.
  373. fmt.Fprintf(w, "%74s;%s\n", "", locStr)
  374. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  375. valueOrDot(n.flatValue(), rpt),
  376. valueOrDot(n.cumValue(), rpt),
  377. n.address, n.instruction,
  378. )
  379. }
  380. }
  381. }
  382. return nil
  383. }
  384. // symbolsFromBinaries examines the binaries listed on the profile
  385. // that have associated samples, and identifies symbols matching rx.
  386. func symbolsFromBinaries(prof *profile.Profile, g *graph.Graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
  387. hasSamples := make(map[string]bool)
  388. // Only examine mappings that have samples that match the
  389. // regexp. This is an optimization to speed up pprof.
  390. for _, n := range g.Nodes {
  391. if name := n.Info.PrintableName(); rx.MatchString(name) && n.Info.Objfile != "" {
  392. hasSamples[n.Info.Objfile] = true
  393. }
  394. }
  395. // Walk all mappings looking for matching functions with samples.
  396. var objSyms []*objSymbol
  397. for _, m := range prof.Mapping {
  398. if !hasSamples[m.File] {
  399. if address == nil || !(m.Start <= *address && *address <= m.Limit) {
  400. continue
  401. }
  402. }
  403. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  404. if err != nil {
  405. fmt.Printf("%v\n", err)
  406. continue
  407. }
  408. // Find symbols in this binary matching the user regexp.
  409. var addr uint64
  410. if address != nil {
  411. addr = *address
  412. }
  413. msyms, err := f.Symbols(rx, addr)
  414. base := f.Base()
  415. f.Close()
  416. if err != nil {
  417. continue
  418. }
  419. for _, ms := range msyms {
  420. objSyms = append(objSyms,
  421. &objSymbol{
  422. sym: ms,
  423. base: base,
  424. },
  425. )
  426. }
  427. }
  428. return objSyms
  429. }
  430. // objSym represents a symbol identified from a binary. It includes
  431. // the SymbolInfo from the disasm package and the base that must be
  432. // added to correspond to sample addresses
  433. type objSymbol struct {
  434. sym *plugin.Sym
  435. base uint64
  436. }
  437. // objSymbols is a wrapper type to enable sorting of []*objSymbol.
  438. type objSymbols []*objSymbol
  439. func (o objSymbols) Len() int {
  440. return len(o)
  441. }
  442. func (o objSymbols) Less(i, j int) bool {
  443. if namei, namej := o[i].sym.Name[0], o[j].sym.Name[0]; namei != namej {
  444. return namei < namej
  445. }
  446. return o[i].sym.Start < o[j].sym.Start
  447. }
  448. func (o objSymbols) Swap(i, j int) {
  449. o[i], o[j] = o[j], o[i]
  450. }
  451. // nodesPerSymbol classifies nodes into a group of symbols.
  452. func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
  453. symNodes := make(map[*objSymbol]graph.Nodes)
  454. for _, s := range symbols {
  455. // Gather samples for this symbol.
  456. for _, n := range ns {
  457. address := n.Info.Address - s.base
  458. if address >= s.sym.Start && address < s.sym.End {
  459. symNodes[s] = append(symNodes[s], n)
  460. }
  461. }
  462. }
  463. return symNodes
  464. }
  465. type assemblyInstruction struct {
  466. address uint64
  467. instruction string
  468. function string
  469. file string
  470. line int
  471. flat, cum int64
  472. flatDiv, cumDiv int64
  473. startsBlock bool
  474. }
  475. func (a *assemblyInstruction) flatValue() int64 {
  476. if a.flatDiv != 0 {
  477. return a.flat / a.flatDiv
  478. }
  479. return a.flat
  480. }
  481. func (a *assemblyInstruction) cumValue() int64 {
  482. if a.cumDiv != 0 {
  483. return a.cum / a.cumDiv
  484. }
  485. return a.cum
  486. }
  487. // annotateAssembly annotates a set of assembly instructions with a
  488. // set of samples. It returns a set of nodes to display. base is an
  489. // offset to adjust the sample addresses.
  490. func annotateAssembly(insts []plugin.Inst, samples graph.Nodes, base uint64) []assemblyInstruction {
  491. // Add end marker to simplify printing loop.
  492. insts = append(insts, plugin.Inst{
  493. Addr: ^uint64(0),
  494. })
  495. // Ensure samples are sorted by address.
  496. samples.Sort(graph.AddressOrder)
  497. s := 0
  498. asm := make([]assemblyInstruction, 0, len(insts))
  499. for ix, in := range insts[:len(insts)-1] {
  500. n := assemblyInstruction{
  501. address: in.Addr,
  502. instruction: in.Text,
  503. function: in.Function,
  504. line: in.Line,
  505. }
  506. if in.File != "" {
  507. n.file = filepath.Base(in.File)
  508. }
  509. // Sum all the samples until the next instruction (to account
  510. // for samples attributed to the middle of an instruction).
  511. for next := insts[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
  512. sample := samples[s]
  513. n.flatDiv += sample.FlatDiv
  514. n.flat += sample.Flat
  515. n.cumDiv += sample.CumDiv
  516. n.cum += sample.Cum
  517. if f := sample.Info.File; f != "" && n.file == "" {
  518. n.file = filepath.Base(f)
  519. }
  520. if ln := sample.Info.Lineno; ln != 0 && n.line == 0 {
  521. n.line = ln
  522. }
  523. if f := sample.Info.Name; f != "" && n.function == "" {
  524. n.function = f
  525. }
  526. }
  527. asm = append(asm, n)
  528. }
  529. return asm
  530. }
  531. // valueOrDot formats a value according to a report, intercepting zero
  532. // values.
  533. func valueOrDot(value int64, rpt *Report) string {
  534. if value == 0 {
  535. return "."
  536. }
  537. return rpt.formatValue(value)
  538. }
  539. // printTags collects all tags referenced in the profile and prints
  540. // them in a sorted table.
  541. func printTags(w io.Writer, rpt *Report) error {
  542. p := rpt.prof
  543. o := rpt.options
  544. formatTag := func(v int64, key string) string {
  545. return measurement.ScaledLabel(v, key, o.OutputUnit)
  546. }
  547. // Hashtable to keep accumulate tags as key,value,count.
  548. tagMap := make(map[string]map[string]int64)
  549. for _, s := range p.Sample {
  550. for key, vals := range s.Label {
  551. for _, val := range vals {
  552. valueMap, ok := tagMap[key]
  553. if !ok {
  554. valueMap = make(map[string]int64)
  555. tagMap[key] = valueMap
  556. }
  557. valueMap[val] += o.SampleValue(s.Value)
  558. }
  559. }
  560. for key, vals := range s.NumLabel {
  561. for _, nval := range vals {
  562. val := formatTag(nval, key)
  563. valueMap, ok := tagMap[key]
  564. if !ok {
  565. valueMap = make(map[string]int64)
  566. tagMap[key] = valueMap
  567. }
  568. valueMap[val] += o.SampleValue(s.Value)
  569. }
  570. }
  571. }
  572. tagKeys := make([]*graph.Tag, 0, len(tagMap))
  573. for key := range tagMap {
  574. tagKeys = append(tagKeys, &graph.Tag{Name: key})
  575. }
  576. tabw := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.AlignRight)
  577. for _, tagKey := range graph.SortTags(tagKeys, true) {
  578. var total int64
  579. key := tagKey.Name
  580. tags := make([]*graph.Tag, 0, len(tagMap[key]))
  581. for t, c := range tagMap[key] {
  582. total += c
  583. tags = append(tags, &graph.Tag{Name: t, Flat: c})
  584. }
  585. f, u := measurement.Scale(total, o.SampleUnit, o.OutputUnit)
  586. fmt.Fprintf(tabw, "%s:\t Total %.1f%s\n", key, f, u)
  587. for _, t := range graph.SortTags(tags, true) {
  588. f, u := measurement.Scale(t.FlatValue(), o.SampleUnit, o.OutputUnit)
  589. if total > 0 {
  590. fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, percentage(t.FlatValue(), total), t.Name)
  591. } else {
  592. fmt.Fprintf(tabw, " \t%.1f%s:\t %s\n", f, u, t.Name)
  593. }
  594. }
  595. fmt.Fprintln(tabw)
  596. }
  597. return tabw.Flush()
  598. }
  599. // printComments prints all freeform comments in the profile.
  600. func printComments(w io.Writer, rpt *Report) error {
  601. p := rpt.prof
  602. for _, c := range p.Comments {
  603. fmt.Fprintln(w, c)
  604. }
  605. return nil
  606. }
  607. // printText prints a flat text report for a profile.
  608. func printText(w io.Writer, rpt *Report) error {
  609. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  610. rpt.selectOutputUnit(g)
  611. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  612. fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
  613. "flat", "flat", "sum", "cum", "cum")
  614. var flatSum int64
  615. for _, n := range g.Nodes {
  616. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  617. var inline, noinline bool
  618. for _, e := range n.In {
  619. if e.Inline {
  620. inline = true
  621. } else {
  622. noinline = true
  623. }
  624. }
  625. if inline {
  626. if noinline {
  627. name = name + " (partial-inline)"
  628. } else {
  629. name = name + " (inline)"
  630. }
  631. }
  632. flatSum += flat
  633. fmt.Fprintf(w, "%10s %s %s %10s %s %s\n",
  634. rpt.formatValue(flat),
  635. percentage(flat, rpt.total),
  636. percentage(flatSum, rpt.total),
  637. rpt.formatValue(cum),
  638. percentage(cum, rpt.total),
  639. name)
  640. }
  641. return nil
  642. }
  643. // printTraces prints all traces from a profile.
  644. func printTraces(w io.Writer, rpt *Report) error {
  645. fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))
  646. prof := rpt.prof
  647. o := rpt.options
  648. const separator = "-----------+-------------------------------------------------------"
  649. _, locations := graph.CreateNodes(prof, &graph.Options{})
  650. for _, sample := range prof.Sample {
  651. var stack graph.Nodes
  652. for _, loc := range sample.Location {
  653. id := loc.ID
  654. stack = append(stack, locations[id]...)
  655. }
  656. if len(stack) == 0 {
  657. continue
  658. }
  659. fmt.Fprintln(w, separator)
  660. // Print any text labels for the sample.
  661. var labels []string
  662. for s, vs := range sample.Label {
  663. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  664. }
  665. sort.Strings(labels)
  666. fmt.Fprint(w, strings.Join(labels, ""))
  667. var d, v int64
  668. v = o.SampleValue(sample.Value)
  669. if o.SampleMeanDivisor != nil {
  670. d = o.SampleMeanDivisor(sample.Value)
  671. }
  672. // Print call stack.
  673. if d != 0 {
  674. v = v / d
  675. }
  676. fmt.Fprintf(w, "%10s %s\n",
  677. rpt.formatValue(v), stack[0].Info.PrintableName())
  678. for _, s := range stack[1:] {
  679. fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName())
  680. }
  681. }
  682. fmt.Fprintln(w, separator)
  683. return nil
  684. }
  685. // printCallgrind prints a graph for a profile on callgrind format.
  686. func printCallgrind(w io.Writer, rpt *Report) error {
  687. o := rpt.options
  688. rpt.options.NodeFraction = 0
  689. rpt.options.EdgeFraction = 0
  690. rpt.options.NodeCount = 0
  691. g, _, _, _ := rpt.newTrimmedGraph()
  692. rpt.selectOutputUnit(g)
  693. nodeNames := getDisambiguatedNames(g)
  694. fmt.Fprintln(w, "positions: instr line")
  695. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  696. objfiles := make(map[string]int)
  697. files := make(map[string]int)
  698. names := make(map[string]int)
  699. // prevInfo points to the previous NodeInfo.
  700. // It is used to group cost lines together as much as possible.
  701. var prevInfo *graph.NodeInfo
  702. for _, n := range g.Nodes {
  703. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  704. fmt.Fprintln(w)
  705. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  706. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  707. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  708. }
  709. addr := callgrindAddress(prevInfo, n.Info.Address)
  710. sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
  711. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  712. // Print outgoing edges.
  713. for _, out := range n.Out.Sort() {
  714. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  715. callee := out.Dest
  716. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  717. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  718. // pprof doesn't have a flat weight for a call, leave as 0.
  719. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  720. // TODO: This address may be in the middle of a call
  721. // instruction. It would be best to find the beginning
  722. // of the instruction, but the tools seem to handle
  723. // this OK.
  724. fmt.Fprintf(w, "* * %d\n", int64(c))
  725. }
  726. prevInfo = &n.Info
  727. }
  728. return nil
  729. }
  730. // getDisambiguatedNames returns a map from each node in the graph to
  731. // the name to use in the callgrind output. Callgrind merges all
  732. // functions with the same [file name, function name]. Add a [%d/n]
  733. // suffix to disambiguate nodes with different values of
  734. // node.Function, which we want to keep separate. In particular, this
  735. // affects graphs created with --call_tree, where nodes from different
  736. // contexts are associated to different Functions.
  737. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  738. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  739. type names struct {
  740. file, function string
  741. }
  742. // nameFunctionIndex maps the callgrind names (filename, function)
  743. // to the node.Function values found for that name, and each
  744. // node.Function value to a sequential index to be used on the
  745. // disambiguated name.
  746. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  747. for _, n := range g.Nodes {
  748. nm := names{n.Info.File, n.Info.Name}
  749. p, ok := nameFunctionIndex[nm]
  750. if !ok {
  751. p = make(map[*graph.Node]int)
  752. nameFunctionIndex[nm] = p
  753. }
  754. if _, ok := p[n.Function]; !ok {
  755. p[n.Function] = len(p)
  756. }
  757. }
  758. for _, n := range g.Nodes {
  759. nm := names{n.Info.File, n.Info.Name}
  760. nodeName[n] = n.Info.Name
  761. if p := nameFunctionIndex[nm]; len(p) > 1 {
  762. // If there is more than one function, add suffix to disambiguate.
  763. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  764. }
  765. }
  766. return nodeName
  767. }
  768. // callgrindName implements the callgrind naming compression scheme.
  769. // For names not previously seen returns "(N) name", where N is a
  770. // unique index. For names previously seen returns "(N)" where N is
  771. // the index returned the first time.
  772. func callgrindName(names map[string]int, name string) string {
  773. if name == "" {
  774. return ""
  775. }
  776. if id, ok := names[name]; ok {
  777. return fmt.Sprintf("(%d)", id)
  778. }
  779. id := len(names) + 1
  780. names[name] = id
  781. return fmt.Sprintf("(%d) %s", id, name)
  782. }
  783. // callgrindAddress implements the callgrind subposition compression scheme if
  784. // possible. If prevInfo != nil, it contains the previous address. The current
  785. // address can be given relative to the previous address, with an explicit +/-
  786. // to indicate it is relative, or * for the same address.
  787. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  788. abs := fmt.Sprintf("%#x", curr)
  789. if prevInfo == nil {
  790. return abs
  791. }
  792. prev := prevInfo.Address
  793. if prev == curr {
  794. return "*"
  795. }
  796. diff := int64(curr - prev)
  797. relative := fmt.Sprintf("%+d", diff)
  798. // Only bother to use the relative address if it is actually shorter.
  799. if len(relative) < len(abs) {
  800. return relative
  801. }
  802. return abs
  803. }
  804. // printTree prints a tree-based report in text form.
  805. func printTree(w io.Writer, rpt *Report) error {
  806. const separator = "----------------------------------------------------------+-------------"
  807. const legend = " flat flat% sum% cum cum% calls calls% + context "
  808. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  809. rpt.selectOutputUnit(g)
  810. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  811. fmt.Fprintln(w, separator)
  812. fmt.Fprintln(w, legend)
  813. var flatSum int64
  814. rx := rpt.options.Symbol
  815. for _, n := range g.Nodes {
  816. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  817. // Skip any entries that do not match the regexp (for the "peek" command).
  818. if rx != nil && !rx.MatchString(name) {
  819. continue
  820. }
  821. fmt.Fprintln(w, separator)
  822. // Print incoming edges.
  823. inEdges := n.In.Sort()
  824. for _, in := range inEdges {
  825. var inline string
  826. if in.Inline {
  827. inline = " (inline)"
  828. }
  829. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  830. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  831. }
  832. // Print current node.
  833. flatSum += flat
  834. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  835. rpt.formatValue(flat),
  836. percentage(flat, rpt.total),
  837. percentage(flatSum, rpt.total),
  838. rpt.formatValue(cum),
  839. percentage(cum, rpt.total),
  840. name)
  841. // Print outgoing edges.
  842. outEdges := n.Out.Sort()
  843. for _, out := range outEdges {
  844. var inline string
  845. if out.Inline {
  846. inline = " (inline)"
  847. }
  848. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  849. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  850. }
  851. }
  852. if len(g.Nodes) > 0 {
  853. fmt.Fprintln(w, separator)
  854. }
  855. return nil
  856. }
  857. // printDOT prints an annotated callgraph in DOT format.
  858. func printDOT(w io.Writer, rpt *Report) error {
  859. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  860. rpt.selectOutputUnit(g)
  861. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  862. o := rpt.options
  863. formatTag := func(v int64, key string) string {
  864. return measurement.ScaledLabel(v, key, o.OutputUnit)
  865. }
  866. c := &graph.DotConfig{
  867. Title: rpt.options.Title,
  868. Labels: labels,
  869. FormatValue: rpt.formatValue,
  870. FormatTag: formatTag,
  871. Total: rpt.total,
  872. }
  873. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  874. return nil
  875. }
  876. // percentage computes the percentage of total of a value, and encodes
  877. // it as a string. At least two digits of precision are printed.
  878. func percentage(value, total int64) string {
  879. var ratio float64
  880. if total != 0 {
  881. ratio = math.Abs(float64(value)/float64(total)) * 100
  882. }
  883. switch {
  884. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  885. return " 100%"
  886. case math.Abs(ratio) >= 1.0:
  887. return fmt.Sprintf("%5.2f%%", ratio)
  888. default:
  889. return fmt.Sprintf("%5.2g%%", ratio)
  890. }
  891. }
  892. // ProfileLabels returns printable labels for a profile.
  893. func ProfileLabels(rpt *Report) []string {
  894. label := []string{}
  895. prof := rpt.prof
  896. o := rpt.options
  897. if len(prof.Mapping) > 0 {
  898. if prof.Mapping[0].File != "" {
  899. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  900. }
  901. if prof.Mapping[0].BuildID != "" {
  902. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  903. }
  904. }
  905. // Only include comments that do not start with '#'.
  906. for _, c := range prof.Comments {
  907. if !strings.HasPrefix(c, "#") {
  908. label = append(label, c)
  909. }
  910. }
  911. if o.SampleType != "" {
  912. label = append(label, "Type: "+o.SampleType)
  913. }
  914. if prof.TimeNanos != 0 {
  915. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  916. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  917. }
  918. if prof.DurationNanos != 0 {
  919. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  920. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  921. var ratio string
  922. if totalUnit == "ns" && totalNanos != 0 {
  923. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  924. }
  925. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  926. }
  927. return label
  928. }
  929. // reportLabels returns printable labels for a report. Includes
  930. // profileLabels.
  931. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  932. nodeFraction := rpt.options.NodeFraction
  933. edgeFraction := rpt.options.EdgeFraction
  934. nodeCount := len(g.Nodes)
  935. var label []string
  936. if len(rpt.options.ProfileLabels) > 0 {
  937. label = append(label, rpt.options.ProfileLabels...)
  938. } else if fullHeaders || !rpt.options.CompactLabels {
  939. label = ProfileLabels(rpt)
  940. }
  941. var flatSum int64
  942. for _, n := range g.Nodes {
  943. flatSum = flatSum + n.FlatValue()
  944. }
  945. label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))
  946. if rpt.total != 0 {
  947. if droppedNodes > 0 {
  948. label = append(label, genLabel(droppedNodes, "node", "cum",
  949. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  950. }
  951. if droppedEdges > 0 {
  952. label = append(label, genLabel(droppedEdges, "edge", "freq",
  953. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  954. }
  955. if nodeCount > 0 && nodeCount < origCount {
  956. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  957. nodeCount, origCount))
  958. }
  959. }
  960. return label
  961. }
  962. func genLabel(d int, n, l, f string) string {
  963. if d > 1 {
  964. n = n + "s"
  965. }
  966. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  967. }
  968. // New builds a new report indexing the sample values interpreting the
  969. // samples with the provided function.
  970. func New(prof *profile.Profile, o *Options) *Report {
  971. format := func(v int64) string {
  972. if r := o.Ratio; r > 0 && r != 1 {
  973. fv := float64(v) * r
  974. v = int64(fv)
  975. }
  976. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  977. }
  978. return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor, !o.PositivePercentages),
  979. o, format}
  980. }
  981. // NewDefault builds a new report indexing the last sample value
  982. // available.
  983. func NewDefault(prof *profile.Profile, options Options) *Report {
  984. index := len(prof.SampleType) - 1
  985. o := &options
  986. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  987. o.Title = filepath.Base(prof.Mapping[0].File)
  988. }
  989. o.SampleType = prof.SampleType[index].Type
  990. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  991. o.SampleValue = func(v []int64) int64 {
  992. return v[index]
  993. }
  994. return New(prof, o)
  995. }
  996. // computeTotal computes the sum of all sample values. This will be
  997. // used to compute percentages. If includeNegative is set, use use
  998. // absolute values to provide a meaningful percentage for both
  999. // negative and positive values. Otherwise only use positive values,
  1000. // which is useful when comparing profiles from different jobs.
  1001. func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64, includeNegative bool) int64 {
  1002. var div, ret int64
  1003. for _, sample := range prof.Sample {
  1004. var d, v int64
  1005. v = value(sample.Value)
  1006. if meanDiv != nil {
  1007. d = meanDiv(sample.Value)
  1008. }
  1009. if v >= 0 {
  1010. ret += v
  1011. div += d
  1012. } else if includeNegative {
  1013. ret -= v
  1014. div += d
  1015. }
  1016. }
  1017. if div != 0 {
  1018. return ret / div
  1019. }
  1020. return ret
  1021. }
  1022. // Report contains the data and associated routines to extract a
  1023. // report from a profile.
  1024. type Report struct {
  1025. prof *profile.Profile
  1026. total int64
  1027. options *Options
  1028. formatValue func(int64) string
  1029. }
  1030. func abs64(i int64) int64 {
  1031. if i < 0 {
  1032. return -i
  1033. }
  1034. return i
  1035. }