Aucune description

legacy_profile.go 31KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. // This file implements parsers to convert legacy profiles into the
  15. // profile.proto format.
  16. package profile
  17. import (
  18. "bufio"
  19. "bytes"
  20. "fmt"
  21. "io"
  22. "math"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. )
  27. var (
  28. countStartRE = regexp.MustCompile(`\A(\w+) profile: total \d+\n\z`)
  29. countRE = regexp.MustCompile(`\A(\d+) @(( 0x[0-9a-f]+)+)\n\z`)
  30. heapHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] *@ *(heap[_a-z0-9]*)/?(\d*)`)
  31. heapSampleRE = regexp.MustCompile(`(-?\d+): *(-?\d+) *\[ *(\d+): *(\d+) *] @([ x0-9a-f]*)`)
  32. contentionSampleRE = regexp.MustCompile(`(\d+) *(\d+) @([ x0-9a-f]*)`)
  33. hexNumberRE = regexp.MustCompile(`0x[0-9a-f]+`)
  34. growthHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] @ growthz`)
  35. fragmentationHeaderRE = regexp.MustCompile(`heap profile: *(\d+): *(\d+) *\[ *(\d+): *(\d+) *\] @ fragmentationz`)
  36. threadzStartRE = regexp.MustCompile(`--- threadz \d+ ---`)
  37. threadStartRE = regexp.MustCompile(`--- Thread ([[:xdigit:]]+) \(name: (.*)/(\d+)\) stack: ---`)
  38. procMapsRE = regexp.MustCompile(`([[:xdigit:]]+)-([[:xdigit:]]+)\s+([-rwxp]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+):([[:xdigit:]]+)\s+([[:digit:]]+)\s*(\S+)?`)
  39. briefMapsRE = regexp.MustCompile(`\s*([[:xdigit:]]+)-([[:xdigit:]]+):\s*(\S+)(\s.*@)?([[:xdigit:]]+)?`)
  40. )
  41. func isSpaceOrComment(line string) bool {
  42. trimmed := strings.TrimSpace(line)
  43. return len(trimmed) == 0 || trimmed[0] == '#'
  44. }
  45. // parseGoCount parses a Go count profile (e.g., threadcreate or
  46. // goroutine) and returns a new Profile.
  47. func parseGoCount(b []byte) (*Profile, error) {
  48. r := bytes.NewBuffer(b)
  49. var line string
  50. var err error
  51. for {
  52. // Skip past comments and empty lines seeking a real header.
  53. line, err = r.ReadString('\n')
  54. if err != nil {
  55. return nil, err
  56. }
  57. if !isSpaceOrComment(line) {
  58. break
  59. }
  60. }
  61. m := countStartRE.FindStringSubmatch(line)
  62. if m == nil {
  63. return nil, errUnrecognized
  64. }
  65. profileType := string(m[1])
  66. p := &Profile{
  67. PeriodType: &ValueType{Type: profileType, Unit: "count"},
  68. Period: 1,
  69. SampleType: []*ValueType{{Type: profileType, Unit: "count"}},
  70. }
  71. locations := make(map[uint64]*Location)
  72. for {
  73. line, err = r.ReadString('\n')
  74. if err != nil {
  75. if err == io.EOF {
  76. break
  77. }
  78. return nil, err
  79. }
  80. if isSpaceOrComment(line) {
  81. continue
  82. }
  83. if strings.HasPrefix(line, "---") {
  84. break
  85. }
  86. m := countRE.FindStringSubmatch(line)
  87. if m == nil {
  88. return nil, errMalformed
  89. }
  90. n, err := strconv.ParseInt(string(m[1]), 0, 64)
  91. if err != nil {
  92. return nil, errMalformed
  93. }
  94. fields := strings.Fields(string(m[2]))
  95. locs := make([]*Location, 0, len(fields))
  96. for _, stk := range fields {
  97. addr, err := strconv.ParseUint(stk, 0, 64)
  98. if err != nil {
  99. return nil, errMalformed
  100. }
  101. // Adjust all frames by -1 (except the leaf) to land on top of
  102. // the call instruction.
  103. if len(locs) > 0 {
  104. addr--
  105. }
  106. loc := locations[addr]
  107. if loc == nil {
  108. loc = &Location{
  109. Address: addr,
  110. }
  111. locations[addr] = loc
  112. p.Location = append(p.Location, loc)
  113. }
  114. locs = append(locs, loc)
  115. }
  116. p.Sample = append(p.Sample, &Sample{
  117. Location: locs,
  118. Value: []int64{n},
  119. })
  120. }
  121. if err = parseAdditionalSections(strings.TrimSpace(line), r, p); err != nil {
  122. return nil, err
  123. }
  124. return p, nil
  125. }
  126. // remapLocationIDs ensures there is a location for each address
  127. // referenced by a sample, and remaps the samples to point to the new
  128. // location ids.
  129. func (p *Profile) remapLocationIDs() {
  130. seen := make(map[*Location]bool, len(p.Location))
  131. var locs []*Location
  132. for _, s := range p.Sample {
  133. for _, l := range s.Location {
  134. if seen[l] {
  135. continue
  136. }
  137. l.ID = uint64(len(locs) + 1)
  138. locs = append(locs, l)
  139. seen[l] = true
  140. }
  141. }
  142. p.Location = locs
  143. }
  144. func (p *Profile) remapFunctionIDs() {
  145. seen := make(map[*Function]bool, len(p.Function))
  146. var fns []*Function
  147. for _, l := range p.Location {
  148. for _, ln := range l.Line {
  149. fn := ln.Function
  150. if fn == nil || seen[fn] {
  151. continue
  152. }
  153. fn.ID = uint64(len(fns) + 1)
  154. fns = append(fns, fn)
  155. seen[fn] = true
  156. }
  157. }
  158. p.Function = fns
  159. }
  160. // remapMappingIDs matches location addresses with existing mappings
  161. // and updates them appropriately. This is O(N*M), if this ever shows
  162. // up as a bottleneck, evaluate sorting the mappings and doing a
  163. // binary search, which would make it O(N*log(M)).
  164. func (p *Profile) remapMappingIDs() {
  165. // Some profile handlers will incorrectly set regions for the main
  166. // executable if its section is remapped. Fix them through heuristics.
  167. if len(p.Mapping) > 0 {
  168. // Remove the initial mapping if named '/anon_hugepage' and has a
  169. // consecutive adjacent mapping.
  170. if m := p.Mapping[0]; strings.HasPrefix(m.File, "/anon_hugepage") {
  171. if len(p.Mapping) > 1 && m.Limit == p.Mapping[1].Start {
  172. p.Mapping = p.Mapping[1:]
  173. }
  174. }
  175. }
  176. // Subtract the offset from the start of the main mapping if it
  177. // ends up at a recognizable start address.
  178. if len(p.Mapping) > 0 {
  179. const expectedStart = 0x400000
  180. if m := p.Mapping[0]; m.Start-m.Offset == expectedStart {
  181. m.Start = expectedStart
  182. m.Offset = 0
  183. }
  184. }
  185. // Associate each location with an address to the corresponding
  186. // mapping. Create fake mapping if a suitable one isn't found.
  187. var fake *Mapping
  188. nextLocation:
  189. for _, l := range p.Location {
  190. a := l.Address
  191. if l.Mapping != nil || a == 0 {
  192. continue
  193. }
  194. for _, m := range p.Mapping {
  195. if m.Start <= a && a < m.Limit {
  196. l.Mapping = m
  197. continue nextLocation
  198. }
  199. }
  200. // Work around legacy handlers failing to encode the first
  201. // part of mappings split into adjacent ranges.
  202. for _, m := range p.Mapping {
  203. if m.Offset != 0 && m.Start-m.Offset <= a && a < m.Start {
  204. m.Start -= m.Offset
  205. m.Offset = 0
  206. l.Mapping = m
  207. continue nextLocation
  208. }
  209. }
  210. // If there is still no mapping, create a fake one.
  211. // This is important for the Go legacy handler, which produced
  212. // no mappings.
  213. if fake == nil {
  214. fake = &Mapping{
  215. ID: 1,
  216. Limit: ^uint64(0),
  217. }
  218. p.Mapping = append(p.Mapping, fake)
  219. }
  220. l.Mapping = fake
  221. }
  222. // Reset all mapping IDs.
  223. for i, m := range p.Mapping {
  224. m.ID = uint64(i + 1)
  225. }
  226. }
  227. var cpuInts = []func([]byte) (uint64, []byte){
  228. get32l,
  229. get32b,
  230. get64l,
  231. get64b,
  232. }
  233. func get32l(b []byte) (uint64, []byte) {
  234. if len(b) < 4 {
  235. return 0, nil
  236. }
  237. return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24, b[4:]
  238. }
  239. func get32b(b []byte) (uint64, []byte) {
  240. if len(b) < 4 {
  241. return 0, nil
  242. }
  243. return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24, b[4:]
  244. }
  245. func get64l(b []byte) (uint64, []byte) {
  246. if len(b) < 8 {
  247. return 0, nil
  248. }
  249. return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56, b[8:]
  250. }
  251. func get64b(b []byte) (uint64, []byte) {
  252. if len(b) < 8 {
  253. return 0, nil
  254. }
  255. return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56, b[8:]
  256. }
  257. // parseCPU parses a profilez legacy profile and returns a newly
  258. // populated Profile.
  259. //
  260. // The general format for profilez samples is a sequence of words in
  261. // binary format. The first words are a header with the following data:
  262. // 1st word -- 0
  263. // 2nd word -- 3
  264. // 3rd word -- 0 if a c++ application, 1 if a java application.
  265. // 4th word -- Sampling period (in microseconds).
  266. // 5th word -- Padding.
  267. func parseCPU(b []byte) (*Profile, error) {
  268. var parse func([]byte) (uint64, []byte)
  269. var n1, n2, n3, n4, n5 uint64
  270. for _, parse = range cpuInts {
  271. var tmp []byte
  272. n1, tmp = parse(b)
  273. n2, tmp = parse(tmp)
  274. n3, tmp = parse(tmp)
  275. n4, tmp = parse(tmp)
  276. n5, tmp = parse(tmp)
  277. if tmp != nil && n1 == 0 && n2 == 3 && n3 == 0 && n4 > 0 && n5 == 0 {
  278. b = tmp
  279. return cpuProfile(b, int64(n4), parse)
  280. }
  281. if tmp != nil && n1 == 0 && n2 == 3 && n3 == 1 && n4 > 0 && n5 == 0 {
  282. b = tmp
  283. return javaCPUProfile(b, int64(n4), parse)
  284. }
  285. }
  286. return nil, errUnrecognized
  287. }
  288. // cpuProfile returns a new Profile from C++ profilez data.
  289. // b is the profile bytes after the header, period is the profiling
  290. // period, and parse is a function to parse 8-byte chunks from the
  291. // profile in its native endianness.
  292. func cpuProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte)) (*Profile, error) {
  293. p := &Profile{
  294. Period: period * 1000,
  295. PeriodType: &ValueType{Type: "cpu", Unit: "nanoseconds"},
  296. SampleType: []*ValueType{
  297. {Type: "samples", Unit: "count"},
  298. {Type: "cpu", Unit: "nanoseconds"},
  299. },
  300. }
  301. var err error
  302. if b, _, err = parseCPUSamples(b, parse, true, p); err != nil {
  303. return nil, err
  304. }
  305. // If *most* samples have the same second-to-the-bottom frame, it
  306. // strongly suggests that it is an uninteresting artifact of
  307. // measurement -- a stack frame pushed by the signal handler. The
  308. // bottom frame is always correct as it is picked up from the signal
  309. // structure, not the stack. Check if this is the case and if so,
  310. // remove.
  311. // Remove up to two frames.
  312. maxiter := 2
  313. // Allow one different sample for this many samples with the same
  314. // second-to-last frame.
  315. similarSamples := 32
  316. margin := len(p.Sample) / similarSamples
  317. for iter := 0; iter < maxiter; iter++ {
  318. addr1 := make(map[uint64]int)
  319. for _, s := range p.Sample {
  320. if len(s.Location) > 1 {
  321. a := s.Location[1].Address
  322. addr1[a] = addr1[a] + 1
  323. }
  324. }
  325. for id1, count := range addr1 {
  326. if count >= len(p.Sample)-margin {
  327. // Found uninteresting frame, strip it out from all samples
  328. for _, s := range p.Sample {
  329. if len(s.Location) > 1 && s.Location[1].Address == id1 {
  330. s.Location = append(s.Location[:1], s.Location[2:]...)
  331. }
  332. }
  333. break
  334. }
  335. }
  336. }
  337. // The profile handler may duplicate the leaf frame, because it gets
  338. // its address both from stack unwinding and from the signal
  339. // context. Detect this and delete the duplicate, which has been
  340. // adjusted by -1. The leaf address should not be adjusted as it is
  341. // not a call.
  342. for _, s := range p.Sample {
  343. if len(s.Location) > 1 && s.Location[0].Address == s.Location[1].Address+1 {
  344. s.Location = append(s.Location[:1], s.Location[2:]...)
  345. }
  346. }
  347. if err := p.ParseMemoryMap(bytes.NewBuffer(b)); err != nil {
  348. return nil, err
  349. }
  350. return p, nil
  351. }
  352. // parseCPUSamples parses a collection of profilez samples from a
  353. // profile.
  354. //
  355. // profilez samples are a repeated sequence of stack frames of the
  356. // form:
  357. // 1st word -- The number of times this stack was encountered.
  358. // 2nd word -- The size of the stack (StackSize).
  359. // 3rd word -- The first address on the stack.
  360. // ...
  361. // StackSize + 2 -- The last address on the stack
  362. // The last stack trace is of the form:
  363. // 1st word -- 0
  364. // 2nd word -- 1
  365. // 3rd word -- 0
  366. //
  367. // Addresses from stack traces may point to the next instruction after
  368. // each call. Optionally adjust by -1 to land somewhere on the actual
  369. // call (except for the leaf, which is not a call).
  370. func parseCPUSamples(b []byte, parse func(b []byte) (uint64, []byte), adjust bool, p *Profile) ([]byte, map[uint64]*Location, error) {
  371. locs := make(map[uint64]*Location)
  372. for len(b) > 0 {
  373. var count, nstk uint64
  374. count, b = parse(b)
  375. nstk, b = parse(b)
  376. if b == nil || nstk > uint64(len(b)/4) {
  377. return nil, nil, errUnrecognized
  378. }
  379. var sloc []*Location
  380. addrs := make([]uint64, nstk)
  381. for i := 0; i < int(nstk); i++ {
  382. addrs[i], b = parse(b)
  383. }
  384. if count == 0 && nstk == 1 && addrs[0] == 0 {
  385. // End of data marker
  386. break
  387. }
  388. for i, addr := range addrs {
  389. if adjust && i > 0 {
  390. addr--
  391. }
  392. loc := locs[addr]
  393. if loc == nil {
  394. loc = &Location{
  395. Address: addr,
  396. }
  397. locs[addr] = loc
  398. p.Location = append(p.Location, loc)
  399. }
  400. sloc = append(sloc, loc)
  401. }
  402. p.Sample = append(p.Sample,
  403. &Sample{
  404. Value: []int64{int64(count), int64(count) * int64(p.Period)},
  405. Location: sloc,
  406. })
  407. }
  408. // Reached the end without finding the EOD marker.
  409. return b, locs, nil
  410. }
  411. // parseHeap parses a heapz legacy or a growthz profile and
  412. // returns a newly populated Profile.
  413. func parseHeap(b []byte) (p *Profile, err error) {
  414. r := bytes.NewBuffer(b)
  415. l, err := r.ReadString('\n')
  416. if err != nil {
  417. return nil, errUnrecognized
  418. }
  419. p = &Profile{}
  420. sampling := ""
  421. hasAlloc := false
  422. p.PeriodType = &ValueType{Type: "space", Unit: "bytes"}
  423. if header := heapHeaderRE.FindStringSubmatch(l); header != nil {
  424. sampling, p.Period, hasAlloc, err = parseHeapHeader(l)
  425. if err != nil {
  426. return nil, err
  427. }
  428. } else if header = growthHeaderRE.FindStringSubmatch(l); header != nil {
  429. p.Period = 1
  430. } else if header = fragmentationHeaderRE.FindStringSubmatch(l); header != nil {
  431. p.Period = 1
  432. } else {
  433. return nil, errUnrecognized
  434. }
  435. if hasAlloc {
  436. // Put alloc before inuse so that default pprof selection
  437. // will prefer inuse_space.
  438. p.SampleType = []*ValueType{
  439. {Type: "alloc_objects", Unit: "count"},
  440. {Type: "alloc_space", Unit: "bytes"},
  441. {Type: "inuse_objects", Unit: "count"},
  442. {Type: "inuse_space", Unit: "bytes"},
  443. }
  444. } else {
  445. p.SampleType = []*ValueType{
  446. {Type: "objects", Unit: "count"},
  447. {Type: "space", Unit: "bytes"},
  448. }
  449. }
  450. locs := make(map[uint64]*Location)
  451. for {
  452. l, err = r.ReadString('\n')
  453. if err != nil {
  454. if err != io.EOF {
  455. return nil, err
  456. }
  457. if l == "" {
  458. break
  459. }
  460. }
  461. if isSpaceOrComment(l) {
  462. continue
  463. }
  464. l = strings.TrimSpace(l)
  465. if sectionTrigger(l) != unrecognizedSection {
  466. break
  467. }
  468. value, blocksize, addrs, err := parseHeapSample(l, p.Period, sampling, hasAlloc)
  469. if err != nil {
  470. return nil, err
  471. }
  472. var sloc []*Location
  473. for i, addr := range addrs {
  474. // Addresses from stack traces point to the next instruction after
  475. // each call. Adjust by -1 to land somewhere on the actual call
  476. // (except for the leaf, which is not a call).
  477. if i > 0 {
  478. addr--
  479. }
  480. loc := locs[addr]
  481. if locs[addr] == nil {
  482. loc = &Location{
  483. Address: addr,
  484. }
  485. p.Location = append(p.Location, loc)
  486. locs[addr] = loc
  487. }
  488. sloc = append(sloc, loc)
  489. }
  490. p.Sample = append(p.Sample, &Sample{
  491. Value: value,
  492. Location: sloc,
  493. NumLabel: map[string][]int64{"bytes": []int64{blocksize}},
  494. })
  495. }
  496. if err = parseAdditionalSections(l, r, p); err != nil {
  497. return nil, err
  498. }
  499. return p, nil
  500. }
  501. func parseHeapHeader(line string) (sampling string, period int64, hasAlloc bool, err error) {
  502. header := heapHeaderRE.FindStringSubmatch(line)
  503. if header == nil {
  504. return "", 0, false, errUnrecognized
  505. }
  506. if len(header[6]) > 0 {
  507. if period, err = strconv.ParseInt(string(header[6]), 10, 64); err != nil {
  508. return "", 0, false, errUnrecognized
  509. }
  510. }
  511. if (header[3] != header[1] && header[3] != "0") || (header[4] != header[2] && header[4] != "0") {
  512. hasAlloc = true
  513. }
  514. switch header[5] {
  515. case "heapz_v2", "heap_v2":
  516. return "v2", period, hasAlloc, nil
  517. case "heapprofile":
  518. return "", 1, hasAlloc, nil
  519. case "heap":
  520. return "v2", period / 2, hasAlloc, nil
  521. default:
  522. return "", 0, false, errUnrecognized
  523. }
  524. }
  525. // parseHeapSample parses a single row from a heap profile into a new Sample.
  526. func parseHeapSample(line string, rate int64, sampling string, includeAlloc bool) (value []int64, blocksize int64, addrs []uint64, err error) {
  527. sampleData := heapSampleRE.FindStringSubmatch(line)
  528. if len(sampleData) != 6 {
  529. return nil, 0, nil, fmt.Errorf("unexpected number of sample values: got %d, want 6", len(sampleData))
  530. }
  531. // This is a local-scoped helper function to avoid needing to pass
  532. // around rate, sampling and many return parameters.
  533. addValues := func(countString, sizeString string, label string) error {
  534. count, err := strconv.ParseInt(countString, 10, 64)
  535. if err != nil {
  536. return fmt.Errorf("malformed sample: %s: %v", line, err)
  537. }
  538. size, err := strconv.ParseInt(sizeString, 10, 64)
  539. if err != nil {
  540. return fmt.Errorf("malformed sample: %s: %v", line, err)
  541. }
  542. if count == 0 && size != 0 {
  543. return fmt.Errorf("%s count was 0 but %s bytes was %d", label, label, size)
  544. }
  545. if count != 0 {
  546. blocksize = size / count
  547. if sampling == "v2" {
  548. count, size = scaleHeapSample(count, size, rate)
  549. }
  550. }
  551. value = append(value, count, size)
  552. return nil
  553. }
  554. if includeAlloc {
  555. if err := addValues(sampleData[3], sampleData[4], "allocation"); err != nil {
  556. return nil, 0, nil, err
  557. }
  558. }
  559. if err := addValues(sampleData[1], sampleData[2], "inuse"); err != nil {
  560. return nil, 0, nil, err
  561. }
  562. addrs = parseHexAddresses(sampleData[5])
  563. return value, blocksize, addrs, nil
  564. }
  565. // extractHexAddresses extracts hex numbers from a string and returns
  566. // them, together with their numeric value, in a slice.
  567. func extractHexAddresses(s string) ([]string, []uint64) {
  568. hexStrings := hexNumberRE.FindAllString(s, -1)
  569. var ids []uint64
  570. for _, s := range hexStrings {
  571. if id, err := strconv.ParseUint(s, 0, 64); err == nil {
  572. ids = append(ids, id)
  573. } else {
  574. // Do not expect any parsing failures due to the regexp matching.
  575. panic("failed to parse hex value:" + s)
  576. }
  577. }
  578. return hexStrings, ids
  579. }
  580. // parseHexAddresses parses hex numbers from a string and returns them
  581. // in a slice.
  582. func parseHexAddresses(s string) []uint64 {
  583. _, ids := extractHexAddresses(s)
  584. return ids
  585. }
  586. // scaleHeapSample adjusts the data from a heapz Sample to
  587. // account for its probability of appearing in the collected
  588. // data. heapz profiles are a sampling of the memory allocations
  589. // requests in a program. We estimate the unsampled value by dividing
  590. // each collected sample by its probability of appearing in the
  591. // profile. heapz v2 profiles rely on a poisson process to determine
  592. // which samples to collect, based on the desired average collection
  593. // rate R. The probability of a sample of size S to appear in that
  594. // profile is 1-exp(-S/R).
  595. func scaleHeapSample(count, size, rate int64) (int64, int64) {
  596. if count == 0 || size == 0 {
  597. return 0, 0
  598. }
  599. if rate <= 1 {
  600. // if rate==1 all samples were collected so no adjustment is needed.
  601. // if rate<1 treat as unknown and skip scaling.
  602. return count, size
  603. }
  604. avgSize := float64(size) / float64(count)
  605. scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
  606. return int64(float64(count) * scale), int64(float64(size) * scale)
  607. }
  608. // parseContention parses a contentionz profile and returns a newly
  609. // populated Profile.
  610. func parseContention(b []byte) (p *Profile, err error) {
  611. r := bytes.NewBuffer(b)
  612. l, err := r.ReadString('\n')
  613. if err != nil {
  614. return nil, errUnrecognized
  615. }
  616. if !strings.HasPrefix(l, "--- contention") {
  617. return nil, errUnrecognized
  618. }
  619. p = &Profile{
  620. PeriodType: &ValueType{Type: "contentions", Unit: "count"},
  621. Period: 1,
  622. SampleType: []*ValueType{
  623. {Type: "contentions", Unit: "count"},
  624. {Type: "delay", Unit: "nanoseconds"},
  625. },
  626. }
  627. var cpuHz int64
  628. // Parse text of the form "attribute = value" before the samples.
  629. const delimiter = "="
  630. for {
  631. l, err = r.ReadString('\n')
  632. if err != nil {
  633. if err != io.EOF {
  634. return nil, err
  635. }
  636. if l == "" {
  637. break
  638. }
  639. }
  640. if l = strings.TrimSpace(l); l == "" {
  641. continue
  642. }
  643. if strings.HasPrefix(l, "---") {
  644. break
  645. }
  646. attr := strings.SplitN(l, delimiter, 2)
  647. if len(attr) != 2 {
  648. break
  649. }
  650. key, val := strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1])
  651. var err error
  652. switch key {
  653. case "cycles/second":
  654. if cpuHz, err = strconv.ParseInt(val, 0, 64); err != nil {
  655. return nil, errUnrecognized
  656. }
  657. case "sampling period":
  658. if p.Period, err = strconv.ParseInt(val, 0, 64); err != nil {
  659. return nil, errUnrecognized
  660. }
  661. case "ms since reset":
  662. ms, err := strconv.ParseInt(val, 0, 64)
  663. if err != nil {
  664. return nil, errUnrecognized
  665. }
  666. p.DurationNanos = ms * 1000 * 1000
  667. case "format":
  668. // CPP contentionz profiles don't have format.
  669. return nil, errUnrecognized
  670. case "resolution":
  671. // CPP contentionz profiles don't have resolution.
  672. return nil, errUnrecognized
  673. case "discarded samples":
  674. default:
  675. return nil, errUnrecognized
  676. }
  677. }
  678. locs := make(map[uint64]*Location)
  679. for {
  680. if l = strings.TrimSpace(l); strings.HasPrefix(l, "---") {
  681. break
  682. }
  683. value, addrs, err := parseContentionSample(l, p.Period, cpuHz)
  684. if err != nil {
  685. return nil, err
  686. }
  687. var sloc []*Location
  688. for i, addr := range addrs {
  689. // Addresses from stack traces point to the next instruction after
  690. // each call. Adjust by -1 to land somewhere on the actual call
  691. // (except for the leaf, which is not a call).
  692. if i > 0 {
  693. addr--
  694. }
  695. loc := locs[addr]
  696. if locs[addr] == nil {
  697. loc = &Location{
  698. Address: addr,
  699. }
  700. p.Location = append(p.Location, loc)
  701. locs[addr] = loc
  702. }
  703. sloc = append(sloc, loc)
  704. }
  705. p.Sample = append(p.Sample, &Sample{
  706. Value: value,
  707. Location: sloc,
  708. })
  709. if l, err = r.ReadString('\n'); err != nil {
  710. if err != io.EOF {
  711. return nil, err
  712. }
  713. if l == "" {
  714. break
  715. }
  716. }
  717. }
  718. if err = parseAdditionalSections(l, r, p); err != nil {
  719. return nil, err
  720. }
  721. return p, nil
  722. }
  723. // parseContentionSample parses a single row from a contention profile
  724. // into a new Sample.
  725. func parseContentionSample(line string, period, cpuHz int64) (value []int64, addrs []uint64, err error) {
  726. sampleData := contentionSampleRE.FindStringSubmatch(line)
  727. if sampleData == nil {
  728. return value, addrs, errUnrecognized
  729. }
  730. v1, err := strconv.ParseInt(sampleData[1], 10, 64)
  731. if err != nil {
  732. return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
  733. }
  734. v2, err := strconv.ParseInt(sampleData[2], 10, 64)
  735. if err != nil {
  736. return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
  737. }
  738. // Unsample values if period and cpuHz are available.
  739. // - Delays are scaled to cycles and then to nanoseconds.
  740. // - Contentions are scaled to cycles.
  741. if period > 0 {
  742. if cpuHz > 0 {
  743. cpuGHz := float64(cpuHz) / 1e9
  744. v1 = int64(float64(v1) * float64(period) / cpuGHz)
  745. }
  746. v2 = v2 * period
  747. }
  748. value = []int64{v2, v1}
  749. addrs = parseHexAddresses(sampleData[3])
  750. return value, addrs, nil
  751. }
  752. // parseThread parses a Threadz profile and returns a new Profile.
  753. func parseThread(b []byte) (*Profile, error) {
  754. r := bytes.NewBuffer(b)
  755. var line string
  756. var err error
  757. for {
  758. // Skip past comments and empty lines seeking a real header.
  759. line, err = r.ReadString('\n')
  760. if err != nil {
  761. return nil, err
  762. }
  763. if !isSpaceOrComment(line) {
  764. break
  765. }
  766. }
  767. if m := threadzStartRE.FindStringSubmatch(line); m != nil {
  768. // Advance over initial comments until first stack trace.
  769. for {
  770. line, err = r.ReadString('\n')
  771. if err != nil {
  772. if err != io.EOF {
  773. return nil, err
  774. }
  775. if line == "" {
  776. break
  777. }
  778. }
  779. if sectionTrigger(line) != unrecognizedSection || line[0] == '-' {
  780. break
  781. }
  782. }
  783. } else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  784. return nil, errUnrecognized
  785. }
  786. p := &Profile{
  787. SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
  788. PeriodType: &ValueType{Type: "thread", Unit: "count"},
  789. Period: 1,
  790. }
  791. locs := make(map[uint64]*Location)
  792. // Recognize each thread and populate profile samples.
  793. for sectionTrigger(line) == unrecognizedSection {
  794. if strings.HasPrefix(line, "---- no stack trace for") {
  795. line = ""
  796. break
  797. }
  798. if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  799. return nil, errUnrecognized
  800. }
  801. var addrs []uint64
  802. line, addrs, err = parseThreadSample(r)
  803. if err != nil {
  804. return nil, errUnrecognized
  805. }
  806. if len(addrs) == 0 {
  807. // We got a --same as previous threads--. Bump counters.
  808. if len(p.Sample) > 0 {
  809. s := p.Sample[len(p.Sample)-1]
  810. s.Value[0]++
  811. }
  812. continue
  813. }
  814. var sloc []*Location
  815. for i, addr := range addrs {
  816. // Addresses from stack traces point to the next instruction after
  817. // each call. Adjust by -1 to land somewhere on the actual call
  818. // (except for the leaf, which is not a call).
  819. if i > 0 {
  820. addr--
  821. }
  822. loc := locs[addr]
  823. if locs[addr] == nil {
  824. loc = &Location{
  825. Address: addr,
  826. }
  827. p.Location = append(p.Location, loc)
  828. locs[addr] = loc
  829. }
  830. sloc = append(sloc, loc)
  831. }
  832. p.Sample = append(p.Sample, &Sample{
  833. Value: []int64{1},
  834. Location: sloc,
  835. })
  836. }
  837. if err = parseAdditionalSections(line, r, p); err != nil {
  838. return nil, err
  839. }
  840. return p, nil
  841. }
  842. // parseThreadSample parses a symbolized or unsymbolized stack trace.
  843. // Returns the first line after the traceback, the sample (or nil if
  844. // it hits a 'same-as-previous' marker) and an error.
  845. func parseThreadSample(b *bytes.Buffer) (nextl string, addrs []uint64, err error) {
  846. var l string
  847. sameAsPrevious := false
  848. for {
  849. if l, err = b.ReadString('\n'); err != nil {
  850. if err != io.EOF {
  851. return "", nil, err
  852. }
  853. if l == "" {
  854. break
  855. }
  856. }
  857. if l = strings.TrimSpace(l); l == "" {
  858. continue
  859. }
  860. if strings.HasPrefix(l, "---") {
  861. break
  862. }
  863. if strings.Contains(l, "same as previous thread") {
  864. sameAsPrevious = true
  865. continue
  866. }
  867. addrs = append(addrs, parseHexAddresses(l)...)
  868. }
  869. if sameAsPrevious {
  870. return l, nil, nil
  871. }
  872. return l, addrs, nil
  873. }
  874. // parseAdditionalSections parses any additional sections in the
  875. // profile, ignoring any unrecognized sections.
  876. func parseAdditionalSections(l string, b *bytes.Buffer, p *Profile) (err error) {
  877. for {
  878. if sectionTrigger(l) == memoryMapSection {
  879. break
  880. }
  881. // Ignore any unrecognized sections.
  882. if l, err := b.ReadString('\n'); err != nil {
  883. if err != io.EOF {
  884. return err
  885. }
  886. if l == "" {
  887. break
  888. }
  889. }
  890. }
  891. return p.ParseMemoryMap(b)
  892. }
  893. // ParseProcMaps parses a memory map in the format of /proc/self/maps.
  894. // ParseMemoryMap should be called after setting on a profile to
  895. // associate locations to the corresponding mapping based on their
  896. // address.
  897. func ParseProcMaps(rd io.Reader) ([]*Mapping, error) {
  898. var mapping []*Mapping
  899. b := bufio.NewReader(rd)
  900. var attrs []string
  901. var r *strings.Replacer
  902. const delimiter = "="
  903. for {
  904. l, err := b.ReadString('\n')
  905. if err != nil {
  906. if err != io.EOF {
  907. return nil, err
  908. }
  909. if l == "" {
  910. break
  911. }
  912. }
  913. if l = strings.TrimSpace(l); l == "" {
  914. continue
  915. }
  916. if r != nil {
  917. l = r.Replace(l)
  918. }
  919. m, err := parseMappingEntry(l)
  920. if err != nil {
  921. if err == errUnrecognized {
  922. // Recognize assignments of the form: attr=value, and replace
  923. // $attr with value on subsequent mappings.
  924. if attr := strings.SplitN(l, delimiter, 2); len(attr) == 2 {
  925. attrs = append(attrs, "$"+strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1]))
  926. r = strings.NewReplacer(attrs...)
  927. }
  928. // Ignore any unrecognized entries
  929. continue
  930. }
  931. return nil, err
  932. }
  933. if m == nil {
  934. continue
  935. }
  936. mapping = append(mapping, m)
  937. }
  938. return mapping, nil
  939. }
  940. // ParseMemoryMap parses a memory map in the format of
  941. // /proc/self/maps, and overrides the mappings in the current profile.
  942. // It renumbers the samples and locations in the profile correspondingly.
  943. func (p *Profile) ParseMemoryMap(rd io.Reader) error {
  944. mapping, err := ParseProcMaps(rd)
  945. if err != nil {
  946. return err
  947. }
  948. p.Mapping = append(p.Mapping, mapping...)
  949. p.massageMappings()
  950. p.remapLocationIDs()
  951. p.remapFunctionIDs()
  952. p.remapMappingIDs()
  953. return nil
  954. }
  955. func parseMappingEntry(l string) (*Mapping, error) {
  956. mapping := &Mapping{}
  957. var err error
  958. if me := procMapsRE.FindStringSubmatch(l); len(me) == 9 {
  959. if !strings.Contains(me[3], "x") {
  960. // Skip non-executable entries.
  961. return nil, nil
  962. }
  963. if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  964. return nil, errUnrecognized
  965. }
  966. if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  967. return nil, errUnrecognized
  968. }
  969. if me[4] != "" {
  970. if mapping.Offset, err = strconv.ParseUint(me[4], 16, 64); err != nil {
  971. return nil, errUnrecognized
  972. }
  973. }
  974. mapping.File = me[8]
  975. return mapping, nil
  976. }
  977. if me := briefMapsRE.FindStringSubmatch(l); len(me) == 6 {
  978. if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  979. return nil, errUnrecognized
  980. }
  981. if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  982. return nil, errUnrecognized
  983. }
  984. mapping.File = me[3]
  985. if me[5] != "" {
  986. if mapping.Offset, err = strconv.ParseUint(me[5], 16, 64); err != nil {
  987. return nil, errUnrecognized
  988. }
  989. }
  990. return mapping, nil
  991. }
  992. return nil, errUnrecognized
  993. }
  994. type sectionType int
  995. const (
  996. unrecognizedSection sectionType = iota
  997. memoryMapSection
  998. )
  999. var memoryMapTriggers = []string{
  1000. "--- Memory map: ---",
  1001. "MAPPED_LIBRARIES:",
  1002. }
  1003. func sectionTrigger(line string) sectionType {
  1004. for _, trigger := range memoryMapTriggers {
  1005. if strings.Contains(line, trigger) {
  1006. return memoryMapSection
  1007. }
  1008. }
  1009. return unrecognizedSection
  1010. }
  1011. func (p *Profile) addLegacyFrameInfo() {
  1012. switch {
  1013. case isProfileType(p, heapzSampleTypes):
  1014. p.DropFrames, p.KeepFrames = allocRxStr, allocSkipRxStr
  1015. case isProfileType(p, contentionzSampleTypes):
  1016. p.DropFrames, p.KeepFrames = lockRxStr, ""
  1017. default:
  1018. p.DropFrames, p.KeepFrames = cpuProfilerRxStr, ""
  1019. }
  1020. }
  1021. var heapzSampleTypes = [][]string{
  1022. {"allocations", "size"}, // early Go pprof profiles
  1023. {"objects", "space"},
  1024. {"inuse_objects", "inuse_space"},
  1025. {"alloc_objects", "alloc_space"},
  1026. }
  1027. var contentionzSampleTypes = [][]string{
  1028. {"contentions", "delay"},
  1029. }
  1030. func isProfileType(p *Profile, types [][]string) bool {
  1031. st := p.SampleType
  1032. nextType:
  1033. for _, t := range types {
  1034. if len(st) != len(t) {
  1035. continue
  1036. }
  1037. for i := range st {
  1038. if st[i].Type != t[i] {
  1039. continue nextType
  1040. }
  1041. }
  1042. return true
  1043. }
  1044. return false
  1045. }
  1046. var allocRxStr = strings.Join([]string{
  1047. // POSIX entry points.
  1048. `calloc`,
  1049. `cfree`,
  1050. `malloc`,
  1051. `free`,
  1052. `memalign`,
  1053. `do_memalign`,
  1054. `(__)?posix_memalign`,
  1055. `pvalloc`,
  1056. `valloc`,
  1057. `realloc`,
  1058. // TC malloc.
  1059. `tcmalloc::.*`,
  1060. `tc_calloc`,
  1061. `tc_cfree`,
  1062. `tc_malloc`,
  1063. `tc_free`,
  1064. `tc_memalign`,
  1065. `tc_posix_memalign`,
  1066. `tc_pvalloc`,
  1067. `tc_valloc`,
  1068. `tc_realloc`,
  1069. `tc_new`,
  1070. `tc_delete`,
  1071. `tc_newarray`,
  1072. `tc_deletearray`,
  1073. `tc_new_nothrow`,
  1074. `tc_newarray_nothrow`,
  1075. // Memory-allocation routines on OS X.
  1076. `malloc_zone_malloc`,
  1077. `malloc_zone_calloc`,
  1078. `malloc_zone_valloc`,
  1079. `malloc_zone_realloc`,
  1080. `malloc_zone_memalign`,
  1081. `malloc_zone_free`,
  1082. // Go runtime
  1083. `runtime\..*`,
  1084. // Other misc. memory allocation routines
  1085. `BaseArena::.*`,
  1086. `(::)?do_malloc_no_errno`,
  1087. `(::)?do_malloc_pages`,
  1088. `(::)?do_malloc`,
  1089. `DoSampledAllocation`,
  1090. `MallocedMemBlock::MallocedMemBlock`,
  1091. `_M_allocate`,
  1092. `__builtin_(vec_)?delete`,
  1093. `__builtin_(vec_)?new`,
  1094. `__gnu_cxx::new_allocator::allocate`,
  1095. `__libc_malloc`,
  1096. `__malloc_alloc_template::allocate`,
  1097. `allocate`,
  1098. `cpp_alloc`,
  1099. `operator new(\[\])?`,
  1100. `simple_alloc::allocate`,
  1101. }, `|`)
  1102. var allocSkipRxStr = strings.Join([]string{
  1103. // Preserve Go runtime frames that appear in the middle/bottom of
  1104. // the stack.
  1105. `runtime\.panic`,
  1106. }, `|`)
  1107. var cpuProfilerRxStr = strings.Join([]string{
  1108. `ProfileData::Add`,
  1109. `ProfileData::prof_handler`,
  1110. `CpuProfiler::prof_handler`,
  1111. `__pthread_sighandler`,
  1112. `__restore`,
  1113. }, `|`)
  1114. var lockRxStr = strings.Join([]string{
  1115. `RecordLockProfileData`,
  1116. `(base::)?RecordLockProfileData.*`,
  1117. `(base::)?SubmitMutexProfileData.*`,
  1118. `(base::)?SubmitSpinLockProfileData.*`,
  1119. `(Mutex::)?AwaitCommon.*`,
  1120. `(Mutex::)?Unlock.*`,
  1121. `(Mutex::)?UnlockSlow.*`,
  1122. `(Mutex::)?ReaderUnlock.*`,
  1123. `(MutexLock::)?~MutexLock.*`,
  1124. `(SpinLock::)?Unlock.*`,
  1125. `(SpinLock::)?SlowUnlock.*`,
  1126. `(SpinLockHolder::)?~SpinLockHolder.*`,
  1127. }, `|`)