profile.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. "math"
  24. "path/filepath"
  25. "regexp"
  26. "sort"
  27. "strings"
  28. "sync"
  29. "time"
  30. )
  31. // Profile is an in-memory representation of profile.proto.
  32. type Profile struct {
  33. SampleType []*ValueType
  34. DefaultSampleType string
  35. Sample []*Sample
  36. Mapping []*Mapping
  37. Location []*Location
  38. Function []*Function
  39. Comments []string
  40. DropFrames string
  41. KeepFrames string
  42. TimeNanos int64
  43. DurationNanos int64
  44. PeriodType *ValueType
  45. Period int64
  46. // The following fields are modified during encoding and copying,
  47. // so are protected by a Mutex.
  48. encodeMu sync.Mutex
  49. commentX []int64
  50. dropFramesX int64
  51. keepFramesX int64
  52. stringTable []string
  53. defaultSampleTypeX int64
  54. }
  55. // ValueType corresponds to Profile.ValueType
  56. type ValueType struct {
  57. Type string // cpu, wall, inuse_space, etc
  58. Unit string // seconds, nanoseconds, bytes, etc
  59. typeX int64
  60. unitX int64
  61. }
  62. // Sample corresponds to Profile.Sample
  63. type Sample struct {
  64. Location []*Location
  65. Value []int64
  66. Label map[string][]string
  67. NumLabel map[string][]int64
  68. NumUnit map[string][]string
  69. locationIDX []uint64
  70. labelX []label
  71. }
  72. // label corresponds to Profile.Label
  73. type label struct {
  74. keyX int64
  75. // Exactly one of the two following values must be set
  76. strX int64
  77. numX int64 // Integer value for this label
  78. // can be set if numX has value
  79. unitX int64
  80. }
  81. // Mapping corresponds to Profile.Mapping
  82. type Mapping struct {
  83. ID uint64
  84. Start uint64
  85. Limit uint64
  86. Offset uint64
  87. File string
  88. BuildID string
  89. HasFunctions bool
  90. HasFilenames bool
  91. HasLineNumbers bool
  92. HasInlineFrames bool
  93. fileX int64
  94. buildIDX int64
  95. }
  96. // Location corresponds to Profile.Location
  97. type Location struct {
  98. ID uint64
  99. Mapping *Mapping
  100. Address uint64
  101. Line []Line
  102. IsFolded bool
  103. mappingIDX uint64
  104. }
  105. // Line corresponds to Profile.Line
  106. type Line struct {
  107. Function *Function
  108. Line int64
  109. functionIDX uint64
  110. }
  111. // Function corresponds to Profile.Function
  112. type Function struct {
  113. ID uint64
  114. Name string
  115. SystemName string
  116. Filename string
  117. StartLine int64
  118. nameX int64
  119. systemNameX int64
  120. filenameX int64
  121. }
  122. // Parse parses a profile and checks for its validity. The input
  123. // may be a gzip-compressed encoded protobuf or one of many legacy
  124. // profile formats which may be unsupported in the future.
  125. func Parse(r io.Reader) (*Profile, error) {
  126. data, err := ioutil.ReadAll(r)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return ParseData(data)
  131. }
  132. // ParseData parses a profile from a buffer and checks for its
  133. // validity.
  134. func ParseData(data []byte) (*Profile, error) {
  135. var p *Profile
  136. var err error
  137. if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
  138. gz, err := gzip.NewReader(bytes.NewBuffer(data))
  139. if err == nil {
  140. data, err = ioutil.ReadAll(gz)
  141. }
  142. if err != nil {
  143. return nil, fmt.Errorf("decompressing profile: %v", err)
  144. }
  145. }
  146. if p, err = ParseUncompressed(data); err != nil && err != errNoData && err != errConcatProfile {
  147. p, err = parseLegacy(data)
  148. }
  149. if err != nil {
  150. return nil, fmt.Errorf("parsing profile: %v", err)
  151. }
  152. if err := p.CheckValid(); err != nil {
  153. return nil, fmt.Errorf("malformed profile: %v", err)
  154. }
  155. return p, nil
  156. }
  157. var errUnrecognized = fmt.Errorf("unrecognized profile format")
  158. var errMalformed = fmt.Errorf("malformed profile format")
  159. var errNoData = fmt.Errorf("empty input file")
  160. var errConcatProfile = fmt.Errorf("concatenated profiles detected")
  161. func parseLegacy(data []byte) (*Profile, error) {
  162. parsers := []func([]byte) (*Profile, error){
  163. parseCPU,
  164. parseHeap,
  165. parseGoCount, // goroutine, threadcreate
  166. parseThread,
  167. parseContention,
  168. parseJavaProfile,
  169. }
  170. for _, parser := range parsers {
  171. p, err := parser(data)
  172. if err == nil {
  173. p.addLegacyFrameInfo()
  174. return p, nil
  175. }
  176. if err != errUnrecognized {
  177. return nil, err
  178. }
  179. }
  180. return nil, errUnrecognized
  181. }
  182. // ParseUncompressed parses an uncompressed protobuf into a profile.
  183. func ParseUncompressed(data []byte) (*Profile, error) {
  184. if len(data) == 0 {
  185. return nil, errNoData
  186. }
  187. p := &Profile{}
  188. if err := unmarshal(data, p); err != nil {
  189. return nil, err
  190. }
  191. if err := p.postDecode(); err != nil {
  192. return nil, err
  193. }
  194. return p, nil
  195. }
  196. var libRx = regexp.MustCompile(`([.]so$|[.]so[._][0-9]+)`)
  197. // massageMappings applies heuristic-based changes to the profile
  198. // mappings to account for quirks of some environments.
  199. func (p *Profile) massageMappings() {
  200. // Merge adjacent regions with matching names, checking that the offsets match
  201. if len(p.Mapping) > 1 {
  202. mappings := []*Mapping{p.Mapping[0]}
  203. for _, m := range p.Mapping[1:] {
  204. lm := mappings[len(mappings)-1]
  205. if adjacent(lm, m) {
  206. lm.Limit = m.Limit
  207. if m.File != "" {
  208. lm.File = m.File
  209. }
  210. if m.BuildID != "" {
  211. lm.BuildID = m.BuildID
  212. }
  213. p.updateLocationMapping(m, lm)
  214. continue
  215. }
  216. mappings = append(mappings, m)
  217. }
  218. p.Mapping = mappings
  219. }
  220. // Use heuristics to identify main binary and move it to the top of the list of mappings
  221. for i, m := range p.Mapping {
  222. file := strings.TrimSpace(strings.Replace(m.File, "(deleted)", "", -1))
  223. if len(file) == 0 {
  224. continue
  225. }
  226. if len(libRx.FindStringSubmatch(file)) > 0 {
  227. continue
  228. }
  229. if file[0] == '[' {
  230. continue
  231. }
  232. // Swap what we guess is main to position 0.
  233. p.Mapping[0], p.Mapping[i] = p.Mapping[i], p.Mapping[0]
  234. break
  235. }
  236. // Keep the mapping IDs neatly sorted
  237. for i, m := range p.Mapping {
  238. m.ID = uint64(i + 1)
  239. }
  240. }
  241. // adjacent returns whether two mapping entries represent the same
  242. // mapping that has been split into two. Check that their addresses are adjacent,
  243. // and if the offsets match, if they are available.
  244. func adjacent(m1, m2 *Mapping) bool {
  245. if m1.File != "" && m2.File != "" {
  246. if m1.File != m2.File {
  247. return false
  248. }
  249. }
  250. if m1.BuildID != "" && m2.BuildID != "" {
  251. if m1.BuildID != m2.BuildID {
  252. return false
  253. }
  254. }
  255. if m1.Limit != m2.Start {
  256. return false
  257. }
  258. if m1.Offset != 0 && m2.Offset != 0 {
  259. offset := m1.Offset + (m1.Limit - m1.Start)
  260. if offset != m2.Offset {
  261. return false
  262. }
  263. }
  264. return true
  265. }
  266. func (p *Profile) updateLocationMapping(from, to *Mapping) {
  267. for _, l := range p.Location {
  268. if l.Mapping == from {
  269. l.Mapping = to
  270. }
  271. }
  272. }
  273. func serialize(p *Profile) []byte {
  274. p.encodeMu.Lock()
  275. p.preEncode()
  276. b := marshal(p)
  277. p.encodeMu.Unlock()
  278. return b
  279. }
  280. // Write writes the profile as a gzip-compressed marshaled protobuf.
  281. func (p *Profile) Write(w io.Writer) error {
  282. zw := gzip.NewWriter(w)
  283. defer zw.Close()
  284. _, err := zw.Write(serialize(p))
  285. return err
  286. }
  287. // WriteUncompressed writes the profile as a marshaled protobuf.
  288. func (p *Profile) WriteUncompressed(w io.Writer) error {
  289. _, err := w.Write(serialize(p))
  290. return err
  291. }
  292. // CheckValid tests whether the profile is valid. Checks include, but are
  293. // not limited to:
  294. // - len(Profile.Sample[n].value) == len(Profile.value_unit)
  295. // - Sample.id has a corresponding Profile.Location
  296. func (p *Profile) CheckValid() error {
  297. // Check that sample values are consistent
  298. sampleLen := len(p.SampleType)
  299. if sampleLen == 0 && len(p.Sample) != 0 {
  300. return fmt.Errorf("missing sample type information")
  301. }
  302. for _, s := range p.Sample {
  303. if s == nil {
  304. return fmt.Errorf("profile has nil sample")
  305. }
  306. if len(s.Value) != sampleLen {
  307. return fmt.Errorf("mismatch: sample has %d values vs. %d types", len(s.Value), len(p.SampleType))
  308. }
  309. for _, l := range s.Location {
  310. if l == nil {
  311. return fmt.Errorf("sample has nil location")
  312. }
  313. }
  314. }
  315. // Check that all mappings/locations/functions are in the tables
  316. // Check that there are no duplicate ids
  317. mappings := make(map[uint64]*Mapping, len(p.Mapping))
  318. for _, m := range p.Mapping {
  319. if m == nil {
  320. return fmt.Errorf("profile has nil mapping")
  321. }
  322. if m.ID == 0 {
  323. return fmt.Errorf("found mapping with reserved ID=0")
  324. }
  325. if mappings[m.ID] != nil {
  326. return fmt.Errorf("multiple mappings with same id: %d", m.ID)
  327. }
  328. mappings[m.ID] = m
  329. }
  330. functions := make(map[uint64]*Function, len(p.Function))
  331. for _, f := range p.Function {
  332. if f == nil {
  333. return fmt.Errorf("profile has nil function")
  334. }
  335. if f.ID == 0 {
  336. return fmt.Errorf("found function with reserved ID=0")
  337. }
  338. if functions[f.ID] != nil {
  339. return fmt.Errorf("multiple functions with same id: %d", f.ID)
  340. }
  341. functions[f.ID] = f
  342. }
  343. locations := make(map[uint64]*Location, len(p.Location))
  344. for _, l := range p.Location {
  345. if l == nil {
  346. return fmt.Errorf("profile has nil location")
  347. }
  348. if l.ID == 0 {
  349. return fmt.Errorf("found location with reserved id=0")
  350. }
  351. if locations[l.ID] != nil {
  352. return fmt.Errorf("multiple locations with same id: %d", l.ID)
  353. }
  354. locations[l.ID] = l
  355. if m := l.Mapping; m != nil {
  356. if m.ID == 0 || mappings[m.ID] != m {
  357. return fmt.Errorf("inconsistent mapping %p: %d", m, m.ID)
  358. }
  359. }
  360. for _, ln := range l.Line {
  361. f := ln.Function
  362. if f == nil {
  363. return fmt.Errorf("location id: %d has a line with nil function", l.ID)
  364. }
  365. if f.ID == 0 || functions[f.ID] != f {
  366. return fmt.Errorf("inconsistent function %p: %d", f, f.ID)
  367. }
  368. }
  369. }
  370. return nil
  371. }
  372. // Aggregate merges the locations in the profile into equivalence
  373. // classes preserving the request attributes. It also updates the
  374. // samples to point to the merged locations.
  375. func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address bool) error {
  376. for _, m := range p.Mapping {
  377. m.HasInlineFrames = m.HasInlineFrames && inlineFrame
  378. m.HasFunctions = m.HasFunctions && function
  379. m.HasFilenames = m.HasFilenames && filename
  380. m.HasLineNumbers = m.HasLineNumbers && linenumber
  381. }
  382. // Aggregate functions
  383. if !function || !filename {
  384. for _, f := range p.Function {
  385. if !function {
  386. f.Name = ""
  387. f.SystemName = ""
  388. }
  389. if !filename {
  390. f.Filename = ""
  391. }
  392. }
  393. }
  394. // Aggregate locations
  395. if !inlineFrame || !address || !linenumber {
  396. for _, l := range p.Location {
  397. if !inlineFrame && len(l.Line) > 1 {
  398. l.Line = l.Line[len(l.Line)-1:]
  399. }
  400. if !linenumber {
  401. for i := range l.Line {
  402. l.Line[i].Line = 0
  403. }
  404. }
  405. if !address {
  406. l.Address = 0
  407. }
  408. }
  409. }
  410. return p.CheckValid()
  411. }
  412. // NumLabelUnits returns a map of numeric label keys to the units
  413. // associated with those keys and a map of those keys to any units
  414. // that were encountered but not used.
  415. // Unit for a given key is the first encountered unit for that key. If multiple
  416. // units are encountered for values paired with a particular key, then the first
  417. // unit encountered is used and all other units are returned in sorted order
  418. // in map of ignored units.
  419. // If no units are encountered for a particular key, the unit is then inferred
  420. // based on the key.
  421. func (p *Profile) NumLabelUnits() (map[string]string, map[string][]string) {
  422. numLabelUnits := map[string]string{}
  423. ignoredUnits := map[string]map[string]bool{}
  424. encounteredKeys := map[string]bool{}
  425. // Determine units based on numeric tags for each sample.
  426. for _, s := range p.Sample {
  427. for k := range s.NumLabel {
  428. encounteredKeys[k] = true
  429. for _, unit := range s.NumUnit[k] {
  430. if unit == "" {
  431. continue
  432. }
  433. if wantUnit, ok := numLabelUnits[k]; !ok {
  434. numLabelUnits[k] = unit
  435. } else if wantUnit != unit {
  436. if v, ok := ignoredUnits[k]; ok {
  437. v[unit] = true
  438. } else {
  439. ignoredUnits[k] = map[string]bool{unit: true}
  440. }
  441. }
  442. }
  443. }
  444. }
  445. // Infer units for keys without any units associated with
  446. // numeric tag values.
  447. for key := range encounteredKeys {
  448. unit := numLabelUnits[key]
  449. if unit == "" {
  450. switch key {
  451. case "alignment", "request":
  452. numLabelUnits[key] = "bytes"
  453. default:
  454. numLabelUnits[key] = key
  455. }
  456. }
  457. }
  458. // Copy ignored units into more readable format
  459. unitsIgnored := make(map[string][]string, len(ignoredUnits))
  460. for key, values := range ignoredUnits {
  461. units := make([]string, len(values))
  462. i := 0
  463. for unit := range values {
  464. units[i] = unit
  465. i++
  466. }
  467. sort.Strings(units)
  468. unitsIgnored[key] = units
  469. }
  470. return numLabelUnits, unitsIgnored
  471. }
  472. // String dumps a text representation of a profile. Intended mainly
  473. // for debugging purposes.
  474. func (p *Profile) String() string {
  475. ss := make([]string, 0, len(p.Comments)+len(p.Sample)+len(p.Mapping)+len(p.Location))
  476. for _, c := range p.Comments {
  477. ss = append(ss, "Comment: "+c)
  478. }
  479. if pt := p.PeriodType; pt != nil {
  480. ss = append(ss, fmt.Sprintf("PeriodType: %s %s", pt.Type, pt.Unit))
  481. }
  482. ss = append(ss, fmt.Sprintf("Period: %d", p.Period))
  483. if p.TimeNanos != 0 {
  484. ss = append(ss, fmt.Sprintf("Time: %v", time.Unix(0, p.TimeNanos)))
  485. }
  486. if p.DurationNanos != 0 {
  487. ss = append(ss, fmt.Sprintf("Duration: %.4v", time.Duration(p.DurationNanos)))
  488. }
  489. ss = append(ss, "Samples:")
  490. var sh1 string
  491. for _, s := range p.SampleType {
  492. dflt := ""
  493. if s.Type == p.DefaultSampleType {
  494. dflt = "[dflt]"
  495. }
  496. sh1 = sh1 + fmt.Sprintf("%s/%s%s ", s.Type, s.Unit, dflt)
  497. }
  498. ss = append(ss, strings.TrimSpace(sh1))
  499. for _, s := range p.Sample {
  500. ss = append(ss, s.string())
  501. }
  502. ss = append(ss, "Locations")
  503. for _, l := range p.Location {
  504. ss = append(ss, l.string())
  505. }
  506. ss = append(ss, "Mappings")
  507. for _, m := range p.Mapping {
  508. ss = append(ss, m.string())
  509. }
  510. return strings.Join(ss, "\n") + "\n"
  511. }
  512. // string dumps a text representation of a mapping. Intended mainly
  513. // for debugging purposes.
  514. func (m *Mapping) string() string {
  515. bits := ""
  516. if m.HasFunctions {
  517. bits = bits + "[FN]"
  518. }
  519. if m.HasFilenames {
  520. bits = bits + "[FL]"
  521. }
  522. if m.HasLineNumbers {
  523. bits = bits + "[LN]"
  524. }
  525. if m.HasInlineFrames {
  526. bits = bits + "[IN]"
  527. }
  528. return fmt.Sprintf("%d: %#x/%#x/%#x %s %s %s",
  529. m.ID,
  530. m.Start, m.Limit, m.Offset,
  531. m.File,
  532. m.BuildID,
  533. bits)
  534. }
  535. // string dumps a text representation of a location. Intended mainly
  536. // for debugging purposes.
  537. func (l *Location) string() string {
  538. ss := []string{}
  539. locStr := fmt.Sprintf("%6d: %#x ", l.ID, l.Address)
  540. if m := l.Mapping; m != nil {
  541. locStr = locStr + fmt.Sprintf("M=%d ", m.ID)
  542. }
  543. if l.IsFolded {
  544. locStr = locStr + "[F] "
  545. }
  546. if len(l.Line) == 0 {
  547. ss = append(ss, locStr)
  548. }
  549. for li := range l.Line {
  550. lnStr := "??"
  551. if fn := l.Line[li].Function; fn != nil {
  552. lnStr = fmt.Sprintf("%s %s:%d s=%d",
  553. fn.Name,
  554. fn.Filename,
  555. l.Line[li].Line,
  556. fn.StartLine)
  557. if fn.Name != fn.SystemName {
  558. lnStr = lnStr + "(" + fn.SystemName + ")"
  559. }
  560. }
  561. ss = append(ss, locStr+lnStr)
  562. // Do not print location details past the first line
  563. locStr = " "
  564. }
  565. return strings.Join(ss, "\n")
  566. }
  567. // string dumps a text representation of a sample. Intended mainly
  568. // for debugging purposes.
  569. func (s *Sample) string() string {
  570. ss := []string{}
  571. var sv string
  572. for _, v := range s.Value {
  573. sv = fmt.Sprintf("%s %10d", sv, v)
  574. }
  575. sv = sv + ": "
  576. for _, l := range s.Location {
  577. sv = sv + fmt.Sprintf("%d ", l.ID)
  578. }
  579. ss = append(ss, sv)
  580. const labelHeader = " "
  581. if len(s.Label) > 0 {
  582. ss = append(ss, labelHeader+labelsToString(s.Label))
  583. }
  584. if len(s.NumLabel) > 0 {
  585. ss = append(ss, labelHeader+numLabelsToString(s.NumLabel, s.NumUnit))
  586. }
  587. return strings.Join(ss, "\n")
  588. }
  589. // labelsToString returns a string representation of a
  590. // map representing labels.
  591. func labelsToString(labels map[string][]string) string {
  592. ls := []string{}
  593. for k, v := range labels {
  594. ls = append(ls, fmt.Sprintf("%s:%v", k, v))
  595. }
  596. sort.Strings(ls)
  597. return strings.Join(ls, " ")
  598. }
  599. // numLabelsToString returns a string representation of a map
  600. // representing numeric labels.
  601. func numLabelsToString(numLabels map[string][]int64, numUnits map[string][]string) string {
  602. ls := []string{}
  603. for k, v := range numLabels {
  604. units := numUnits[k]
  605. var labelString string
  606. if len(units) == len(v) {
  607. values := make([]string, len(v))
  608. for i, vv := range v {
  609. values[i] = fmt.Sprintf("%d %s", vv, units[i])
  610. }
  611. labelString = fmt.Sprintf("%s:%v", k, values)
  612. } else {
  613. labelString = fmt.Sprintf("%s:%v", k, v)
  614. }
  615. ls = append(ls, labelString)
  616. }
  617. sort.Strings(ls)
  618. return strings.Join(ls, " ")
  619. }
  620. // SetLabel sets the specified key to the specified value for all samples in the
  621. // profile.
  622. func (p *Profile) SetLabel(key string, value []string) {
  623. for _, sample := range p.Sample {
  624. if sample.Label == nil {
  625. sample.Label = map[string][]string{key: value}
  626. } else {
  627. sample.Label[key] = value
  628. }
  629. }
  630. }
  631. // RemoveLabel removes all labels associated with the specified key for all
  632. // samples in the profile.
  633. func (p *Profile) RemoveLabel(key string) {
  634. for _, sample := range p.Sample {
  635. delete(sample.Label, key)
  636. }
  637. }
  638. // HasLabel returns true if a sample has a label with indicated key and value.
  639. func (s *Sample) HasLabel(key, value string) bool {
  640. for _, v := range s.Label[key] {
  641. if v == value {
  642. return true
  643. }
  644. }
  645. return false
  646. }
  647. // DiffBaseSample returns true if a sample belongs to the diff base and false
  648. // otherwise.
  649. func (s *Sample) DiffBaseSample() bool {
  650. return s.HasLabel("pprof::base", "true")
  651. }
  652. // Scale multiplies all sample values in a profile by a constant and keeps
  653. // only samples that have at least one non-zero value.
  654. func (p *Profile) Scale(ratio float64) {
  655. if ratio == 1 {
  656. return
  657. }
  658. ratios := make([]float64, len(p.SampleType))
  659. for i := range p.SampleType {
  660. ratios[i] = ratio
  661. }
  662. p.ScaleN(ratios)
  663. }
  664. // ScaleN multiplies each sample values in a sample by a different amount
  665. // and keeps only samples that have at least one non-zero value.
  666. func (p *Profile) ScaleN(ratios []float64) error {
  667. if len(p.SampleType) != len(ratios) {
  668. return fmt.Errorf("mismatched scale ratios, got %d, want %d", len(ratios), len(p.SampleType))
  669. }
  670. allOnes := true
  671. for _, r := range ratios {
  672. if r != 1 {
  673. allOnes = false
  674. break
  675. }
  676. }
  677. if allOnes {
  678. return nil
  679. }
  680. fillIdx := 0
  681. for _, s := range p.Sample {
  682. keepSample := false
  683. for i, v := range s.Value {
  684. if ratios[i] != 1 {
  685. val := int64(math.Round(float64(v) * ratios[i]))
  686. s.Value[i] = val
  687. keepSample = keepSample || val != 0
  688. }
  689. }
  690. if keepSample {
  691. p.Sample[fillIdx] = s
  692. fillIdx++
  693. }
  694. }
  695. p.Sample = p.Sample[:fillIdx]
  696. return nil
  697. }
  698. // HasFunctions determines if all locations in this profile have
  699. // symbolized function information.
  700. func (p *Profile) HasFunctions() bool {
  701. for _, l := range p.Location {
  702. if l.Mapping != nil && !l.Mapping.HasFunctions {
  703. return false
  704. }
  705. }
  706. return true
  707. }
  708. // HasFileLines determines if all locations in this profile have
  709. // symbolized file and line number information.
  710. func (p *Profile) HasFileLines() bool {
  711. for _, l := range p.Location {
  712. if l.Mapping != nil && (!l.Mapping.HasFilenames || !l.Mapping.HasLineNumbers) {
  713. return false
  714. }
  715. }
  716. return true
  717. }
  718. // Unsymbolizable returns true if a mapping points to a binary for which
  719. // locations can't be symbolized in principle, at least now. Examples are
  720. // "[vdso]", [vsyscall]" and some others, see the code.
  721. func (m *Mapping) Unsymbolizable() bool {
  722. name := filepath.Base(m.File)
  723. return strings.HasPrefix(name, "[") || strings.HasPrefix(name, "linux-vdso") || strings.HasPrefix(m.File, "/dev/dri/")
  724. }
  725. // Copy makes a fully independent copy of a profile.
  726. func (p *Profile) Copy() *Profile {
  727. pp := &Profile{}
  728. if err := unmarshal(serialize(p), pp); err != nil {
  729. panic(err)
  730. }
  731. if err := pp.postDecode(); err != nil {
  732. panic(err)
  733. }
  734. return pp
  735. }