Нема описа

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