暫無描述

report.go 29KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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, Callgrind:
  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[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, "positions: instr line")
  554. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  555. objfiles := make(map[string]int)
  556. files := make(map[string]int)
  557. names := make(map[string]int)
  558. // prevInfo points to the previous NodeInfo.
  559. // It is used to group cost lines together as much as possible.
  560. var prevInfo *graph.NodeInfo
  561. for _, n := range g.Nodes {
  562. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  563. fmt.Fprintln(w)
  564. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  565. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  566. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  567. }
  568. addr := callgrindAddress(prevInfo, n.Info.Address)
  569. sv, _ := measurement.Scale(n.Flat, o.SampleUnit, o.OutputUnit)
  570. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  571. // Print outgoing edges.
  572. for _, out := range n.Out.Sort() {
  573. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  574. callee := out.Dest
  575. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  576. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  577. // pprof doesn't have a flat weight for a call, leave as 0.
  578. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  579. // TODO: This address may be in the middle of a call
  580. // instruction. It would be best to find the beginning
  581. // of the instruction, but the tools seem to handle
  582. // this OK.
  583. fmt.Fprintf(w, "* * %d\n", int64(c))
  584. }
  585. prevInfo = &n.Info
  586. }
  587. return nil
  588. }
  589. // getDisambiguatedNames returns a map from each node in the graph to
  590. // the name to use in the callgrind output. Callgrind merges all
  591. // functions with the same [file name, function name]. Add a [%d/n]
  592. // suffix to disambiguate nodes with different values of
  593. // node.Function, which we want to keep separate. In particular, this
  594. // affects graphs created with --call_tree, where nodes from different
  595. // contexts are associated to different Functions.
  596. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  597. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  598. type names struct {
  599. file, function string
  600. }
  601. // nameFunctionIndex maps the callgrind names (filename, function)
  602. // to the node.Function values found for that name, and each
  603. // node.Function value to a sequential index to be used on the
  604. // disambiguated name.
  605. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  606. for _, n := range g.Nodes {
  607. nm := names{n.Info.File, n.Info.Name}
  608. p, ok := nameFunctionIndex[nm]
  609. if !ok {
  610. p = make(map[*graph.Node]int)
  611. nameFunctionIndex[nm] = p
  612. }
  613. if _, ok := p[n.Function]; !ok {
  614. p[n.Function] = len(p)
  615. }
  616. }
  617. for _, n := range g.Nodes {
  618. nm := names{n.Info.File, n.Info.Name}
  619. nodeName[n] = n.Info.Name
  620. if p := nameFunctionIndex[nm]; len(p) > 1 {
  621. // If there is more than one function, add suffix to disambiguate.
  622. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  623. }
  624. }
  625. return nodeName
  626. }
  627. // callgrindName implements the callgrind naming compression scheme.
  628. // For names not previously seen returns "(N) name", where N is a
  629. // unique index. For names previously seen returns "(N)" where N is
  630. // the index returned the first time.
  631. func callgrindName(names map[string]int, name string) string {
  632. if name == "" {
  633. return ""
  634. }
  635. if id, ok := names[name]; ok {
  636. return fmt.Sprintf("(%d)", id)
  637. }
  638. id := len(names) + 1
  639. names[name] = id
  640. return fmt.Sprintf("(%d) %s", id, name)
  641. }
  642. // callgrindAddress implements the callgrind subposition compression scheme if
  643. // possible. If prevInfo != nil, it contains the previous address. The current
  644. // address can be given relative to the previous address, with an explicit +/-
  645. // to indicate it is relative, or * for the same address.
  646. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  647. abs := fmt.Sprintf("%#x", curr)
  648. if prevInfo == nil {
  649. return abs
  650. }
  651. prev := prevInfo.Address
  652. if prev == curr {
  653. return "*"
  654. }
  655. diff := int64(curr - prev)
  656. relative := fmt.Sprintf("%+d", diff)
  657. // Only bother to use the relative address if it is actually shorter.
  658. if len(relative) < len(abs) {
  659. return relative
  660. }
  661. return abs
  662. }
  663. // printTree prints a tree-based report in text form.
  664. func printTree(w io.Writer, rpt *Report) error {
  665. const separator = "----------------------------------------------------------+-------------"
  666. const legend = " flat flat% sum% cum cum% calls calls% + context "
  667. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  668. rpt.selectOutputUnit(g)
  669. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  670. fmt.Fprintln(w, separator)
  671. fmt.Fprintln(w, legend)
  672. var flatSum int64
  673. rx := rpt.options.Symbol
  674. for _, n := range g.Nodes {
  675. name, flat, cum := n.Info.PrintableName(), n.Flat, n.Cum
  676. // Skip any entries that do not match the regexp (for the "peek" command).
  677. if rx != nil && !rx.MatchString(name) {
  678. continue
  679. }
  680. fmt.Fprintln(w, separator)
  681. // Print incoming edges.
  682. inEdges := n.In.Sort()
  683. for _, in := range inEdges {
  684. var inline string
  685. if in.Inline {
  686. inline = " (inline)"
  687. }
  688. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  689. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  690. }
  691. // Print current node.
  692. flatSum += flat
  693. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  694. rpt.formatValue(flat),
  695. percentage(flat, rpt.total),
  696. percentage(flatSum, rpt.total),
  697. rpt.formatValue(cum),
  698. percentage(cum, rpt.total),
  699. name)
  700. // Print outgoing edges.
  701. outEdges := n.Out.Sort()
  702. for _, out := range outEdges {
  703. var inline string
  704. if out.Inline {
  705. inline = " (inline)"
  706. }
  707. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  708. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  709. }
  710. }
  711. if len(g.Nodes) > 0 {
  712. fmt.Fprintln(w, separator)
  713. }
  714. return nil
  715. }
  716. // printDOT prints an annotated callgraph in DOT format.
  717. func printDOT(w io.Writer, rpt *Report) error {
  718. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  719. rpt.selectOutputUnit(g)
  720. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  721. c := &graph.DotConfig{
  722. Title: rpt.options.Title,
  723. Labels: labels,
  724. FormatValue: rpt.formatValue,
  725. Total: rpt.total,
  726. }
  727. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  728. return nil
  729. }
  730. // percentage computes the percentage of total of a value, and encodes
  731. // it as a string. At least two digits of precision are printed.
  732. func percentage(value, total int64) string {
  733. var ratio float64
  734. if total != 0 {
  735. ratio = math.Abs(float64(value)/float64(total)) * 100
  736. }
  737. switch {
  738. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  739. return " 100%"
  740. case math.Abs(ratio) >= 1.0:
  741. return fmt.Sprintf("%5.2f%%", ratio)
  742. default:
  743. return fmt.Sprintf("%5.2g%%", ratio)
  744. }
  745. }
  746. // ProfileLabels returns printable labels for a profile.
  747. func ProfileLabels(rpt *Report) []string {
  748. label := []string{}
  749. prof := rpt.prof
  750. o := rpt.options
  751. if len(prof.Mapping) > 0 {
  752. if prof.Mapping[0].File != "" {
  753. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  754. }
  755. if prof.Mapping[0].BuildID != "" {
  756. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  757. }
  758. }
  759. label = append(label, prof.Comments...)
  760. if o.SampleType != "" {
  761. label = append(label, "Type: "+o.SampleType)
  762. }
  763. if prof.TimeNanos != 0 {
  764. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  765. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  766. }
  767. if prof.DurationNanos != 0 {
  768. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  769. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  770. var ratio string
  771. if totalUnit == "ns" && totalNanos != 0 {
  772. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  773. }
  774. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  775. }
  776. return label
  777. }
  778. // reportLabels returns printable labels for a report. Includes
  779. // profileLabels.
  780. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  781. nodeFraction := rpt.options.NodeFraction
  782. edgeFraction := rpt.options.EdgeFraction
  783. nodeCount := len(g.Nodes)
  784. var label []string
  785. if len(rpt.options.ProfileLabels) > 0 {
  786. for _, l := range rpt.options.ProfileLabels {
  787. label = append(label, l)
  788. }
  789. } else if fullHeaders || !rpt.options.CompactLabels {
  790. label = ProfileLabels(rpt)
  791. }
  792. var flatSum int64
  793. for _, n := range g.Nodes {
  794. flatSum = flatSum + n.Flat
  795. }
  796. 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)))
  797. if rpt.total != 0 {
  798. if droppedNodes > 0 {
  799. label = append(label, genLabel(droppedNodes, "node", "cum",
  800. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  801. }
  802. if droppedEdges > 0 {
  803. label = append(label, genLabel(droppedEdges, "edge", "freq",
  804. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  805. }
  806. if nodeCount > 0 && nodeCount < origCount {
  807. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  808. nodeCount, origCount))
  809. }
  810. }
  811. return label
  812. }
  813. func genLabel(d int, n, l, f string) string {
  814. if d > 1 {
  815. n = n + "s"
  816. }
  817. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  818. }
  819. // Output formats.
  820. const (
  821. Proto = iota
  822. Dot
  823. Tags
  824. Tree
  825. Text
  826. Traces
  827. Raw
  828. Dis
  829. List
  830. WebList
  831. Callgrind
  832. TopProto
  833. )
  834. // Options are the formatting and filtering options used to generate a
  835. // profile.
  836. type Options struct {
  837. OutputFormat int
  838. CumSort bool
  839. CallTree bool
  840. DropNegative bool
  841. PositivePercentages bool
  842. CompactLabels bool
  843. Ratio float64
  844. Title string
  845. ProfileLabels []string
  846. NodeCount int
  847. NodeFraction float64
  848. EdgeFraction float64
  849. SampleValue func(s []int64) int64
  850. SampleType string
  851. SampleUnit string // Unit for the sample data from the profile.
  852. OutputUnit string // Units for data formatting in report.
  853. Symbol *regexp.Regexp // Symbols to include on disassembly report.
  854. SourcePath string // Search path for source files.
  855. }
  856. // New builds a new report indexing the sample values interpreting the
  857. // samples with the provided function.
  858. func New(prof *profile.Profile, o *Options) *Report {
  859. format := func(v int64) string {
  860. if r := o.Ratio; r > 0 && r != 1 {
  861. fv := float64(v) * r
  862. v = int64(fv)
  863. }
  864. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  865. }
  866. return &Report{prof, computeTotal(prof, o.SampleValue, !o.PositivePercentages),
  867. o, format}
  868. }
  869. // NewDefault builds a new report indexing the last sample value
  870. // available.
  871. func NewDefault(prof *profile.Profile, options Options) *Report {
  872. index := len(prof.SampleType) - 1
  873. o := &options
  874. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  875. o.Title = filepath.Base(prof.Mapping[0].File)
  876. }
  877. o.SampleType = prof.SampleType[index].Type
  878. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  879. o.SampleValue = func(v []int64) int64 {
  880. return v[index]
  881. }
  882. return New(prof, o)
  883. }
  884. // computeTotal computes the sum of all sample values. This will be
  885. // used to compute percentages. If includeNegative is set, use use
  886. // absolute values to provide a meaningful percentage for both
  887. // negative and positive values. Otherwise only use positive values,
  888. // which is useful when comparing profiles from different jobs.
  889. func computeTotal(prof *profile.Profile, value func(v []int64) int64, includeNegative bool) int64 {
  890. var ret int64
  891. for _, sample := range prof.Sample {
  892. if v := value(sample.Value); v > 0 {
  893. ret += v
  894. } else if includeNegative {
  895. ret -= v
  896. }
  897. }
  898. return ret
  899. }
  900. // Report contains the data and associated routines to extract a
  901. // report from a profile.
  902. type Report struct {
  903. prof *profile.Profile
  904. total int64
  905. options *Options
  906. formatValue func(int64) string
  907. }
  908. func (rpt *Report) formatTags(s *profile.Sample) (string, bool) {
  909. var labels []string
  910. for key, vals := range s.Label {
  911. for _, v := range vals {
  912. labels = append(labels, key+":"+v)
  913. }
  914. }
  915. for key, nvals := range s.NumLabel {
  916. for _, v := range nvals {
  917. labels = append(labels, measurement.Label(v, key))
  918. }
  919. }
  920. if len(labels) == 0 {
  921. return "", false
  922. }
  923. sort.Strings(labels)
  924. return strings.Join(labels, `\n`), true
  925. }
  926. func abs64(i int64) int64 {
  927. if i < 0 {
  928. return -i
  929. }
  930. return i
  931. }