Brak opisu

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