Keine Beschreibung

profile.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package profile provides a representation of profile.proto and
  15. // methods to encode/decode profiles in this format.
  16. package profile
  17. import (
  18. "bytes"
  19. "compress/gzip"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "path/filepath"
  24. "regexp"
  25. "sort"
  26. "strings"
  27. "time"
  28. )
  29. // Profile is an in-memory representation of profile.proto.
  30. type Profile struct {
  31. SampleType []*ValueType
  32. DefaultSampleType string
  33. Sample []*Sample
  34. Mapping []*Mapping
  35. Location []*Location
  36. Function []*Function
  37. Comments []string
  38. DropFrames string
  39. KeepFrames string
  40. TimeNanos int64
  41. DurationNanos int64
  42. PeriodType *ValueType
  43. Period int64
  44. commentX []int64
  45. dropFramesX int64
  46. keepFramesX int64
  47. stringTable []string
  48. defaultSampleTypeX int64
  49. }
  50. // ValueType corresponds to Profile.ValueType
  51. type ValueType struct {
  52. Type string // cpu, wall, inuse_space, etc
  53. Unit string // seconds, nanoseconds, bytes, etc
  54. typeX int64
  55. unitX int64
  56. }
  57. // Sample corresponds to Profile.Sample
  58. type Sample struct {
  59. Location []*Location
  60. Value []int64
  61. Label map[string][]string
  62. NumLabel map[string][]int64
  63. locationIDX []uint64
  64. labelX []label
  65. }
  66. // label corresponds to Profile.Label
  67. type label struct {
  68. keyX int64
  69. // Exactly one of the two following values must be set
  70. strX int64
  71. numX int64 // Integer value for this label
  72. }
  73. // Mapping corresponds to Profile.Mapping
  74. type Mapping struct {
  75. ID uint64
  76. Start uint64
  77. Limit uint64
  78. Offset uint64
  79. File string
  80. BuildID string
  81. HasFunctions bool
  82. HasFilenames bool
  83. HasLineNumbers bool
  84. HasInlineFrames bool
  85. fileX int64
  86. buildIDX int64
  87. }
  88. // Location corresponds to Profile.Location
  89. type Location struct {
  90. ID uint64
  91. Mapping *Mapping
  92. Address uint64
  93. Line []Line
  94. mappingIDX uint64
  95. }
  96. // Line corresponds to Profile.Line
  97. type Line struct {
  98. Function *Function
  99. Line int64
  100. functionIDX uint64
  101. }
  102. // Function corresponds to Profile.Function
  103. type Function struct {
  104. ID uint64
  105. Name string
  106. SystemName string
  107. Filename string
  108. StartLine int64
  109. nameX int64
  110. systemNameX int64
  111. filenameX int64
  112. }
  113. // Parse parses a profile and checks for its validity. The input
  114. // may be a gzip-compressed encoded protobuf or one of many legacy
  115. // profile formats which may be unsupported in the future.
  116. func Parse(r io.Reader) (*Profile, error) {
  117. data, err := ioutil.ReadAll(r)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return ParseData(data)
  122. }
  123. // ParseData parses a profile from a buffer and checks for its
  124. // validity.
  125. func ParseData(data []byte) (*Profile, error) {
  126. var p *Profile
  127. var err error
  128. if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
  129. gz, err := gzip.NewReader(bytes.NewBuffer(data))
  130. if err == nil {
  131. data, err = ioutil.ReadAll(gz)
  132. }
  133. if err != nil {
  134. return nil, fmt.Errorf("decompressing profile: %v", err)
  135. }
  136. }
  137. if p, err = ParseUncompressed(data); err != nil && err != errNoData {
  138. p, err = parseLegacy(data)
  139. }
  140. if err != nil {
  141. return nil, fmt.Errorf("parsing profile: %v", err)
  142. }
  143. if err := p.CheckValid(); err != nil {
  144. return nil, fmt.Errorf("malformed profile: %v", err)
  145. }
  146. return p, nil
  147. }
  148. var errUnrecognized = fmt.Errorf("unrecognized profile format")
  149. var errMalformed = fmt.Errorf("malformed profile format")
  150. var errNoData = fmt.Errorf("empty input file")
  151. func parseLegacy(data []byte) (*Profile, error) {
  152. parsers := []func([]byte) (*Profile, error){
  153. parseCPU,
  154. parseHeap,
  155. parseGoCount, // goroutine, threadcreate
  156. parseThread,
  157. parseContention,
  158. parseJavaProfile,
  159. }
  160. for _, parser := range parsers {
  161. p, err := parser(data)
  162. if err == nil {
  163. p.addLegacyFrameInfo()
  164. return p, nil
  165. }
  166. if err != errUnrecognized {
  167. return nil, err
  168. }
  169. }
  170. return nil, errUnrecognized
  171. }
  172. // ParseUncompressed parses an uncompressed protobuf into a profile.
  173. func ParseUncompressed(data []byte) (*Profile, error) {
  174. if len(data) == 0 {
  175. return nil, errNoData
  176. }
  177. p := &Profile{}
  178. if err := unmarshal(data, p); err != nil {
  179. return nil, err
  180. }
  181. if err := p.postDecode(); err != nil {
  182. return nil, err
  183. }
  184. return p, nil
  185. }
  186. var libRx = regexp.MustCompile(`([.]so$|[.]so[._][0-9]+)`)
  187. // massageMappings applies heuristic-based changes to the profile
  188. // mappings to account for quirks of some environments.
  189. func (p *Profile) massageMappings() {
  190. // Merge adjacent regions with matching names, checking that the offsets match
  191. if len(p.Mapping) > 1 {
  192. mappings := []*Mapping{p.Mapping[0]}
  193. for _, m := range p.Mapping[1:] {
  194. lm := mappings[len(mappings)-1]
  195. if adjacent(lm, m) {
  196. lm.Limit = m.Limit
  197. if m.File != "" {
  198. lm.File = m.File
  199. }
  200. if m.BuildID != "" {
  201. lm.BuildID = m.BuildID
  202. }
  203. p.updateLocationMapping(m, lm)
  204. continue
  205. }
  206. mappings = append(mappings, m)
  207. }
  208. p.Mapping = mappings
  209. }
  210. // Use heuristics to identify main binary and move it to the top of the list of mappings
  211. for i, m := range p.Mapping {
  212. file := strings.TrimSpace(strings.Replace(m.File, "(deleted)", "", -1))
  213. if len(file) == 0 {
  214. continue
  215. }
  216. if len(libRx.FindStringSubmatch(file)) > 0 {
  217. continue
  218. }
  219. if file[0] == '[' {
  220. continue
  221. }
  222. // Swap what we guess is main to position 0.
  223. p.Mapping[0], p.Mapping[i] = p.Mapping[i], p.Mapping[0]
  224. break
  225. }
  226. // Keep the mapping IDs neatly sorted
  227. for i, m := range p.Mapping {
  228. m.ID = uint64(i + 1)
  229. }
  230. }
  231. // adjacent returns whether two mapping entries represent the same
  232. // mapping that has been split into two. Check that their addresses are adjacent,
  233. // and if the offsets match, if they are available.
  234. func adjacent(m1, m2 *Mapping) bool {
  235. if m1.File != "" && m2.File != "" {
  236. if m1.File != m2.File {
  237. return false
  238. }
  239. }
  240. if m1.BuildID != "" && m2.BuildID != "" {
  241. if m1.BuildID != m2.BuildID {
  242. return false
  243. }
  244. }
  245. if m1.Limit != m2.Start {
  246. return false
  247. }
  248. if m1.Offset != 0 && m2.Offset != 0 {
  249. offset := m1.Offset + (m1.Limit - m1.Start)
  250. if offset != m2.Offset {
  251. return false
  252. }
  253. }
  254. return true
  255. }
  256. func (p *Profile) updateLocationMapping(from, to *Mapping) {
  257. for _, l := range p.Location {
  258. if l.Mapping == from {
  259. l.Mapping = to
  260. }
  261. }
  262. }
  263. // Write writes the profile as a gzip-compressed marshaled protobuf.
  264. func (p *Profile) Write(w io.Writer) error {
  265. p.preEncode()
  266. b := marshal(p)
  267. zw := gzip.NewWriter(w)
  268. defer zw.Close()
  269. _, err := zw.Write(b)
  270. return err
  271. }
  272. // WriteUncompressed writes the profile as a marshaled protobuf.
  273. func (p *Profile) WriteUncompressed(w io.Writer) error {
  274. p.preEncode()
  275. b := marshal(p)
  276. _, err := w.Write(b)
  277. return err
  278. }
  279. // CheckValid tests whether the profile is valid. Checks include, but are
  280. // not limited to:
  281. // - len(Profile.Sample[n].value) == len(Profile.value_unit)
  282. // - Sample.id has a corresponding Profile.Location
  283. func (p *Profile) CheckValid() error {
  284. // Check that sample values are consistent
  285. sampleLen := len(p.SampleType)
  286. if sampleLen == 0 && len(p.Sample) != 0 {
  287. return fmt.Errorf("missing sample type information")
  288. }
  289. for _, s := range p.Sample {
  290. if len(s.Value) != sampleLen {
  291. return fmt.Errorf("mismatch: sample has: %d values vs. %d types", len(s.Value), len(p.SampleType))
  292. }
  293. for _, l := range s.Location {
  294. if l == nil {
  295. return fmt.Errorf("sample has nil location")
  296. }
  297. }
  298. }
  299. // Check that all mappings/locations/functions are in the tables
  300. // Check that there are no duplicate ids
  301. mappings := make(map[uint64]*Mapping, len(p.Mapping))
  302. for _, m := range p.Mapping {
  303. if m.ID == 0 {
  304. return fmt.Errorf("found mapping with reserved ID=0")
  305. }
  306. if mappings[m.ID] != nil {
  307. return fmt.Errorf("multiple mappings with same id: %d", m.ID)
  308. }
  309. mappings[m.ID] = m
  310. }
  311. functions := make(map[uint64]*Function, len(p.Function))
  312. for _, f := range p.Function {
  313. if f.ID == 0 {
  314. return fmt.Errorf("found function with reserved ID=0")
  315. }
  316. if functions[f.ID] != nil {
  317. return fmt.Errorf("multiple functions with same id: %d", f.ID)
  318. }
  319. functions[f.ID] = f
  320. }
  321. locations := make(map[uint64]*Location, len(p.Location))
  322. for _, l := range p.Location {
  323. if l.ID == 0 {
  324. return fmt.Errorf("found location with reserved id=0")
  325. }
  326. if locations[l.ID] != nil {
  327. return fmt.Errorf("multiple locations with same id: %d", l.ID)
  328. }
  329. locations[l.ID] = l
  330. if m := l.Mapping; m != nil {
  331. if m.ID == 0 || mappings[m.ID] != m {
  332. return fmt.Errorf("inconsistent mapping %p: %d", m, m.ID)
  333. }
  334. }
  335. for _, ln := range l.Line {
  336. if f := ln.Function; f != nil {
  337. if f.ID == 0 || functions[f.ID] != f {
  338. return fmt.Errorf("inconsistent function %p: %d", f, f.ID)
  339. }
  340. }
  341. }
  342. }
  343. return nil
  344. }
  345. // Aggregate merges the locations in the profile into equivalence
  346. // classes preserving the request attributes. It also updates the
  347. // samples to point to the merged locations.
  348. func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address bool) error {
  349. for _, m := range p.Mapping {
  350. m.HasInlineFrames = m.HasInlineFrames && inlineFrame
  351. m.HasFunctions = m.HasFunctions && function
  352. m.HasFilenames = m.HasFilenames && filename
  353. m.HasLineNumbers = m.HasLineNumbers && linenumber
  354. }
  355. // Aggregate functions
  356. if !function || !filename {
  357. for _, f := range p.Function {
  358. if !function {
  359. f.Name = ""
  360. f.SystemName = ""
  361. }
  362. if !filename {
  363. f.Filename = ""
  364. }
  365. }
  366. }
  367. // Aggregate locations
  368. if !inlineFrame || !address || !linenumber {
  369. for _, l := range p.Location {
  370. if !inlineFrame && len(l.Line) > 1 {
  371. l.Line = l.Line[len(l.Line)-1:]
  372. }
  373. if !linenumber {
  374. for i := range l.Line {
  375. l.Line[i].Line = 0
  376. }
  377. }
  378. if !address {
  379. l.Address = 0
  380. }
  381. }
  382. }
  383. return p.CheckValid()
  384. }
  385. // String dumps a text representation of a profile. Intended mainly
  386. // for debugging purposes.
  387. func (p *Profile) String() string {
  388. ss := make([]string, 0, len(p.Comments)+len(p.Sample)+len(p.Mapping)+len(p.Location))
  389. for _, c := range p.Comments {
  390. ss = append(ss, "Comment: "+c)
  391. }
  392. if pt := p.PeriodType; pt != nil {
  393. ss = append(ss, fmt.Sprintf("PeriodType: %s %s", pt.Type, pt.Unit))
  394. }
  395. ss = append(ss, fmt.Sprintf("Period: %d", p.Period))
  396. if p.TimeNanos != 0 {
  397. ss = append(ss, fmt.Sprintf("Time: %v", time.Unix(0, p.TimeNanos)))
  398. }
  399. if p.DurationNanos != 0 {
  400. ss = append(ss, fmt.Sprintf("Duration: %.4v", time.Duration(p.DurationNanos)))
  401. }
  402. ss = append(ss, "Samples:")
  403. var sh1 string
  404. for _, s := range p.SampleType {
  405. dflt := ""
  406. if s.Type == p.DefaultSampleType {
  407. dflt = "[dflt]"
  408. }
  409. sh1 = sh1 + fmt.Sprintf("%s/%s%s ", s.Type, s.Unit, dflt)
  410. }
  411. ss = append(ss, strings.TrimSpace(sh1))
  412. for _, s := range p.Sample {
  413. var sv string
  414. for _, v := range s.Value {
  415. sv = fmt.Sprintf("%s %10d", sv, v)
  416. }
  417. sv = sv + ": "
  418. for _, l := range s.Location {
  419. sv = sv + fmt.Sprintf("%d ", l.ID)
  420. }
  421. ss = append(ss, sv)
  422. const labelHeader = " "
  423. if len(s.Label) > 0 {
  424. ls := []string{}
  425. for k, v := range s.Label {
  426. ls = append(ls, fmt.Sprintf("%s:%v", k, v))
  427. }
  428. sort.Strings(ls)
  429. ss = append(ss, labelHeader+strings.Join(ls, " "))
  430. }
  431. if len(s.NumLabel) > 0 {
  432. ls := []string{}
  433. for k, v := range s.NumLabel {
  434. ls = append(ls, fmt.Sprintf("%s:%v", k, v))
  435. }
  436. sort.Strings(ls)
  437. ss = append(ss, labelHeader+strings.Join(ls, " "))
  438. }
  439. }
  440. ss = append(ss, "Locations")
  441. for _, l := range p.Location {
  442. locStr := fmt.Sprintf("%6d: %#x ", l.ID, l.Address)
  443. if m := l.Mapping; m != nil {
  444. locStr = locStr + fmt.Sprintf("M=%d ", m.ID)
  445. }
  446. if len(l.Line) == 0 {
  447. ss = append(ss, locStr)
  448. }
  449. for li := range l.Line {
  450. lnStr := "??"
  451. if fn := l.Line[li].Function; fn != nil {
  452. lnStr = fmt.Sprintf("%s %s:%d s=%d",
  453. fn.Name,
  454. fn.Filename,
  455. l.Line[li].Line,
  456. fn.StartLine)
  457. if fn.Name != fn.SystemName {
  458. lnStr = lnStr + "(" + fn.SystemName + ")"
  459. }
  460. }
  461. ss = append(ss, locStr+lnStr)
  462. // Do not print location details past the first line
  463. locStr = " "
  464. }
  465. }
  466. ss = append(ss, "Mappings")
  467. for _, m := range p.Mapping {
  468. bits := ""
  469. if m.HasFunctions {
  470. bits = bits + "[FN]"
  471. }
  472. if m.HasFilenames {
  473. bits = bits + "[FL]"
  474. }
  475. if m.HasLineNumbers {
  476. bits = bits + "[LN]"
  477. }
  478. if m.HasInlineFrames {
  479. bits = bits + "[IN]"
  480. }
  481. ss = append(ss, fmt.Sprintf("%d: %#x/%#x/%#x %s %s %s",
  482. m.ID,
  483. m.Start, m.Limit, m.Offset,
  484. m.File,
  485. m.BuildID,
  486. bits))
  487. }
  488. return strings.Join(ss, "\n") + "\n"
  489. }
  490. // Scale multiplies all sample values in a profile by a constant.
  491. func (p *Profile) Scale(ratio float64) {
  492. if ratio == 1 {
  493. return
  494. }
  495. ratios := make([]float64, len(p.SampleType))
  496. for i := range p.SampleType {
  497. ratios[i] = ratio
  498. }
  499. p.ScaleN(ratios)
  500. }
  501. // ScaleN multiplies each sample values in a sample by a different amount.
  502. func (p *Profile) ScaleN(ratios []float64) error {
  503. if len(p.SampleType) != len(ratios) {
  504. return fmt.Errorf("mismatched scale ratios, got %d, want %d", len(ratios), len(p.SampleType))
  505. }
  506. allOnes := true
  507. for _, r := range ratios {
  508. if r != 1 {
  509. allOnes = false
  510. break
  511. }
  512. }
  513. if allOnes {
  514. return nil
  515. }
  516. for _, s := range p.Sample {
  517. for i, v := range s.Value {
  518. if ratios[i] != 1 {
  519. s.Value[i] = int64(float64(v) * ratios[i])
  520. }
  521. }
  522. }
  523. return nil
  524. }
  525. // HasFunctions determines if all locations in this profile have
  526. // symbolized function information.
  527. func (p *Profile) HasFunctions() bool {
  528. for _, l := range p.Location {
  529. if l.Mapping != nil && !l.Mapping.HasFunctions {
  530. return false
  531. }
  532. }
  533. return true
  534. }
  535. // HasFileLines determines if all locations in this profile have
  536. // symbolized file and line number information.
  537. func (p *Profile) HasFileLines() bool {
  538. for _, l := range p.Location {
  539. if l.Mapping != nil && (!l.Mapping.HasFilenames || !l.Mapping.HasLineNumbers) {
  540. return false
  541. }
  542. }
  543. return true
  544. }
  545. // Unsymbolizable returns true if a mapping points to a binary for which
  546. // locations can't be symbolized in principle, at least now. Examples are
  547. // "[vdso]", [vsyscall]" and some others, see the code.
  548. func (m *Mapping) Unsymbolizable() bool {
  549. name := filepath.Base(m.File)
  550. return strings.HasPrefix(name, "[") || strings.HasPrefix(name, "linux-vdso") || strings.HasPrefix(m.File, "/dev/dri/")
  551. }
  552. // Copy makes a fully independent copy of a profile.
  553. func (p *Profile) Copy() *Profile {
  554. p.preEncode()
  555. b := marshal(p)
  556. pp := &Profile{}
  557. if err := unmarshal(b, pp); err != nil {
  558. panic(err)
  559. }
  560. if err := pp.postDecode(); err != nil {
  561. panic(err)
  562. }
  563. return pp
  564. }