No Description

report.go 28KB

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