You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1226 lines
33 KiB

  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(\S+) 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, err = parseHexAddresses(sampleData[5])
  565. if err != nil {
  566. return nil, 0, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
  567. }
  568. return value, blocksize, addrs, nil
  569. }
  570. // parseHexAddresses extracts hex numbers from a string, attempts to convert
  571. // each to an unsigned 64-bit number and returns the resulting numbers as a
  572. // slice, or an error if the string contains hex numbers which are too large to
  573. // handle (which means a malformed profile).
  574. func parseHexAddresses(s string) ([]uint64, error) {
  575. hexStrings := hexNumberRE.FindAllString(s, -1)
  576. var addrs []uint64
  577. for _, s := range hexStrings {
  578. if addr, err := strconv.ParseUint(s, 0, 64); err == nil {
  579. addrs = append(addrs, addr)
  580. } else {
  581. return nil, fmt.Errorf("failed to parse as hex 64-bit number: %s", s)
  582. }
  583. }
  584. return addrs, nil
  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 mutex or contention profile. There are 2 cases:
  609. // "--- contentionz " for legacy C++ profiles (and backwards compatibility)
  610. // "--- mutex:" or "--- contention:" for profiles generated by the Go runtime.
  611. func parseContention(b []byte) (*Profile, error) {
  612. s := bufio.NewScanner(bytes.NewBuffer(b))
  613. if !s.Scan() {
  614. if err := s.Err(); err != nil {
  615. return nil, err
  616. }
  617. return nil, errUnrecognized
  618. }
  619. switch l := s.Text(); {
  620. case strings.HasPrefix(l, "--- contentionz "):
  621. case strings.HasPrefix(l, "--- mutex:"):
  622. case strings.HasPrefix(l, "--- contention:"):
  623. default:
  624. return nil, errUnrecognized
  625. }
  626. p := &Profile{
  627. PeriodType: &ValueType{Type: "contentions", Unit: "count"},
  628. Period: 1,
  629. SampleType: []*ValueType{
  630. {Type: "contentions", Unit: "count"},
  631. {Type: "delay", Unit: "nanoseconds"},
  632. },
  633. }
  634. var cpuHz int64
  635. // Parse text of the form "attribute = value" before the samples.
  636. const delimiter = "="
  637. for s.Scan() {
  638. line := s.Text()
  639. if line = strings.TrimSpace(line); isSpaceOrComment(line) {
  640. continue
  641. }
  642. if strings.HasPrefix(line, "---") {
  643. break
  644. }
  645. attr := strings.SplitN(line, delimiter, 2)
  646. if len(attr) != 2 {
  647. break
  648. }
  649. key, val := strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1])
  650. var err error
  651. switch key {
  652. case "cycles/second":
  653. if cpuHz, err = strconv.ParseInt(val, 0, 64); err != nil {
  654. return nil, errUnrecognized
  655. }
  656. case "sampling period":
  657. if p.Period, err = strconv.ParseInt(val, 0, 64); err != nil {
  658. return nil, errUnrecognized
  659. }
  660. case "ms since reset":
  661. ms, err := strconv.ParseInt(val, 0, 64)
  662. if err != nil {
  663. return nil, errUnrecognized
  664. }
  665. p.DurationNanos = ms * 1000 * 1000
  666. case "format":
  667. // CPP contentionz profiles don't have format.
  668. return nil, errUnrecognized
  669. case "resolution":
  670. // CPP contentionz profiles don't have resolution.
  671. return nil, errUnrecognized
  672. case "discarded samples":
  673. default:
  674. return nil, errUnrecognized
  675. }
  676. }
  677. if err := s.Err(); err != nil {
  678. return nil, err
  679. }
  680. locs := make(map[uint64]*Location)
  681. for {
  682. line := strings.TrimSpace(s.Text())
  683. if strings.HasPrefix(line, "---") {
  684. break
  685. }
  686. if !isSpaceOrComment(line) {
  687. value, addrs, err := parseContentionSample(line, p.Period, cpuHz)
  688. if err != nil {
  689. return nil, err
  690. }
  691. var sloc []*Location
  692. for _, addr := range addrs {
  693. // Addresses from stack traces point to the next instruction after
  694. // each call. Adjust by -1 to land somewhere on the actual call.
  695. addr--
  696. loc := locs[addr]
  697. if locs[addr] == nil {
  698. loc = &Location{
  699. Address: addr,
  700. }
  701. p.Location = append(p.Location, loc)
  702. locs[addr] = loc
  703. }
  704. sloc = append(sloc, loc)
  705. }
  706. p.Sample = append(p.Sample, &Sample{
  707. Value: value,
  708. Location: sloc,
  709. })
  710. }
  711. if !s.Scan() {
  712. break
  713. }
  714. }
  715. if err := s.Err(); err != nil {
  716. return nil, err
  717. }
  718. if err := parseAdditionalSections(s, 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 nil, nil, errUnrecognized
  729. }
  730. v1, err := strconv.ParseInt(sampleData[1], 10, 64)
  731. if err != nil {
  732. return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
  733. }
  734. v2, err := strconv.ParseInt(sampleData[2], 10, 64)
  735. if err != nil {
  736. return nil, nil, 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, err = parseHexAddresses(sampleData[3])
  750. if err != nil {
  751. return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
  752. }
  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. s := bufio.NewScanner(bytes.NewBuffer(b))
  758. // Skip past comments and empty lines seeking a real header.
  759. for s.Scan() && isSpaceOrComment(s.Text()) {
  760. }
  761. line := s.Text()
  762. if m := threadzStartRE.FindStringSubmatch(line); m != nil {
  763. // Advance over initial comments until first stack trace.
  764. for s.Scan() {
  765. if line = s.Text(); isMemoryMapSentinel(line) || strings.HasPrefix(line, "-") {
  766. break
  767. }
  768. }
  769. } else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  770. return nil, errUnrecognized
  771. }
  772. p := &Profile{
  773. SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
  774. PeriodType: &ValueType{Type: "thread", Unit: "count"},
  775. Period: 1,
  776. }
  777. locs := make(map[uint64]*Location)
  778. // Recognize each thread and populate profile samples.
  779. for !isMemoryMapSentinel(line) {
  780. if strings.HasPrefix(line, "---- no stack trace for") {
  781. line = ""
  782. break
  783. }
  784. if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
  785. return nil, errUnrecognized
  786. }
  787. var addrs []uint64
  788. var err error
  789. line, addrs, err = parseThreadSample(s)
  790. if err != nil {
  791. return nil, err
  792. }
  793. if len(addrs) == 0 {
  794. // We got a --same as previous threads--. Bump counters.
  795. if len(p.Sample) > 0 {
  796. s := p.Sample[len(p.Sample)-1]
  797. s.Value[0]++
  798. }
  799. continue
  800. }
  801. var sloc []*Location
  802. for i, addr := range addrs {
  803. // Addresses from stack traces point to the next instruction after
  804. // each call. Adjust by -1 to land somewhere on the actual call
  805. // (except for the leaf, which is not a call).
  806. if i > 0 {
  807. addr--
  808. }
  809. loc := locs[addr]
  810. if locs[addr] == nil {
  811. loc = &Location{
  812. Address: addr,
  813. }
  814. p.Location = append(p.Location, loc)
  815. locs[addr] = loc
  816. }
  817. sloc = append(sloc, loc)
  818. }
  819. p.Sample = append(p.Sample, &Sample{
  820. Value: []int64{1},
  821. Location: sloc,
  822. })
  823. }
  824. if err := parseAdditionalSections(s, p); err != nil {
  825. return nil, err
  826. }
  827. cleanupDuplicateLocations(p)
  828. return p, nil
  829. }
  830. // parseThreadSample parses a symbolized or unsymbolized stack trace.
  831. // Returns the first line after the traceback, the sample (or nil if
  832. // it hits a 'same-as-previous' marker) and an error.
  833. func parseThreadSample(s *bufio.Scanner) (nextl string, addrs []uint64, err error) {
  834. var line string
  835. sameAsPrevious := false
  836. for s.Scan() {
  837. line = strings.TrimSpace(s.Text())
  838. if line == "" {
  839. continue
  840. }
  841. if strings.HasPrefix(line, "---") {
  842. break
  843. }
  844. if strings.Contains(line, "same as previous thread") {
  845. sameAsPrevious = true
  846. continue
  847. }
  848. curAddrs, err := parseHexAddresses(line)
  849. if err != nil {
  850. return "", nil, fmt.Errorf("malformed sample: %s: %v", line, err)
  851. }
  852. addrs = append(addrs, curAddrs...)
  853. }
  854. if err := s.Err(); err != nil {
  855. return "", nil, err
  856. }
  857. if sameAsPrevious {
  858. return line, nil, nil
  859. }
  860. return line, addrs, nil
  861. }
  862. // parseAdditionalSections parses any additional sections in the
  863. // profile, ignoring any unrecognized sections.
  864. func parseAdditionalSections(s *bufio.Scanner, p *Profile) error {
  865. for !isMemoryMapSentinel(s.Text()) && s.Scan() {
  866. }
  867. if err := s.Err(); err != nil {
  868. return err
  869. }
  870. return p.ParseMemoryMapFromScanner(s)
  871. }
  872. // ParseProcMaps parses a memory map in the format of /proc/self/maps.
  873. // ParseMemoryMap should be called after setting on a profile to
  874. // associate locations to the corresponding mapping based on their
  875. // address.
  876. func ParseProcMaps(rd io.Reader) ([]*Mapping, error) {
  877. s := bufio.NewScanner(rd)
  878. return parseProcMapsFromScanner(s)
  879. }
  880. func parseProcMapsFromScanner(s *bufio.Scanner) ([]*Mapping, error) {
  881. var mapping []*Mapping
  882. var attrs []string
  883. const delimiter = "="
  884. r := strings.NewReplacer()
  885. for s.Scan() {
  886. line := r.Replace(removeLoggingInfo(s.Text()))
  887. m, err := parseMappingEntry(line)
  888. if err != nil {
  889. if err == errUnrecognized {
  890. // Recognize assignments of the form: attr=value, and replace
  891. // $attr with value on subsequent mappings.
  892. if attr := strings.SplitN(line, delimiter, 2); len(attr) == 2 {
  893. attrs = append(attrs, "$"+strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1]))
  894. r = strings.NewReplacer(attrs...)
  895. }
  896. // Ignore any unrecognized entries
  897. continue
  898. }
  899. return nil, err
  900. }
  901. if m == nil {
  902. continue
  903. }
  904. mapping = append(mapping, m)
  905. }
  906. if err := s.Err(); err != nil {
  907. return nil, err
  908. }
  909. return mapping, nil
  910. }
  911. // removeLoggingInfo detects and removes log prefix entries generated
  912. // by the glog package. If no logging prefix is detected, the string
  913. // is returned unmodified.
  914. func removeLoggingInfo(line string) string {
  915. if match := logInfoRE.FindStringIndex(line); match != nil {
  916. return line[match[1]:]
  917. }
  918. return line
  919. }
  920. // ParseMemoryMap parses a memory map in the format of
  921. // /proc/self/maps, and overrides the mappings in the current profile.
  922. // It renumbers the samples and locations in the profile correspondingly.
  923. func (p *Profile) ParseMemoryMap(rd io.Reader) error {
  924. return p.ParseMemoryMapFromScanner(bufio.NewScanner(rd))
  925. }
  926. // ParseMemoryMapFromScanner parses a memory map in the format of
  927. // /proc/self/maps or a variety of legacy format, and overrides the
  928. // mappings in the current profile. It renumbers the samples and
  929. // locations in the profile correspondingly.
  930. func (p *Profile) ParseMemoryMapFromScanner(s *bufio.Scanner) error {
  931. mapping, err := parseProcMapsFromScanner(s)
  932. if err != nil {
  933. return err
  934. }
  935. p.Mapping = append(p.Mapping, mapping...)
  936. p.massageMappings()
  937. p.remapLocationIDs()
  938. p.remapFunctionIDs()
  939. p.remapMappingIDs()
  940. return nil
  941. }
  942. func parseMappingEntry(l string) (*Mapping, error) {
  943. var start, end, perm, file, offset, buildID string
  944. if me := procMapsRE.FindStringSubmatch(l); len(me) == 6 {
  945. start, end, perm, offset, file = me[1], me[2], me[3], me[4], me[5]
  946. } else if me := briefMapsRE.FindStringSubmatch(l); len(me) == 7 {
  947. start, end, perm, file, offset, buildID = me[1], me[2], me[3], me[4], me[5], me[6]
  948. } else {
  949. return nil, errUnrecognized
  950. }
  951. var err error
  952. mapping := &Mapping{
  953. File: file,
  954. BuildID: buildID,
  955. }
  956. if perm != "" && !strings.Contains(perm, "x") {
  957. // Skip non-executable entries.
  958. return nil, nil
  959. }
  960. if mapping.Start, err = strconv.ParseUint(start, 16, 64); err != nil {
  961. return nil, errUnrecognized
  962. }
  963. if mapping.Limit, err = strconv.ParseUint(end, 16, 64); err != nil {
  964. return nil, errUnrecognized
  965. }
  966. if offset != "" {
  967. if mapping.Offset, err = strconv.ParseUint(offset, 16, 64); err != nil {
  968. return nil, errUnrecognized
  969. }
  970. }
  971. return mapping, nil
  972. }
  973. var memoryMapSentinels = []string{
  974. "--- Memory map: ---",
  975. "MAPPED_LIBRARIES:",
  976. }
  977. // isMemoryMapSentinel returns true if the string contains one of the
  978. // known sentinels for memory map information.
  979. func isMemoryMapSentinel(line string) bool {
  980. for _, s := range memoryMapSentinels {
  981. if strings.Contains(line, s) {
  982. return true
  983. }
  984. }
  985. return false
  986. }
  987. func (p *Profile) addLegacyFrameInfo() {
  988. switch {
  989. case isProfileType(p, heapzSampleTypes):
  990. p.DropFrames, p.KeepFrames = allocRxStr, allocSkipRxStr
  991. case isProfileType(p, contentionzSampleTypes):
  992. p.DropFrames, p.KeepFrames = lockRxStr, ""
  993. default:
  994. p.DropFrames, p.KeepFrames = cpuProfilerRxStr, ""
  995. }
  996. }
  997. var heapzSampleTypes = [][]string{
  998. {"allocations", "size"}, // early Go pprof profiles
  999. {"objects", "space"},
  1000. {"inuse_objects", "inuse_space"},
  1001. {"alloc_objects", "alloc_space"},
  1002. {"alloc_objects", "alloc_space", "inuse_objects", "inuse_space"}, // Go pprof legacy profiles
  1003. }
  1004. var contentionzSampleTypes = [][]string{
  1005. {"contentions", "delay"},
  1006. }
  1007. func isProfileType(p *Profile, types [][]string) bool {
  1008. st := p.SampleType
  1009. nextType:
  1010. for _, t := range types {
  1011. if len(st) != len(t) {
  1012. continue
  1013. }
  1014. for i := range st {
  1015. if st[i].Type != t[i] {
  1016. continue nextType
  1017. }
  1018. }
  1019. return true
  1020. }
  1021. return false
  1022. }
  1023. var allocRxStr = strings.Join([]string{
  1024. // POSIX entry points.
  1025. `calloc`,
  1026. `cfree`,
  1027. `malloc`,
  1028. `free`,
  1029. `memalign`,
  1030. `do_memalign`,
  1031. `(__)?posix_memalign`,
  1032. `pvalloc`,
  1033. `valloc`,
  1034. `realloc`,
  1035. // TC malloc.
  1036. `tcmalloc::.*`,
  1037. `tc_calloc`,
  1038. `tc_cfree`,
  1039. `tc_malloc`,
  1040. `tc_free`,
  1041. `tc_memalign`,
  1042. `tc_posix_memalign`,
  1043. `tc_pvalloc`,
  1044. `tc_valloc`,
  1045. `tc_realloc`,
  1046. `tc_new`,
  1047. `tc_delete`,
  1048. `tc_newarray`,
  1049. `tc_deletearray`,
  1050. `tc_new_nothrow`,
  1051. `tc_newarray_nothrow`,
  1052. // Memory-allocation routines on OS X.
  1053. `malloc_zone_malloc`,
  1054. `malloc_zone_calloc`,
  1055. `malloc_zone_valloc`,
  1056. `malloc_zone_realloc`,
  1057. `malloc_zone_memalign`,
  1058. `malloc_zone_free`,
  1059. // Go runtime
  1060. `runtime\..*`,
  1061. // Other misc. memory allocation routines
  1062. `BaseArena::.*`,
  1063. `(::)?do_malloc_no_errno`,
  1064. `(::)?do_malloc_pages`,
  1065. `(::)?do_malloc`,
  1066. `DoSampledAllocation`,
  1067. `MallocedMemBlock::MallocedMemBlock`,
  1068. `_M_allocate`,
  1069. `__builtin_(vec_)?delete`,
  1070. `__builtin_(vec_)?new`,
  1071. `__gnu_cxx::new_allocator::allocate`,
  1072. `__libc_malloc`,
  1073. `__malloc_alloc_template::allocate`,
  1074. `allocate`,
  1075. `cpp_alloc`,
  1076. `operator new(\[\])?`,
  1077. `simple_alloc::allocate`,
  1078. }, `|`)
  1079. var allocSkipRxStr = strings.Join([]string{
  1080. // Preserve Go runtime frames that appear in the middle/bottom of
  1081. // the stack.
  1082. `runtime\.panic`,
  1083. `runtime\.reflectcall`,
  1084. `runtime\.call[0-9]*`,
  1085. }, `|`)
  1086. var cpuProfilerRxStr = strings.Join([]string{
  1087. `ProfileData::Add`,
  1088. `ProfileData::prof_handler`,
  1089. `CpuProfiler::prof_handler`,
  1090. `__pthread_sighandler`,
  1091. `__restore`,
  1092. }, `|`)
  1093. var lockRxStr = strings.Join([]string{
  1094. `RecordLockProfileData`,
  1095. `(base::)?RecordLockProfileData.*`,
  1096. `(base::)?SubmitMutexProfileData.*`,
  1097. `(base::)?SubmitSpinLockProfileData.*`,
  1098. `(base::Mutex::)?AwaitCommon.*`,
  1099. `(base::Mutex::)?Unlock.*`,
  1100. `(base::Mutex::)?UnlockSlow.*`,
  1101. `(base::Mutex::)?ReaderUnlock.*`,
  1102. `(base::MutexLock::)?~MutexLock.*`,
  1103. `(Mutex::)?AwaitCommon.*`,
  1104. `(Mutex::)?Unlock.*`,
  1105. `(Mutex::)?UnlockSlow.*`,
  1106. `(Mutex::)?ReaderUnlock.*`,
  1107. `(MutexLock::)?~MutexLock.*`,
  1108. `(SpinLock::)?Unlock.*`,
  1109. `(SpinLock::)?SlowUnlock.*`,
  1110. `(SpinLockHolder::)?~SpinLockHolder.*`,
  1111. }, `|`)