Нема описа

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