Нет описания

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