Sin descripción

report.go 31KB

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