Brak opisu

legacy_profile.go 32KB

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