暂无描述

legacy_profile.go 31KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. if err := p.ParseMemoryMap(bytes.NewBuffer(b)); err != nil {
  338. return nil, err
  339. }
  340. cleanupDuplicateLocations(p)
  341. return p, nil
  342. }
  343. func cleanupDuplicateLocations(p *Profile) {
  344. // The profile handler may duplicate the leaf frame, because it gets
  345. // its address both from stack unwinding and from the signal
  346. // context. Detect this and delete the duplicate, which has been
  347. // adjusted by -1. The leaf address should not be adjusted as it is
  348. // not a call.
  349. for _, s := range p.Sample {
  350. if len(s.Location) > 1 && s.Location[0].Address == s.Location[1].Address+1 {
  351. s.Location = append(s.Location[:1], s.Location[2:]...)
  352. }
  353. }
  354. }
  355. // parseCPUSamples parses a collection of profilez samples from a
  356. // profile.
  357. //
  358. // profilez samples are a repeated sequence of stack frames of the
  359. // form:
  360. // 1st word -- The number of times this stack was encountered.
  361. // 2nd word -- The size of the stack (StackSize).
  362. // 3rd word -- The first address on the stack.
  363. // ...
  364. // StackSize + 2 -- The last address on the stack
  365. // The last stack trace is of the form:
  366. // 1st word -- 0
  367. // 2nd word -- 1
  368. // 3rd word -- 0
  369. //
  370. // Addresses from stack traces may point to the next instruction after
  371. // each call. Optionally adjust by -1 to land somewhere on the actual
  372. // call (except for the leaf, which is not a call).
  373. func parseCPUSamples(b []byte, parse func(b []byte) (uint64, []byte), adjust bool, p *Profile) ([]byte, map[uint64]*Location, error) {
  374. locs := make(map[uint64]*Location)
  375. for len(b) > 0 {
  376. var count, nstk uint64
  377. count, b = parse(b)
  378. nstk, b = parse(b)
  379. if b == nil || nstk > uint64(len(b)/4) {
  380. return nil, nil, errUnrecognized
  381. }
  382. var sloc []*Location
  383. addrs := make([]uint64, nstk)
  384. for i := 0; i < int(nstk); i++ {
  385. addrs[i], b = parse(b)
  386. }
  387. if count == 0 && nstk == 1 && addrs[0] == 0 {
  388. // End of data marker
  389. break
  390. }
  391. for i, addr := range addrs {
  392. if adjust && i > 0 {
  393. addr--
  394. }
  395. loc := locs[addr]
  396. if loc == nil {
  397. loc = &Location{
  398. Address: addr,
  399. }
  400. locs[addr] = loc
  401. p.Location = append(p.Location, loc)
  402. }
  403. sloc = append(sloc, loc)
  404. }
  405. p.Sample = append(p.Sample,
  406. &Sample{
  407. Value: []int64{int64(count), int64(count) * int64(p.Period)},
  408. Location: sloc,
  409. })
  410. }
  411. // Reached the end without finding the EOD marker.
  412. return b, locs, nil
  413. }
  414. // parseHeap parses a heapz legacy or a growthz profile and
  415. // returns a newly populated Profile.
  416. func parseHeap(b []byte) (p *Profile, err error) {
  417. r := bytes.NewBuffer(b)
  418. l, err := r.ReadString('\n')
  419. if err != nil {
  420. return nil, errUnrecognized
  421. }
  422. p = &Profile{}
  423. sampling := ""
  424. hasAlloc := false
  425. p.PeriodType = &ValueType{Type: "space", Unit: "bytes"}
  426. if header := heapHeaderRE.FindStringSubmatch(l); header != nil {
  427. sampling, p.Period, hasAlloc, err = parseHeapHeader(l)
  428. if err != nil {
  429. return nil, err
  430. }
  431. } else if header = growthHeaderRE.FindStringSubmatch(l); header != nil {
  432. p.Period = 1
  433. } else if header = fragmentationHeaderRE.FindStringSubmatch(l); header != nil {
  434. p.Period = 1
  435. } else {
  436. return nil, errUnrecognized
  437. }
  438. if hasAlloc {
  439. // Put alloc before inuse so that default pprof selection
  440. // will prefer inuse_space.
  441. p.SampleType = []*ValueType{
  442. {Type: "alloc_objects", Unit: "count"},
  443. {Type: "alloc_space", Unit: "bytes"},
  444. {Type: "inuse_objects", Unit: "count"},
  445. {Type: "inuse_space", Unit: "bytes"},
  446. }
  447. } else {
  448. p.SampleType = []*ValueType{
  449. {Type: "objects", Unit: "count"},
  450. {Type: "space", Unit: "bytes"},
  451. }
  452. }
  453. locs := make(map[uint64]*Location)
  454. for {
  455. l, err = r.ReadString('\n')
  456. if err != nil {
  457. if err != io.EOF {
  458. return nil, err
  459. }
  460. if l == "" {
  461. break
  462. }
  463. }
  464. if isSpaceOrComment(l) {
  465. continue
  466. }
  467. l = strings.TrimSpace(l)
  468. if sectionTrigger(l) != unrecognizedSection {
  469. break
  470. }
  471. value, blocksize, addrs, err := parseHeapSample(l, p.Period, sampling, hasAlloc)
  472. if err != nil {
  473. return nil, err
  474. }
  475. var sloc []*Location
  476. for i, addr := range addrs {
  477. // Addresses from stack traces point to the next instruction after
  478. // each call. Adjust by -1 to land somewhere on the actual call
  479. // (except for the leaf, which is not a call).
  480. if i > 0 {
  481. addr--
  482. }
  483. loc := locs[addr]
  484. if locs[addr] == nil {
  485. loc = &Location{
  486. Address: addr,
  487. }
  488. p.Location = append(p.Location, loc)
  489. locs[addr] = loc
  490. }
  491. sloc = append(sloc, loc)
  492. }
  493. p.Sample = append(p.Sample, &Sample{
  494. Value: value,
  495. Location: sloc,
  496. NumLabel: map[string][]int64{"bytes": []int64{blocksize}},
  497. })
  498. }
  499. if err = parseAdditionalSections(l, r, p); err != nil {
  500. return nil, err
  501. }
  502. return p, nil
  503. }
  504. func parseHeapHeader(line string) (sampling string, period int64, hasAlloc bool, err error) {
  505. header := heapHeaderRE.FindStringSubmatch(line)
  506. if header == nil {
  507. return "", 0, false, errUnrecognized
  508. }
  509. if len(header[6]) > 0 {
  510. if period, err = strconv.ParseInt(string(header[6]), 10, 64); err != nil {
  511. return "", 0, false, errUnrecognized
  512. }
  513. }
  514. if (header[3] != header[1] && header[3] != "0") || (header[4] != header[2] && header[4] != "0") {
  515. hasAlloc = true
  516. }
  517. switch header[5] {
  518. case "heapz_v2", "heap_v2":
  519. return "v2", period, hasAlloc, nil
  520. case "heapprofile":
  521. return "", 1, hasAlloc, nil
  522. case "heap":
  523. return "v2", period / 2, hasAlloc, nil
  524. default:
  525. return "", 0, false, errUnrecognized
  526. }
  527. }
  528. // parseHeapSample parses a single row from a heap profile into a new Sample.
  529. func parseHeapSample(line string, rate int64, sampling string, includeAlloc bool) (value []int64, blocksize int64, addrs []uint64, err error) {
  530. sampleData := heapSampleRE.FindStringSubmatch(line)
  531. if len(sampleData) != 6 {
  532. return nil, 0, nil, fmt.Errorf("unexpected number of sample values: got %d, want 6", len(sampleData))
  533. }
  534. // This is a local-scoped helper function to avoid needing to pass
  535. // around rate, sampling and many return parameters.
  536. addValues := func(countString, sizeString string, label string) error {
  537. count, err := strconv.ParseInt(countString, 10, 64)
  538. if err != nil {
  539. return fmt.Errorf("malformed sample: %s: %v", line, err)
  540. }
  541. size, err := strconv.ParseInt(sizeString, 10, 64)
  542. if err != nil {
  543. return fmt.Errorf("malformed sample: %s: %v", line, err)
  544. }
  545. if count == 0 && size != 0 {
  546. return fmt.Errorf("%s count was 0 but %s bytes was %d", label, label, size)
  547. }
  548. if count != 0 {
  549. blocksize = size / count
  550. if sampling == "v2" {
  551. count, size = scaleHeapSample(count, size, rate)
  552. }
  553. }
  554. value = append(value, count, size)
  555. return nil
  556. }
  557. if includeAlloc {
  558. if err := addValues(sampleData[3], sampleData[4], "allocation"); err != nil {
  559. return nil, 0, nil, err
  560. }
  561. }
  562. if err := addValues(sampleData[1], sampleData[2], "inuse"); err != nil {
  563. return nil, 0, nil, err
  564. }
  565. addrs = parseHexAddresses(sampleData[5])
  566. return value, blocksize, addrs, nil
  567. }
  568. // extractHexAddresses extracts hex numbers from a string and returns
  569. // them, together with their numeric value, in a slice.
  570. func extractHexAddresses(s string) ([]string, []uint64) {
  571. hexStrings := hexNumberRE.FindAllString(s, -1)
  572. var ids []uint64
  573. for _, s := range hexStrings {
  574. if id, err := strconv.ParseUint(s, 0, 64); err == nil {
  575. ids = append(ids, id)
  576. } else {
  577. // Do not expect any parsing failures due to the regexp matching.
  578. panic("failed to parse hex value:" + s)
  579. }
  580. }
  581. return hexStrings, ids
  582. }
  583. // parseHexAddresses parses hex numbers from a string and returns them
  584. // in a slice.
  585. func parseHexAddresses(s string) []uint64 {
  586. _, ids := extractHexAddresses(s)
  587. return ids
  588. }
  589. // scaleHeapSample adjusts the data from a heapz Sample to
  590. // account for its probability of appearing in the collected
  591. // data. heapz profiles are a sampling of the memory allocations
  592. // requests in a program. We estimate the unsampled value by dividing
  593. // each collected sample by its probability of appearing in the
  594. // profile. heapz v2 profiles rely on a poisson process to determine
  595. // which samples to collect, based on the desired average collection
  596. // rate R. The probability of a sample of size S to appear in that
  597. // profile is 1-exp(-S/R).
  598. func scaleHeapSample(count, size, rate int64) (int64, int64) {
  599. if count == 0 || size == 0 {
  600. return 0, 0
  601. }
  602. if rate <= 1 {
  603. // if rate==1 all samples were collected so no adjustment is needed.
  604. // if rate<1 treat as unknown and skip scaling.
  605. return count, size
  606. }
  607. avgSize := float64(size) / float64(count)
  608. scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
  609. return int64(float64(count) * scale), int64(float64(size) * scale)
  610. }
  611. // parseContention parses a contentionz profile and returns a newly
  612. // populated Profile.
  613. func parseContention(b []byte) (p *Profile, err error) {
  614. r := bytes.NewBuffer(b)
  615. l, err := r.ReadString('\n')
  616. if err != nil {
  617. return nil, errUnrecognized
  618. }
  619. if !strings.HasPrefix(l, "--- contention") {
  620. return nil, errUnrecognized
  621. }
  622. p = &Profile{
  623. PeriodType: &ValueType{Type: "contentions", Unit: "count"},
  624. Period: 1,
  625. SampleType: []*ValueType{
  626. {Type: "contentions", Unit: "count"},
  627. {Type: "delay", Unit: "nanoseconds"},
  628. },
  629. }
  630. var cpuHz int64
  631. // Parse text of the form "attribute = value" before the samples.
  632. const delimiter = "="
  633. for {
  634. l, err = r.ReadString('\n')
  635. if err != nil {
  636. if err != io.EOF {
  637. return nil, err
  638. }
  639. if l == "" {
  640. break
  641. }
  642. }
  643. if l = strings.TrimSpace(l); l == "" {
  644. continue
  645. }
  646. if strings.HasPrefix(l, "---") {
  647. break
  648. }
  649. attr := strings.SplitN(l, delimiter, 2)
  650. if len(attr) != 2 {
  651. break
  652. }
  653. key, val := strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1])
  654. var err error
  655. switch key {
  656. case "cycles/second":
  657. if cpuHz, err = strconv.ParseInt(val, 0, 64); err != nil {
  658. return nil, errUnrecognized
  659. }
  660. case "sampling period":
  661. if p.Period, err = strconv.ParseInt(val, 0, 64); err != nil {
  662. return nil, errUnrecognized
  663. }
  664. case "ms since reset":
  665. ms, err := strconv.ParseInt(val, 0, 64)
  666. if err != nil {
  667. return nil, errUnrecognized
  668. }
  669. p.DurationNanos = ms * 1000 * 1000
  670. case "format":
  671. // CPP contentionz profiles don't have format.
  672. return nil, errUnrecognized
  673. case "resolution":
  674. // CPP contentionz profiles don't have resolution.
  675. return nil, errUnrecognized
  676. case "discarded samples":
  677. default:
  678. return nil, errUnrecognized
  679. }
  680. }
  681. locs := make(map[uint64]*Location)
  682. for {
  683. if l = strings.TrimSpace(l); strings.HasPrefix(l, "---") {
  684. break
  685. }
  686. value, addrs, err := parseContentionSample(l, p.Period, cpuHz)
  687. if err != nil {
  688. return nil, err
  689. }
  690. var sloc []*Location
  691. for i, addr := range addrs {
  692. // Addresses from stack traces point to the next instruction after
  693. // each call. Adjust by -1 to land somewhere on the actual call
  694. // (except for the leaf, which is not a call).
  695. if i > 0 {
  696. addr--
  697. }
  698. loc := locs[addr]
  699. if locs[addr] == nil {
  700. loc = &Location{
  701. Address: addr,
  702. }
  703. p.Location = append(p.Location, loc)
  704. locs[addr] = loc
  705. }
  706. sloc = append(sloc, loc)
  707. }
  708. p.Sample = append(p.Sample, &Sample{
  709. Value: value,
  710. Location: sloc,
  711. })
  712. if l, err = r.ReadString('\n'); err != nil {
  713. if err != io.EOF {
  714. return nil, err
  715. }
  716. if l == "" {
  717. break
  718. }
  719. }
  720. }
  721. if err = parseAdditionalSections(l, r, p); err != nil {
  722. return nil, err
  723. }
  724. return p, nil
  725. }
  726. // parseContentionSample parses a single row from a contention profile
  727. // into a new Sample.
  728. func parseContentionSample(line string, period, cpuHz int64) (value []int64, addrs []uint64, err error) {
  729. sampleData := contentionSampleRE.FindStringSubmatch(line)
  730. if sampleData == nil {
  731. return value, addrs, errUnrecognized
  732. }
  733. v1, err := strconv.ParseInt(sampleData[1], 10, 64)
  734. if err != nil {
  735. return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
  736. }
  737. v2, err := strconv.ParseInt(sampleData[2], 10, 64)
  738. if err != nil {
  739. return value, addrs, fmt.Errorf("malformed sample: %s: %v", line, err)
  740. }
  741. // Unsample values if period and cpuHz are available.
  742. // - Delays are scaled to cycles and then to nanoseconds.
  743. // - Contentions are scaled to cycles.
  744. if period > 0 {
  745. if cpuHz > 0 {
  746. cpuGHz := float64(cpuHz) / 1e9
  747. v1 = int64(float64(v1) * float64(period) / cpuGHz)
  748. }
  749. v2 = v2 * period
  750. }
  751. value = []int64{v2, v1}
  752. addrs = parseHexAddresses(sampleData[3])
  753. return value, addrs, nil
  754. }
  755. // parseThread parses a Threadz profile and returns a new Profile.
  756. func parseThread(b []byte) (*Profile, error) {
  757. r := bytes.NewBuffer(b)
  758. var line string
  759. var err error
  760. for {
  761. // Skip past comments and empty lines seeking a real header.
  762. line, err = r.ReadString('\n')
  763. if err != nil {
  764. return nil, err
  765. }
  766. if !isSpaceOrComment(line) {
  767. break
  768. }
  769. }
  770. if m := threadzStartRE.FindStringSubmatch(line); m != nil {
  771. // Advance over initial comments until first stack trace.
  772. for {
  773. line, err = r.ReadString('\n')
  774. if err != nil {
  775. if err != io.EOF {
  776. return nil, err
  777. }
  778. if line == "" {
  779. break
  780. }
  781. }
  782. if sectionTrigger(line) != unrecognizedSection || line[0] == '-' {
  783. break
  784. }
  785. }
  786. } else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  787. return nil, errUnrecognized
  788. }
  789. p := &Profile{
  790. SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
  791. PeriodType: &ValueType{Type: "thread", Unit: "count"},
  792. Period: 1,
  793. }
  794. locs := make(map[uint64]*Location)
  795. // Recognize each thread and populate profile samples.
  796. for sectionTrigger(line) == unrecognizedSection {
  797. if strings.HasPrefix(line, "---- no stack trace for") {
  798. line = ""
  799. break
  800. }
  801. if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  802. return nil, errUnrecognized
  803. }
  804. var addrs []uint64
  805. line, addrs, err = parseThreadSample(r)
  806. if err != nil {
  807. return nil, errUnrecognized
  808. }
  809. if len(addrs) == 0 {
  810. // We got a --same as previous threads--. Bump counters.
  811. if len(p.Sample) > 0 {
  812. s := p.Sample[len(p.Sample)-1]
  813. s.Value[0]++
  814. }
  815. continue
  816. }
  817. var sloc []*Location
  818. for i, addr := range addrs {
  819. // Addresses from stack traces point to the next instruction after
  820. // each call. Adjust by -1 to land somewhere on the actual call
  821. // (except for the leaf, which is not a call).
  822. if i > 0 {
  823. addr--
  824. }
  825. loc := locs[addr]
  826. if locs[addr] == nil {
  827. loc = &Location{
  828. Address: addr,
  829. }
  830. p.Location = append(p.Location, loc)
  831. locs[addr] = loc
  832. }
  833. sloc = append(sloc, loc)
  834. }
  835. p.Sample = append(p.Sample, &Sample{
  836. Value: []int64{1},
  837. Location: sloc,
  838. })
  839. }
  840. if err = parseAdditionalSections(line, r, p); err != nil {
  841. return nil, err
  842. }
  843. cleanupDuplicateLocations(p)
  844. return p, nil
  845. }
  846. // parseThreadSample parses a symbolized or unsymbolized stack trace.
  847. // Returns the first line after the traceback, the sample (or nil if
  848. // it hits a 'same-as-previous' marker) and an error.
  849. func parseThreadSample(b *bytes.Buffer) (nextl string, addrs []uint64, err error) {
  850. var l string
  851. sameAsPrevious := false
  852. for {
  853. if l, err = b.ReadString('\n'); err != nil {
  854. if err != io.EOF {
  855. return "", nil, err
  856. }
  857. if l == "" {
  858. break
  859. }
  860. }
  861. if l = strings.TrimSpace(l); l == "" {
  862. continue
  863. }
  864. if strings.HasPrefix(l, "---") {
  865. break
  866. }
  867. if strings.Contains(l, "same as previous thread") {
  868. sameAsPrevious = true
  869. continue
  870. }
  871. addrs = append(addrs, parseHexAddresses(l)...)
  872. }
  873. if sameAsPrevious {
  874. return l, nil, nil
  875. }
  876. return l, addrs, nil
  877. }
  878. // parseAdditionalSections parses any additional sections in the
  879. // profile, ignoring any unrecognized sections.
  880. func parseAdditionalSections(l string, b *bytes.Buffer, p *Profile) error {
  881. for {
  882. if sectionTrigger(l) == memoryMapSection {
  883. break
  884. }
  885. // Ignore any unrecognized sections.
  886. var err error
  887. if l, err = b.ReadString('\n'); err != nil {
  888. if err != io.EOF {
  889. return err
  890. }
  891. if l == "" {
  892. break
  893. }
  894. }
  895. }
  896. return p.ParseMemoryMap(b)
  897. }
  898. // ParseProcMaps parses a memory map in the format of /proc/self/maps.
  899. // ParseMemoryMap should be called after setting on a profile to
  900. // associate locations to the corresponding mapping based on their
  901. // address.
  902. func ParseProcMaps(rd io.Reader) ([]*Mapping, error) {
  903. var mapping []*Mapping
  904. b := bufio.NewReader(rd)
  905. var attrs []string
  906. var r *strings.Replacer
  907. const delimiter = "="
  908. for {
  909. l, err := b.ReadString('\n')
  910. if err != nil {
  911. if err != io.EOF {
  912. return nil, err
  913. }
  914. if l == "" {
  915. break
  916. }
  917. }
  918. if l = strings.TrimSpace(l); l == "" {
  919. continue
  920. }
  921. if r != nil {
  922. l = r.Replace(l)
  923. }
  924. m, err := parseMappingEntry(l)
  925. if err != nil {
  926. if err == errUnrecognized {
  927. // Recognize assignments of the form: attr=value, and replace
  928. // $attr with value on subsequent mappings.
  929. if attr := strings.SplitN(l, delimiter, 2); len(attr) == 2 {
  930. attrs = append(attrs, "$"+strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1]))
  931. r = strings.NewReplacer(attrs...)
  932. }
  933. // Ignore any unrecognized entries
  934. continue
  935. }
  936. return nil, err
  937. }
  938. if m == nil {
  939. continue
  940. }
  941. mapping = append(mapping, m)
  942. }
  943. return mapping, nil
  944. }
  945. // ParseMemoryMap parses a memory map in the format of
  946. // /proc/self/maps, and overrides the mappings in the current profile.
  947. // It renumbers the samples and locations in the profile correspondingly.
  948. func (p *Profile) ParseMemoryMap(rd io.Reader) error {
  949. mapping, err := ParseProcMaps(rd)
  950. if err != nil {
  951. return err
  952. }
  953. p.Mapping = append(p.Mapping, mapping...)
  954. p.massageMappings()
  955. p.remapLocationIDs()
  956. p.remapFunctionIDs()
  957. p.remapMappingIDs()
  958. return nil
  959. }
  960. func parseMappingEntry(l string) (*Mapping, error) {
  961. mapping := &Mapping{}
  962. var err error
  963. if me := procMapsRE.FindStringSubmatch(l); len(me) == 9 {
  964. if !strings.Contains(me[3], "x") {
  965. // Skip non-executable entries.
  966. return nil, nil
  967. }
  968. if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  969. return nil, errUnrecognized
  970. }
  971. if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  972. return nil, errUnrecognized
  973. }
  974. if me[4] != "" {
  975. if mapping.Offset, err = strconv.ParseUint(me[4], 16, 64); err != nil {
  976. return nil, errUnrecognized
  977. }
  978. }
  979. mapping.File = me[8]
  980. return mapping, nil
  981. }
  982. if me := briefMapsRE.FindStringSubmatch(l); len(me) == 6 {
  983. if mapping.Start, err = strconv.ParseUint(me[1], 16, 64); err != nil {
  984. return nil, errUnrecognized
  985. }
  986. if mapping.Limit, err = strconv.ParseUint(me[2], 16, 64); err != nil {
  987. return nil, errUnrecognized
  988. }
  989. mapping.File = me[3]
  990. if me[5] != "" {
  991. if mapping.Offset, err = strconv.ParseUint(me[5], 16, 64); err != nil {
  992. return nil, errUnrecognized
  993. }
  994. }
  995. return mapping, nil
  996. }
  997. return nil, errUnrecognized
  998. }
  999. type sectionType int
  1000. const (
  1001. unrecognizedSection sectionType = iota
  1002. memoryMapSection
  1003. )
  1004. var memoryMapTriggers = []string{
  1005. "--- Memory map: ---",
  1006. "MAPPED_LIBRARIES:",
  1007. }
  1008. func sectionTrigger(line string) sectionType {
  1009. for _, trigger := range memoryMapTriggers {
  1010. if strings.Contains(line, trigger) {
  1011. return memoryMapSection
  1012. }
  1013. }
  1014. return unrecognizedSection
  1015. }
  1016. func (p *Profile) addLegacyFrameInfo() {
  1017. switch {
  1018. case isProfileType(p, heapzSampleTypes):
  1019. p.DropFrames, p.KeepFrames = allocRxStr, allocSkipRxStr
  1020. case isProfileType(p, contentionzSampleTypes):
  1021. p.DropFrames, p.KeepFrames = lockRxStr, ""
  1022. default:
  1023. p.DropFrames, p.KeepFrames = cpuProfilerRxStr, ""
  1024. }
  1025. }
  1026. var heapzSampleTypes = [][]string{
  1027. {"allocations", "size"}, // early Go pprof profiles
  1028. {"objects", "space"},
  1029. {"inuse_objects", "inuse_space"},
  1030. {"alloc_objects", "alloc_space"},
  1031. }
  1032. var contentionzSampleTypes = [][]string{
  1033. {"contentions", "delay"},
  1034. }
  1035. func isProfileType(p *Profile, types [][]string) bool {
  1036. st := p.SampleType
  1037. nextType:
  1038. for _, t := range types {
  1039. if len(st) != len(t) {
  1040. continue
  1041. }
  1042. for i := range st {
  1043. if st[i].Type != t[i] {
  1044. continue nextType
  1045. }
  1046. }
  1047. return true
  1048. }
  1049. return false
  1050. }
  1051. var allocRxStr = strings.Join([]string{
  1052. // POSIX entry points.
  1053. `calloc`,
  1054. `cfree`,
  1055. `malloc`,
  1056. `free`,
  1057. `memalign`,
  1058. `do_memalign`,
  1059. `(__)?posix_memalign`,
  1060. `pvalloc`,
  1061. `valloc`,
  1062. `realloc`,
  1063. // TC malloc.
  1064. `tcmalloc::.*`,
  1065. `tc_calloc`,
  1066. `tc_cfree`,
  1067. `tc_malloc`,
  1068. `tc_free`,
  1069. `tc_memalign`,
  1070. `tc_posix_memalign`,
  1071. `tc_pvalloc`,
  1072. `tc_valloc`,
  1073. `tc_realloc`,
  1074. `tc_new`,
  1075. `tc_delete`,
  1076. `tc_newarray`,
  1077. `tc_deletearray`,
  1078. `tc_new_nothrow`,
  1079. `tc_newarray_nothrow`,
  1080. // Memory-allocation routines on OS X.
  1081. `malloc_zone_malloc`,
  1082. `malloc_zone_calloc`,
  1083. `malloc_zone_valloc`,
  1084. `malloc_zone_realloc`,
  1085. `malloc_zone_memalign`,
  1086. `malloc_zone_free`,
  1087. // Go runtime
  1088. `runtime\..*`,
  1089. // Other misc. memory allocation routines
  1090. `BaseArena::.*`,
  1091. `(::)?do_malloc_no_errno`,
  1092. `(::)?do_malloc_pages`,
  1093. `(::)?do_malloc`,
  1094. `DoSampledAllocation`,
  1095. `MallocedMemBlock::MallocedMemBlock`,
  1096. `_M_allocate`,
  1097. `__builtin_(vec_)?delete`,
  1098. `__builtin_(vec_)?new`,
  1099. `__gnu_cxx::new_allocator::allocate`,
  1100. `__libc_malloc`,
  1101. `__malloc_alloc_template::allocate`,
  1102. `allocate`,
  1103. `cpp_alloc`,
  1104. `operator new(\[\])?`,
  1105. `simple_alloc::allocate`,
  1106. }, `|`)
  1107. var allocSkipRxStr = strings.Join([]string{
  1108. // Preserve Go runtime frames that appear in the middle/bottom of
  1109. // the stack.
  1110. `runtime\.panic`,
  1111. }, `|`)
  1112. var cpuProfilerRxStr = strings.Join([]string{
  1113. `ProfileData::Add`,
  1114. `ProfileData::prof_handler`,
  1115. `CpuProfiler::prof_handler`,
  1116. `__pthread_sighandler`,
  1117. `__restore`,
  1118. }, `|`)
  1119. var lockRxStr = strings.Join([]string{
  1120. `RecordLockProfileData`,
  1121. `(base::)?RecordLockProfileData.*`,
  1122. `(base::)?SubmitMutexProfileData.*`,
  1123. `(base::)?SubmitSpinLockProfileData.*`,
  1124. `(Mutex::)?AwaitCommon.*`,
  1125. `(Mutex::)?Unlock.*`,
  1126. `(Mutex::)?UnlockSlow.*`,
  1127. `(Mutex::)?ReaderUnlock.*`,
  1128. `(MutexLock::)?~MutexLock.*`,
  1129. `(SpinLock::)?Unlock.*`,
  1130. `(SpinLock::)?SlowUnlock.*`,
  1131. `(SpinLockHolder::)?~SpinLockHolder.*`,
  1132. }, `|`)