Няма описание

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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
  15. import (
  16. "fmt"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. )
  21. // Compact performs garbage collection on a profile to remove any
  22. // unreferenced fields. This is useful to reduce the size of a profile
  23. // after samples or locations have been removed.
  24. func (p *Profile) Compact() *Profile {
  25. p, _ = Merge([]*Profile{p})
  26. return p
  27. }
  28. // Merge merges all the profiles in profs into a single Profile.
  29. // Returns a new profile independent of the input profiles. The merged
  30. // profile is compacted to eliminate unused samples, locations,
  31. // functions and mappings. Profiles must have identical profile sample
  32. // and period types or the merge will fail. profile.Period of the
  33. // resulting profile will be the maximum of all profiles, and
  34. // profile.TimeNanos will be the earliest nonzero one.
  35. func Merge(srcs []*Profile) (*Profile, error) {
  36. if len(srcs) == 0 {
  37. return nil, fmt.Errorf("no profiles to merge")
  38. }
  39. p, err := combineHeaders(srcs)
  40. if err != nil {
  41. return nil, err
  42. }
  43. pm := &profileMerger{
  44. p: p,
  45. samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)),
  46. locations: make(map[locationKey]*Location, len(srcs[0].Location)),
  47. functions: make(map[functionKey]*Function, len(srcs[0].Function)),
  48. mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)),
  49. }
  50. for _, src := range srcs {
  51. // Clear the profile-specific hash tables
  52. pm.locationsByID = make(map[uint64]*Location, len(src.Location))
  53. pm.functionsByID = make(map[uint64]*Function, len(src.Function))
  54. pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping))
  55. if len(pm.mappings) == 0 && len(src.Mapping) > 0 {
  56. // The Mapping list has the property that the first mapping
  57. // represents the main binary. Take the first Mapping we see,
  58. // otherwise the operations below will add mappings in an
  59. // arbitrary order.
  60. pm.mapMapping(srcs[0].Mapping[0])
  61. }
  62. for _, s := range src.Sample {
  63. if !isZeroSample(s) {
  64. pm.mapSample(s)
  65. }
  66. }
  67. }
  68. for _, s := range p.Sample {
  69. if isZeroSample(s) {
  70. // If there are any zero samples, re-merge the profile to GC
  71. // them.
  72. return Merge([]*Profile{p})
  73. }
  74. }
  75. return p, nil
  76. }
  77. // Normalize normalizes the source profile by multiplying each value in profile by the
  78. // ratio of the sum of the base profile's values of that sample type to the sum of the
  79. // source profile's value of that sample type.
  80. func (p *Profile) Normalize(pb *Profile) error {
  81. if err := p.compatible(pb); err != nil {
  82. return err
  83. }
  84. baseVals := make([]int64, len(p.SampleType))
  85. for _, s := range pb.Sample {
  86. for i, v := range s.Value {
  87. baseVals[i] += v
  88. }
  89. }
  90. srcVals := make([]int64, len(p.SampleType))
  91. for _, s := range p.Sample {
  92. for i, v := range s.Value {
  93. srcVals[i] += v
  94. }
  95. }
  96. normScale := make([]float64, len(baseVals))
  97. for i := range baseVals {
  98. if srcVals[i] == 0 {
  99. normScale[i] = 0.0
  100. } else {
  101. normScale[i] = float64(baseVals[i]) / float64(srcVals[i])
  102. }
  103. }
  104. p.ScaleN(normScale)
  105. return nil
  106. }
  107. func isZeroSample(s *Sample) bool {
  108. for _, v := range s.Value {
  109. if v != 0 {
  110. return false
  111. }
  112. }
  113. return true
  114. }
  115. type profileMerger struct {
  116. p *Profile
  117. // Memoization tables within a profile.
  118. locationsByID map[uint64]*Location
  119. functionsByID map[uint64]*Function
  120. mappingsByID map[uint64]mapInfo
  121. // Memoization tables for profile entities.
  122. samples map[sampleKey]*Sample
  123. locations map[locationKey]*Location
  124. functions map[functionKey]*Function
  125. mappings map[mappingKey]*Mapping
  126. }
  127. type mapInfo struct {
  128. m *Mapping
  129. offset int64
  130. }
  131. func (pm *profileMerger) mapSample(src *Sample) *Sample {
  132. s := &Sample{
  133. Location: make([]*Location, len(src.Location)),
  134. Value: make([]int64, len(src.Value)),
  135. Label: make(map[string][]string, len(src.Label)),
  136. NumLabel: make(map[string][]int64, len(src.NumLabel)),
  137. NumUnit: make(map[string][]string, len(src.NumLabel)),
  138. }
  139. for i, l := range src.Location {
  140. s.Location[i] = pm.mapLocation(l)
  141. }
  142. for k, v := range src.Label {
  143. vv := make([]string, len(v))
  144. copy(vv, v)
  145. s.Label[k] = vv
  146. }
  147. for k, v := range src.NumLabel {
  148. u := src.NumUnit[k]
  149. vv := make([]int64, len(v))
  150. uu := make([]string, len(u))
  151. copy(vv, v)
  152. copy(uu, u)
  153. s.NumLabel[k] = vv
  154. s.NumUnit[k] = uu
  155. }
  156. // Check memoization table. Must be done on the remapped location to
  157. // account for the remapped mapping. Add current values to the
  158. // existing sample.
  159. k := s.key()
  160. if ss, ok := pm.samples[k]; ok {
  161. for i, v := range src.Value {
  162. ss.Value[i] += v
  163. }
  164. return ss
  165. }
  166. copy(s.Value, src.Value)
  167. pm.samples[k] = s
  168. pm.p.Sample = append(pm.p.Sample, s)
  169. return s
  170. }
  171. // key generates sampleKey to be used as a key for maps.
  172. func (sample *Sample) key() sampleKey {
  173. ids := make([]string, len(sample.Location))
  174. for i, l := range sample.Location {
  175. ids[i] = strconv.FormatUint(l.ID, 16)
  176. }
  177. labels := make([]string, 0, len(sample.Label))
  178. for k, v := range sample.Label {
  179. labels = append(labels, fmt.Sprintf("%q%q", k, v))
  180. }
  181. sort.Strings(labels)
  182. numlabels := make([]string, 0, len(sample.NumLabel))
  183. for k, v := range sample.NumLabel {
  184. numlabels = append(numlabels, fmt.Sprintf("%q%x%x", k, v, sample.NumUnit[k]))
  185. }
  186. sort.Strings(numlabels)
  187. return sampleKey{
  188. strings.Join(ids, "|"),
  189. strings.Join(labels, ""),
  190. strings.Join(numlabels, ""),
  191. }
  192. }
  193. type sampleKey struct {
  194. locations string
  195. labels string
  196. numlabels string
  197. }
  198. func (pm *profileMerger) mapLocation(src *Location) *Location {
  199. if src == nil {
  200. return nil
  201. }
  202. if l, ok := pm.locationsByID[src.ID]; ok {
  203. pm.locationsByID[src.ID] = l
  204. return l
  205. }
  206. mi := pm.mapMapping(src.Mapping)
  207. l := &Location{
  208. ID: uint64(len(pm.p.Location) + 1),
  209. Mapping: mi.m,
  210. Address: uint64(int64(src.Address) + mi.offset),
  211. Line: make([]Line, len(src.Line)),
  212. }
  213. for i, ln := range src.Line {
  214. l.Line[i] = pm.mapLine(ln)
  215. }
  216. // Check memoization table. Must be done on the remapped location to
  217. // account for the remapped mapping ID.
  218. k := l.key()
  219. if ll, ok := pm.locations[k]; ok {
  220. pm.locationsByID[src.ID] = ll
  221. return ll
  222. }
  223. pm.locationsByID[src.ID] = l
  224. pm.locations[k] = l
  225. pm.p.Location = append(pm.p.Location, l)
  226. return l
  227. }
  228. // key generates locationKey to be used as a key for maps.
  229. func (l *Location) key() locationKey {
  230. key := locationKey{
  231. addr: l.Address,
  232. }
  233. if l.Mapping != nil {
  234. // Normalizes address to handle address space randomization.
  235. key.addr -= l.Mapping.Start
  236. key.mappingID = l.Mapping.ID
  237. }
  238. lines := make([]string, len(l.Line)*2)
  239. for i, line := range l.Line {
  240. if line.Function != nil {
  241. lines[i*2] = strconv.FormatUint(line.Function.ID, 16)
  242. }
  243. lines[i*2+1] = strconv.FormatInt(line.Line, 16)
  244. }
  245. key.lines = strings.Join(lines, "|")
  246. return key
  247. }
  248. type locationKey struct {
  249. addr, mappingID uint64
  250. lines string
  251. }
  252. func (pm *profileMerger) mapMapping(src *Mapping) mapInfo {
  253. if src == nil {
  254. return mapInfo{}
  255. }
  256. if mi, ok := pm.mappingsByID[src.ID]; ok {
  257. return mi
  258. }
  259. // Check memoization tables.
  260. bk, pk := src.key()
  261. if src.BuildID != "" {
  262. if m, ok := pm.mappings[bk]; ok {
  263. mi := mapInfo{m, int64(m.Start) - int64(src.Start)}
  264. pm.mappingsByID[src.ID] = mi
  265. return mi
  266. }
  267. }
  268. if src.File != "" {
  269. if m, ok := pm.mappings[pk]; ok {
  270. mi := mapInfo{m, int64(m.Start) - int64(src.Start)}
  271. pm.mappingsByID[src.ID] = mi
  272. return mi
  273. }
  274. }
  275. m := &Mapping{
  276. ID: uint64(len(pm.p.Mapping) + 1),
  277. Start: src.Start,
  278. Limit: src.Limit,
  279. Offset: src.Offset,
  280. File: src.File,
  281. BuildID: src.BuildID,
  282. HasFunctions: src.HasFunctions,
  283. HasFilenames: src.HasFilenames,
  284. HasLineNumbers: src.HasLineNumbers,
  285. HasInlineFrames: src.HasInlineFrames,
  286. }
  287. pm.p.Mapping = append(pm.p.Mapping, m)
  288. // Update memoization tables.
  289. if m.BuildID != "" {
  290. pm.mappings[bk] = m
  291. }
  292. if m.File != "" {
  293. pm.mappings[pk] = m
  294. }
  295. mi := mapInfo{m, 0}
  296. pm.mappingsByID[src.ID] = mi
  297. return mi
  298. }
  299. // key generates encoded strings of Mapping to be used as a key for
  300. // maps. The first key represents only the build id, while the second
  301. // represents only the file path.
  302. func (m *Mapping) key() (buildIDKey, pathKey mappingKey) {
  303. // Normalize addresses to handle address space randomization.
  304. // Round up to next 4K boundary to avoid minor discrepancies.
  305. const mapsizeRounding = 0x1000
  306. size := m.Limit - m.Start
  307. size = size + mapsizeRounding - 1
  308. size = size - (size % mapsizeRounding)
  309. buildIDKey = mappingKey{
  310. size,
  311. m.Offset,
  312. m.BuildID,
  313. }
  314. pathKey = mappingKey{
  315. size,
  316. m.Offset,
  317. m.File,
  318. }
  319. return
  320. }
  321. type mappingKey struct {
  322. size, offset uint64
  323. buildidIDOrFile string
  324. }
  325. func (pm *profileMerger) mapLine(src Line) Line {
  326. ln := Line{
  327. Function: pm.mapFunction(src.Function),
  328. Line: src.Line,
  329. }
  330. return ln
  331. }
  332. func (pm *profileMerger) mapFunction(src *Function) *Function {
  333. if src == nil {
  334. return nil
  335. }
  336. if f, ok := pm.functionsByID[src.ID]; ok {
  337. return f
  338. }
  339. k := src.key()
  340. if f, ok := pm.functions[k]; ok {
  341. pm.functionsByID[src.ID] = f
  342. return f
  343. }
  344. f := &Function{
  345. ID: uint64(len(pm.p.Function) + 1),
  346. Name: src.Name,
  347. SystemName: src.SystemName,
  348. Filename: src.Filename,
  349. StartLine: src.StartLine,
  350. }
  351. pm.functions[k] = f
  352. pm.functionsByID[src.ID] = f
  353. pm.p.Function = append(pm.p.Function, f)
  354. return f
  355. }
  356. // key generates a struct to be used as a key for maps.
  357. func (f *Function) key() functionKey {
  358. return functionKey{
  359. f.StartLine,
  360. f.Name,
  361. f.SystemName,
  362. f.Filename,
  363. }
  364. }
  365. type functionKey struct {
  366. startLine int64
  367. name, systemName, fileName string
  368. }
  369. // combineHeaders checks that all profiles can be merged and returns
  370. // their combined profile.
  371. func combineHeaders(srcs []*Profile) (*Profile, error) {
  372. for _, s := range srcs[1:] {
  373. if err := srcs[0].compatible(s); err != nil {
  374. return nil, err
  375. }
  376. }
  377. var timeNanos, durationNanos, period int64
  378. var comments []string
  379. var defaultSampleType string
  380. for _, s := range srcs {
  381. if timeNanos == 0 || s.TimeNanos < timeNanos {
  382. timeNanos = s.TimeNanos
  383. }
  384. durationNanos += s.DurationNanos
  385. if period == 0 || period < s.Period {
  386. period = s.Period
  387. }
  388. comments = append(comments, s.Comments...)
  389. if defaultSampleType == "" {
  390. defaultSampleType = s.DefaultSampleType
  391. }
  392. }
  393. p := &Profile{
  394. SampleType: make([]*ValueType, len(srcs[0].SampleType)),
  395. DropFrames: srcs[0].DropFrames,
  396. KeepFrames: srcs[0].KeepFrames,
  397. TimeNanos: timeNanos,
  398. DurationNanos: durationNanos,
  399. PeriodType: srcs[0].PeriodType,
  400. Period: period,
  401. Comments: comments,
  402. DefaultSampleType: defaultSampleType,
  403. }
  404. copy(p.SampleType, srcs[0].SampleType)
  405. return p, nil
  406. }
  407. // compatible determines if two profiles can be compared/merged.
  408. // returns nil if the profiles are compatible; otherwise an error with
  409. // details on the incompatibility.
  410. func (p *Profile) compatible(pb *Profile) error {
  411. if !equalValueType(p.PeriodType, pb.PeriodType) {
  412. return fmt.Errorf("incompatible period types %v and %v", p.PeriodType, pb.PeriodType)
  413. }
  414. if len(p.SampleType) != len(pb.SampleType) {
  415. return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
  416. }
  417. for i := range p.SampleType {
  418. if !equalValueType(p.SampleType[i], pb.SampleType[i]) {
  419. return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
  420. }
  421. }
  422. return nil
  423. }
  424. // equalValueType returns true if the two value types are semantically
  425. // equal. It ignores the internal fields used during encode/decode.
  426. func equalValueType(st1, st2 *ValueType) bool {
  427. return st1.Type == st2.Type && st1.Unit == st2.Unit
  428. }