暂无描述

driver_test.go 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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 driver
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "testing"
  23. "time"
  24. "github.com/google/pprof/internal/plugin"
  25. "github.com/google/pprof/internal/proftest"
  26. "github.com/google/pprof/internal/symbolz"
  27. "github.com/google/pprof/profile"
  28. )
  29. func TestParse(t *testing.T) {
  30. // Override weblist command to collect output in buffer
  31. pprofCommands["weblist"].postProcess = nil
  32. testcase := []struct {
  33. flags, source string
  34. }{
  35. {"text,functions,flat", "cpu"},
  36. {"tree,addresses,flat,nodecount=4", "cpusmall"},
  37. {"text,functions,flat", "unknown"},
  38. {"text,alloc_objects,flat", "heap_alloc"},
  39. {"text,files,flat", "heap"},
  40. {"text,inuse_objects,flat", "heap"},
  41. {"text,lines,cum,hide=line[X3]0", "cpu"},
  42. {"text,lines,cum,show=[12]00", "cpu"},
  43. {"topproto,lines,cum,hide=mangled[X3]0", "cpu"},
  44. {"tree,lines,cum,focus=[24]00", "heap"},
  45. {"tree,relative_percentages,cum,focus=[24]00", "heap"},
  46. {"callgrind", "cpu"},
  47. {"callgrind", "heap"},
  48. {"dot,functions,flat", "cpu"},
  49. {"dot,lines,flat,focus=[12]00", "heap"},
  50. {"dot,addresses,flat,ignore=[X3]002,focus=[X1]000", "contention"},
  51. {"dot,files,cum", "contention"},
  52. {"tags", "cpu"},
  53. {"tags,tagignore=tag[13],tagfocus=key[12]", "cpu"},
  54. {"traces", "cpu"},
  55. {"dot,alloc_space,flat,focus=[234]00", "heap_alloc"},
  56. {"dot,alloc_space,flat,hide=line.*1?23?", "heap_alloc"},
  57. {"dot,inuse_space,flat,tagfocus=1mb:2gb", "heap"},
  58. {"dot,inuse_space,flat,tagfocus=30kb:,tagignore=1mb:2mb", "heap"},
  59. {"disasm=line[13],addresses,flat", "cpu"},
  60. {"peek=line.*01", "cpu"},
  61. {"weblist=line[13],addresses,flat", "cpu"},
  62. }
  63. baseVars := pprofVariables
  64. defer func() { pprofVariables = baseVars }()
  65. for _, tc := range testcase {
  66. // Reset the pprof variables before processing
  67. pprofVariables = baseVars.makeCopy()
  68. f := baseFlags()
  69. f.args = []string{tc.source}
  70. flags := strings.Split(tc.flags, ",")
  71. // Skip the output format in the first flag, to output to a proto
  72. addFlags(&f, flags[1:])
  73. // Encode profile into a protobuf and decode it again.
  74. protoTempFile, err := ioutil.TempFile("", "profile_proto")
  75. if err != nil {
  76. t.Errorf("cannot create tempfile: %v", err)
  77. }
  78. defer protoTempFile.Close()
  79. f.strings["output"] = protoTempFile.Name()
  80. if flags[0] == "topproto" {
  81. f.bools["proto"] = false
  82. f.bools["topproto"] = true
  83. }
  84. // First pprof invocation to save the profile into a profile.proto.
  85. o1 := setDefaults(nil)
  86. o1.Flagset = f
  87. o1.Fetch = testFetcher{}
  88. o1.Sym = testSymbolizer{}
  89. if err := PProf(o1); err != nil {
  90. t.Errorf("%s %q: %v", tc.source, tc.flags, err)
  91. continue
  92. }
  93. // Reset the pprof variables after the proto invocation
  94. pprofVariables = baseVars.makeCopy()
  95. // Read the profile from the encoded protobuf
  96. outputTempFile, err := ioutil.TempFile("", "profile_output")
  97. if err != nil {
  98. t.Errorf("cannot create tempfile: %v", err)
  99. }
  100. defer outputTempFile.Close()
  101. f.strings["output"] = outputTempFile.Name()
  102. f.args = []string{protoTempFile.Name()}
  103. var solution string
  104. // Apply the flags for the second pprof run, and identify name of
  105. // the file containing expected results
  106. if flags[0] == "topproto" {
  107. solution = solutionFilename(tc.source, &f)
  108. delete(f.bools, "topproto")
  109. f.bools["text"] = true
  110. } else {
  111. delete(f.bools, "proto")
  112. addFlags(&f, flags[:1])
  113. solution = solutionFilename(tc.source, &f)
  114. }
  115. // Second pprof invocation to read the profile from profile.proto
  116. // and generate a report.
  117. o2 := setDefaults(nil)
  118. o2.Flagset = f
  119. o2.Sym = testSymbolizeDemangler{}
  120. o2.Obj = new(mockObjTool)
  121. if err := PProf(o2); err != nil {
  122. t.Errorf("%s: %v", tc.source, err)
  123. }
  124. b, err := ioutil.ReadFile(outputTempFile.Name())
  125. if err != nil {
  126. t.Errorf("Failed to read profile %s: %v", outputTempFile.Name(), err)
  127. }
  128. // Read data file with expected solution
  129. solution = "testdata/" + solution
  130. sbuf, err := ioutil.ReadFile(solution)
  131. if err != nil {
  132. t.Errorf("reading solution file %s: %v", solution, err)
  133. continue
  134. }
  135. if flags[0] == "svg" {
  136. b = removeScripts(b)
  137. sbuf = removeScripts(sbuf)
  138. }
  139. if string(b) != string(sbuf) {
  140. t.Errorf("diff %s %s", solution, tc.source)
  141. d, err := proftest.Diff(sbuf, b)
  142. if err != nil {
  143. t.Fatalf("diff %s %v", solution, err)
  144. }
  145. t.Errorf("%s\n%s\n", solution, d)
  146. }
  147. }
  148. }
  149. // removeScripts removes <script > .. </script> pairs from its input
  150. func removeScripts(in []byte) []byte {
  151. beginMarker := []byte("<script")
  152. endMarker := []byte("</script>")
  153. if begin := bytes.Index(in, beginMarker); begin > 0 {
  154. if end := bytes.Index(in[begin:], endMarker); end > 0 {
  155. in = append(in[:begin], removeScripts(in[begin+end+len(endMarker):])...)
  156. }
  157. }
  158. return in
  159. }
  160. // addFlags parses flag descriptions and adds them to the testFlags
  161. func addFlags(f *testFlags, flags []string) {
  162. for _, flag := range flags {
  163. fields := strings.SplitN(flag, "=", 2)
  164. switch len(fields) {
  165. case 1:
  166. f.bools[fields[0]] = true
  167. case 2:
  168. if i, err := strconv.Atoi(fields[1]); err == nil {
  169. f.ints[fields[0]] = i
  170. } else {
  171. f.strings[fields[0]] = fields[1]
  172. }
  173. }
  174. }
  175. }
  176. // solutionFilename returns the name of the solution file for the test
  177. func solutionFilename(source string, f *testFlags) string {
  178. name := []string{"pprof", strings.TrimPrefix(source, "http://host:8000/")}
  179. name = addString(name, f, []string{"flat", "cum"})
  180. name = addString(name, f, []string{"functions", "files", "lines", "addresses"})
  181. name = addString(name, f, []string{"inuse_space", "inuse_objects", "alloc_space", "alloc_objects"})
  182. name = addString(name, f, []string{"relative_percentages"})
  183. name = addString(name, f, []string{"seconds"})
  184. name = addString(name, f, []string{"text", "tree", "callgrind", "dot", "svg", "tags", "dot", "traces", "disasm", "peek", "weblist", "topproto"})
  185. if f.strings["focus"] != "" || f.strings["tagfocus"] != "" {
  186. name = append(name, "focus")
  187. }
  188. if f.strings["ignore"] != "" || f.strings["tagignore"] != "" {
  189. name = append(name, "ignore")
  190. }
  191. name = addString(name, f, []string{"hide", "show"})
  192. return strings.Join(name, ".")
  193. }
  194. func addString(name []string, f *testFlags, components []string) []string {
  195. for _, c := range components {
  196. if f.bools[c] || f.strings[c] != "" || f.ints[c] != 0 {
  197. return append(name, c)
  198. }
  199. }
  200. return name
  201. }
  202. // testFlags implements the plugin.FlagSet interface.
  203. type testFlags struct {
  204. bools map[string]bool
  205. ints map[string]int
  206. floats map[string]float64
  207. strings map[string]string
  208. args []string
  209. }
  210. func (testFlags) ExtraUsage() string { return "" }
  211. func (f testFlags) Bool(s string, d bool, c string) *bool {
  212. if b, ok := f.bools[s]; ok {
  213. return &b
  214. }
  215. return &d
  216. }
  217. func (f testFlags) Int(s string, d int, c string) *int {
  218. if i, ok := f.ints[s]; ok {
  219. return &i
  220. }
  221. return &d
  222. }
  223. func (f testFlags) Float64(s string, d float64, c string) *float64 {
  224. if g, ok := f.floats[s]; ok {
  225. return &g
  226. }
  227. return &d
  228. }
  229. func (f testFlags) String(s, d, c string) *string {
  230. if t, ok := f.strings[s]; ok {
  231. return &t
  232. }
  233. return &d
  234. }
  235. func (f testFlags) BoolVar(p *bool, s string, d bool, c string) {
  236. if b, ok := f.bools[s]; ok {
  237. *p = b
  238. } else {
  239. *p = d
  240. }
  241. }
  242. func (f testFlags) IntVar(p *int, s string, d int, c string) {
  243. if i, ok := f.ints[s]; ok {
  244. *p = i
  245. } else {
  246. *p = d
  247. }
  248. }
  249. func (f testFlags) Float64Var(p *float64, s string, d float64, c string) {
  250. if g, ok := f.floats[s]; ok {
  251. *p = g
  252. } else {
  253. *p = d
  254. }
  255. }
  256. func (f testFlags) StringVar(p *string, s, d, c string) {
  257. if t, ok := f.strings[s]; ok {
  258. *p = t
  259. } else {
  260. *p = d
  261. }
  262. }
  263. func (f testFlags) StringList(s, d, c string) *[]*string {
  264. return &[]*string{}
  265. }
  266. func (f testFlags) Parse(func()) []string {
  267. return f.args
  268. }
  269. func baseFlags() testFlags {
  270. return testFlags{
  271. bools: map[string]bool{
  272. "proto": true,
  273. "trim": true,
  274. "compact_labels": true,
  275. },
  276. ints: map[string]int{
  277. "nodecount": 20,
  278. },
  279. floats: map[string]float64{
  280. "nodefraction": 0.05,
  281. "edgefraction": 0.01,
  282. "divide_by": 1.0,
  283. },
  284. strings: map[string]string{
  285. "unit": "minimum",
  286. },
  287. }
  288. }
  289. type testProfile struct {
  290. }
  291. const testStart = 0x1000
  292. const testOffset = 0x5000
  293. type testFetcher struct{}
  294. func (testFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) {
  295. var p *profile.Profile
  296. s = strings.TrimPrefix(s, "http://host:8000/")
  297. switch s {
  298. case "cpu", "unknown":
  299. p = cpuProfile()
  300. case "cpusmall":
  301. p = cpuProfileSmall()
  302. case "heap":
  303. p = heapProfile()
  304. case "heap_alloc":
  305. p = heapProfile()
  306. p.SampleType = []*profile.ValueType{
  307. {Type: "alloc_objects", Unit: "count"},
  308. {Type: "alloc_space", Unit: "bytes"},
  309. }
  310. case "contention":
  311. p = contentionProfile()
  312. case "symbolz":
  313. p = symzProfile()
  314. case "http://host2/symbolz":
  315. p = symzProfile()
  316. p.Mapping[0].Start += testOffset
  317. p.Mapping[0].Limit += testOffset
  318. for i := range p.Location {
  319. p.Location[i].Address += testOffset
  320. }
  321. default:
  322. return nil, "", fmt.Errorf("unexpected source: %s", s)
  323. }
  324. return p, s, nil
  325. }
  326. type testSymbolizer struct{}
  327. func (testSymbolizer) Symbolize(_ string, _ plugin.MappingSources, _ *profile.Profile) error {
  328. return nil
  329. }
  330. type testSymbolizeDemangler struct{}
  331. func (testSymbolizeDemangler) Symbolize(_ string, _ plugin.MappingSources, p *profile.Profile) error {
  332. for _, fn := range p.Function {
  333. if fn.Name == "" || fn.SystemName == fn.Name {
  334. fn.Name = fakeDemangler(fn.SystemName)
  335. }
  336. }
  337. return nil
  338. }
  339. func testFetchSymbols(source, post string) ([]byte, error) {
  340. var buf bytes.Buffer
  341. if source == "http://host2/symbolz" {
  342. for _, address := range strings.Split(post, "+") {
  343. a, _ := strconv.ParseInt(address, 0, 64)
  344. fmt.Fprintf(&buf, "%v\t", address)
  345. if a-testStart < testOffset {
  346. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  347. continue
  348. }
  349. fmt.Fprintf(&buf, "%#x\n", a-testStart-testOffset)
  350. }
  351. return buf.Bytes(), nil
  352. }
  353. for _, address := range strings.Split(post, "+") {
  354. a, _ := strconv.ParseInt(address, 0, 64)
  355. fmt.Fprintf(&buf, "%v\t", address)
  356. if a-testStart > testOffset {
  357. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  358. continue
  359. }
  360. fmt.Fprintf(&buf, "%#x\n", a-testStart)
  361. }
  362. return buf.Bytes(), nil
  363. }
  364. type testSymbolzSymbolizer struct{}
  365. func (testSymbolzSymbolizer) Symbolize(variables string, sources plugin.MappingSources, p *profile.Profile) error {
  366. return symbolz.Symbolize(sources, testFetchSymbols, p, nil)
  367. }
  368. func fakeDemangler(name string) string {
  369. switch name {
  370. case "mangled1000":
  371. return "line1000"
  372. case "mangled2000":
  373. return "line2000"
  374. case "mangled2001":
  375. return "line2001"
  376. case "mangled3000":
  377. return "line3000"
  378. case "mangled3001":
  379. return "line3001"
  380. case "mangled3002":
  381. return "line3002"
  382. case "mangledNEW":
  383. return "operator new"
  384. case "mangledMALLOC":
  385. return "malloc"
  386. default:
  387. return name
  388. }
  389. }
  390. func cpuProfile() *profile.Profile {
  391. var cpuM = []*profile.Mapping{
  392. {
  393. ID: 1,
  394. Start: 0x1000,
  395. Limit: 0x4000,
  396. File: "testbinary",
  397. HasFunctions: true,
  398. HasFilenames: true,
  399. HasLineNumbers: true,
  400. HasInlineFrames: true,
  401. },
  402. }
  403. var cpuF = []*profile.Function{
  404. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  405. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  406. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  407. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  408. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  409. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  410. }
  411. var cpuL = []*profile.Location{
  412. {
  413. ID: 1000,
  414. Mapping: cpuM[0],
  415. Address: 0x1000,
  416. Line: []profile.Line{
  417. {Function: cpuF[0], Line: 1},
  418. },
  419. },
  420. {
  421. ID: 2000,
  422. Mapping: cpuM[0],
  423. Address: 0x2000,
  424. Line: []profile.Line{
  425. {Function: cpuF[2], Line: 9},
  426. {Function: cpuF[1], Line: 4},
  427. },
  428. },
  429. {
  430. ID: 3000,
  431. Mapping: cpuM[0],
  432. Address: 0x3000,
  433. Line: []profile.Line{
  434. {Function: cpuF[5], Line: 2},
  435. {Function: cpuF[4], Line: 5},
  436. {Function: cpuF[3], Line: 6},
  437. },
  438. },
  439. {
  440. ID: 3001,
  441. Mapping: cpuM[0],
  442. Address: 0x3001,
  443. Line: []profile.Line{
  444. {Function: cpuF[4], Line: 8},
  445. {Function: cpuF[3], Line: 9},
  446. },
  447. },
  448. {
  449. ID: 3002,
  450. Mapping: cpuM[0],
  451. Address: 0x3002,
  452. Line: []profile.Line{
  453. {Function: cpuF[5], Line: 5},
  454. {Function: cpuF[3], Line: 7},
  455. },
  456. },
  457. }
  458. return &profile.Profile{
  459. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  460. Period: 1,
  461. DurationNanos: 10e9,
  462. SampleType: []*profile.ValueType{
  463. {Type: "samples", Unit: "count"},
  464. {Type: "cpu", Unit: "milliseconds"},
  465. },
  466. Sample: []*profile.Sample{
  467. {
  468. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  469. Value: []int64{1000, 1000},
  470. Label: map[string][]string{
  471. "key1": []string{"tag1"},
  472. "key2": []string{"tag1"},
  473. },
  474. },
  475. {
  476. Location: []*profile.Location{cpuL[0], cpuL[3]},
  477. Value: []int64{100, 100},
  478. Label: map[string][]string{
  479. "key1": []string{"tag2"},
  480. "key3": []string{"tag2"},
  481. },
  482. },
  483. {
  484. Location: []*profile.Location{cpuL[1], cpuL[4]},
  485. Value: []int64{10, 10},
  486. Label: map[string][]string{
  487. "key1": []string{"tag3"},
  488. "key2": []string{"tag2"},
  489. },
  490. },
  491. {
  492. Location: []*profile.Location{cpuL[2]},
  493. Value: []int64{10, 10},
  494. Label: map[string][]string{
  495. "key1": []string{"tag4"},
  496. "key2": []string{"tag1"},
  497. },
  498. },
  499. },
  500. Location: cpuL,
  501. Function: cpuF,
  502. Mapping: cpuM,
  503. }
  504. }
  505. func cpuProfileSmall() *profile.Profile {
  506. var cpuM = []*profile.Mapping{
  507. {
  508. ID: 1,
  509. Start: 0x1000,
  510. Limit: 0x4000,
  511. File: "testbinary",
  512. HasFunctions: true,
  513. HasFilenames: true,
  514. HasLineNumbers: true,
  515. HasInlineFrames: true,
  516. },
  517. }
  518. var cpuL = []*profile.Location{
  519. {
  520. ID: 1000,
  521. Mapping: cpuM[0],
  522. Address: 0x1000,
  523. },
  524. {
  525. ID: 2000,
  526. Mapping: cpuM[0],
  527. Address: 0x2000,
  528. },
  529. {
  530. ID: 3000,
  531. Mapping: cpuM[0],
  532. Address: 0x3000,
  533. },
  534. {
  535. ID: 4000,
  536. Mapping: cpuM[0],
  537. Address: 0x4000,
  538. },
  539. {
  540. ID: 5000,
  541. Mapping: cpuM[0],
  542. Address: 0x5000,
  543. },
  544. }
  545. return &profile.Profile{
  546. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  547. Period: 1,
  548. DurationNanos: 10e9,
  549. SampleType: []*profile.ValueType{
  550. {Type: "samples", Unit: "count"},
  551. {Type: "cpu", Unit: "milliseconds"},
  552. },
  553. Sample: []*profile.Sample{
  554. {
  555. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  556. Value: []int64{1000, 1000},
  557. },
  558. {
  559. Location: []*profile.Location{cpuL[3], cpuL[1], cpuL[4]},
  560. Value: []int64{1000, 1000},
  561. },
  562. {
  563. Location: []*profile.Location{cpuL[2]},
  564. Value: []int64{1000, 1000},
  565. },
  566. {
  567. Location: []*profile.Location{cpuL[4]},
  568. Value: []int64{1000, 1000},
  569. },
  570. },
  571. Location: cpuL,
  572. Function: nil,
  573. Mapping: cpuM,
  574. }
  575. }
  576. func heapProfile() *profile.Profile {
  577. var heapM = []*profile.Mapping{
  578. {
  579. ID: 1,
  580. BuildID: "buildid",
  581. Start: 0x1000,
  582. Limit: 0x4000,
  583. HasFunctions: true,
  584. HasFilenames: true,
  585. HasLineNumbers: true,
  586. HasInlineFrames: true,
  587. },
  588. }
  589. var heapF = []*profile.Function{
  590. {ID: 1, Name: "pruneme", SystemName: "pruneme", Filename: "prune.h"},
  591. {ID: 2, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  592. {ID: 3, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  593. {ID: 4, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  594. {ID: 5, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  595. {ID: 6, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  596. {ID: 7, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  597. {ID: 8, Name: "mangledMALLOC", SystemName: "mangledMALLOC", Filename: "malloc.h"},
  598. {ID: 9, Name: "mangledNEW", SystemName: "mangledNEW", Filename: "new.h"},
  599. }
  600. var heapL = []*profile.Location{
  601. {
  602. ID: 1000,
  603. Mapping: heapM[0],
  604. Address: 0x1000,
  605. Line: []profile.Line{
  606. {Function: heapF[0], Line: 100},
  607. {Function: heapF[7], Line: 100},
  608. {Function: heapF[1], Line: 1},
  609. },
  610. },
  611. {
  612. ID: 2000,
  613. Mapping: heapM[0],
  614. Address: 0x2000,
  615. Line: []profile.Line{
  616. {Function: heapF[8], Line: 100},
  617. {Function: heapF[3], Line: 2},
  618. {Function: heapF[2], Line: 3},
  619. },
  620. },
  621. {
  622. ID: 3000,
  623. Mapping: heapM[0],
  624. Address: 0x3000,
  625. Line: []profile.Line{
  626. {Function: heapF[8], Line: 100},
  627. {Function: heapF[6], Line: 3},
  628. {Function: heapF[5], Line: 2},
  629. {Function: heapF[4], Line: 4},
  630. },
  631. },
  632. {
  633. ID: 3001,
  634. Mapping: heapM[0],
  635. Address: 0x3001,
  636. Line: []profile.Line{
  637. {Function: heapF[0], Line: 100},
  638. {Function: heapF[8], Line: 100},
  639. {Function: heapF[5], Line: 2},
  640. {Function: heapF[4], Line: 4},
  641. },
  642. },
  643. {
  644. ID: 3002,
  645. Mapping: heapM[0],
  646. Address: 0x3002,
  647. Line: []profile.Line{
  648. {Function: heapF[6], Line: 3},
  649. {Function: heapF[4], Line: 4},
  650. },
  651. },
  652. }
  653. return &profile.Profile{
  654. PeriodType: &profile.ValueType{Type: "allocations", Unit: "bytes"},
  655. Period: 524288,
  656. SampleType: []*profile.ValueType{
  657. {Type: "inuse_objects", Unit: "count"},
  658. {Type: "inuse_space", Unit: "bytes"},
  659. },
  660. Sample: []*profile.Sample{
  661. {
  662. Location: []*profile.Location{heapL[0], heapL[1], heapL[2]},
  663. Value: []int64{10, 1024000},
  664. NumLabel: map[string][]int64{
  665. "bytes": []int64{102400},
  666. },
  667. },
  668. {
  669. Location: []*profile.Location{heapL[0], heapL[3]},
  670. Value: []int64{20, 4096000},
  671. NumLabel: map[string][]int64{
  672. "bytes": []int64{204800},
  673. },
  674. },
  675. {
  676. Location: []*profile.Location{heapL[1], heapL[4]},
  677. Value: []int64{40, 65536000},
  678. NumLabel: map[string][]int64{
  679. "bytes": []int64{1638400},
  680. },
  681. },
  682. {
  683. Location: []*profile.Location{heapL[2]},
  684. Value: []int64{80, 32768000},
  685. NumLabel: map[string][]int64{
  686. "bytes": []int64{409600},
  687. },
  688. },
  689. },
  690. DropFrames: ".*operator new.*|malloc",
  691. Location: heapL,
  692. Function: heapF,
  693. Mapping: heapM,
  694. }
  695. }
  696. func contentionProfile() *profile.Profile {
  697. var contentionM = []*profile.Mapping{
  698. {
  699. ID: 1,
  700. BuildID: "buildid-contention",
  701. Start: 0x1000,
  702. Limit: 0x4000,
  703. HasFunctions: true,
  704. HasFilenames: true,
  705. HasLineNumbers: true,
  706. HasInlineFrames: true,
  707. },
  708. }
  709. var contentionF = []*profile.Function{
  710. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  711. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  712. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  713. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  714. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  715. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  716. }
  717. var contentionL = []*profile.Location{
  718. {
  719. ID: 1000,
  720. Mapping: contentionM[0],
  721. Address: 0x1000,
  722. Line: []profile.Line{
  723. {Function: contentionF[0], Line: 1},
  724. },
  725. },
  726. {
  727. ID: 2000,
  728. Mapping: contentionM[0],
  729. Address: 0x2000,
  730. Line: []profile.Line{
  731. {Function: contentionF[2], Line: 2},
  732. {Function: contentionF[1], Line: 3},
  733. },
  734. },
  735. {
  736. ID: 3000,
  737. Mapping: contentionM[0],
  738. Address: 0x3000,
  739. Line: []profile.Line{
  740. {Function: contentionF[5], Line: 2},
  741. {Function: contentionF[4], Line: 3},
  742. {Function: contentionF[3], Line: 5},
  743. },
  744. },
  745. {
  746. ID: 3001,
  747. Mapping: contentionM[0],
  748. Address: 0x3001,
  749. Line: []profile.Line{
  750. {Function: contentionF[4], Line: 3},
  751. {Function: contentionF[3], Line: 5},
  752. },
  753. },
  754. {
  755. ID: 3002,
  756. Mapping: contentionM[0],
  757. Address: 0x3002,
  758. Line: []profile.Line{
  759. {Function: contentionF[5], Line: 4},
  760. {Function: contentionF[3], Line: 3},
  761. },
  762. },
  763. }
  764. return &profile.Profile{
  765. PeriodType: &profile.ValueType{Type: "contentions", Unit: "count"},
  766. Period: 524288,
  767. SampleType: []*profile.ValueType{
  768. {Type: "contentions", Unit: "count"},
  769. {Type: "delay", Unit: "nanoseconds"},
  770. },
  771. Sample: []*profile.Sample{
  772. {
  773. Location: []*profile.Location{contentionL[0], contentionL[1], contentionL[2]},
  774. Value: []int64{10, 10240000},
  775. },
  776. {
  777. Location: []*profile.Location{contentionL[0], contentionL[3]},
  778. Value: []int64{20, 40960000},
  779. },
  780. {
  781. Location: []*profile.Location{contentionL[1], contentionL[4]},
  782. Value: []int64{40, 65536000},
  783. },
  784. {
  785. Location: []*profile.Location{contentionL[2]},
  786. Value: []int64{80, 32768000},
  787. },
  788. },
  789. Location: contentionL,
  790. Function: contentionF,
  791. Mapping: contentionM,
  792. Comments: []string{"Comment #1", "Comment #2"},
  793. }
  794. }
  795. func symzProfile() *profile.Profile {
  796. var symzM = []*profile.Mapping{
  797. {
  798. ID: 1,
  799. Start: testStart,
  800. Limit: 0x4000,
  801. File: "testbinary",
  802. },
  803. }
  804. var symzL = []*profile.Location{
  805. {ID: 1, Mapping: symzM[0], Address: testStart},
  806. {ID: 2, Mapping: symzM[0], Address: testStart + 0x1000},
  807. {ID: 3, Mapping: symzM[0], Address: testStart + 0x2000},
  808. }
  809. return &profile.Profile{
  810. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  811. Period: 1,
  812. DurationNanos: 10e9,
  813. SampleType: []*profile.ValueType{
  814. {Type: "samples", Unit: "count"},
  815. {Type: "cpu", Unit: "milliseconds"},
  816. },
  817. Sample: []*profile.Sample{
  818. {
  819. Location: []*profile.Location{symzL[0], symzL[1], symzL[2]},
  820. Value: []int64{1, 1},
  821. },
  822. },
  823. Location: symzL,
  824. Mapping: symzM,
  825. }
  826. }
  827. var autoCompleteTests = []struct {
  828. in string
  829. out string
  830. }{
  831. {"", ""},
  832. {"xyz", "xyz"}, // no match
  833. {"dis", "disasm"}, // single match
  834. {"t", "t"}, // many matches
  835. {"top abc", "top abc"}, // no function name match
  836. {"top mangledM", "top mangledMALLOC"}, // single function name match
  837. {"top cmd cmd mangledM", "top cmd cmd mangledMALLOC"},
  838. {"top mangled", "top mangled"}, // many function name matches
  839. {"cmd mangledM", "cmd mangledM"}, // invalid command
  840. {"top mangledM cmd", "top mangledM cmd"}, // cursor misplaced
  841. {"top edMA", "top mangledMALLOC"}, // single infix function name match
  842. {"top -mangledM", "top -mangledMALLOC"}, // ignore sign handled
  843. {"lin", "lines"}, // single variable match
  844. {"EdGeF", "edgefraction"}, // single capitalized match
  845. {"help dis", "help disasm"}, // help command match
  846. {"help relative_perc", "help relative_percentages"}, // help variable match
  847. {"help coMpa", "help compact_labels"}, // help variable capitalized match
  848. }
  849. func TestAutoComplete(t *testing.T) {
  850. complete := newCompleter(functionNames(heapProfile()))
  851. for _, test := range autoCompleteTests {
  852. if out := complete(test.in); out != test.out {
  853. t.Errorf("autoComplete(%s) = %s; want %s", test.in, out, test.out)
  854. }
  855. }
  856. }
  857. func TestTagFilter(t *testing.T) {
  858. var tagFilterTests = []struct {
  859. name, value string
  860. tags map[string][]string
  861. want bool
  862. }{
  863. {"test1", "tag2", map[string][]string{"value1": {"tag1", "tag2"}}, true},
  864. {"test2", "tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false},
  865. {"test3", "tag1,tag3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true},
  866. {"test4", "t..[12],t..3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true},
  867. {"test5", "tag2,tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false},
  868. }
  869. for _, test := range tagFilterTests {
  870. filter, err := compileTagFilter(test.name, test.value, &proftest.TestUI{T: t}, nil)
  871. if err != nil {
  872. t.Errorf("tagFilter %s:%v", test.name, err)
  873. continue
  874. }
  875. s := profile.Sample{
  876. Label: test.tags,
  877. }
  878. if got := filter(&s); got != test.want {
  879. t.Errorf("tagFilter %s: got %v, want %v", test.name, got, test.want)
  880. }
  881. }
  882. }
  883. func TestSymbolzAfterMerge(t *testing.T) {
  884. baseVars := pprofVariables
  885. pprofVariables = baseVars.makeCopy()
  886. defer func() { pprofVariables = baseVars }()
  887. f := baseFlags()
  888. f.args = []string{"symbolz", "http://host2/symbolz"}
  889. o := setDefaults(nil)
  890. o.Flagset = f
  891. o.Obj = new(mockObjTool)
  892. src, cmd, err := parseFlags(o)
  893. if err != nil {
  894. t.Fatalf("parseFlags: %v", err)
  895. }
  896. if len(cmd) != 1 || cmd[0] != "proto" {
  897. t.Fatalf("parseFlags returned command %v, want [proto]", cmd)
  898. }
  899. o.Fetch = testFetcher{}
  900. o.Sym = testSymbolzSymbolizer{}
  901. p, err := fetchProfiles(src, o)
  902. if err != nil {
  903. t.Fatalf("fetchProfiles: %v", err)
  904. }
  905. if len(p.Location) != 3 {
  906. t.Errorf("Got %d locations after merge, want %d", len(p.Location), 3)
  907. }
  908. for i, l := range p.Location {
  909. if len(l.Line) != 1 {
  910. t.Errorf("Number of lines for symbolz %#x in iteration %d, got %d, want %d", l.Address, i, len(l.Line), 1)
  911. continue
  912. }
  913. address := l.Address - l.Mapping.Start
  914. if got, want := l.Line[0].Function.Name, fmt.Sprintf("%#x", address); got != want {
  915. t.Errorf("symbolz %#x, got %s, want %s", address, got, want)
  916. }
  917. }
  918. }
  919. type mockObjTool struct{}
  920. func (*mockObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  921. return &mockFile{file, "abcdef", 0}, nil
  922. }
  923. func (m *mockObjTool) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  924. switch start {
  925. case 0x1000:
  926. return []plugin.Inst{
  927. {0x1000, "instruction one", "", 0},
  928. {0x1001, "instruction two", "", 0},
  929. {0x1002, "instruction three", "", 0},
  930. {0x1003, "instruction four", "", 0},
  931. }, nil
  932. case 0x3000:
  933. return []plugin.Inst{
  934. {0x3000, "instruction one", "", 0},
  935. {0x3001, "instruction two", "", 0},
  936. {0x3002, "instruction three", "", 0},
  937. {0x3003, "instruction four", "", 0},
  938. {0x3004, "instruction five", "", 0},
  939. }, nil
  940. }
  941. return nil, fmt.Errorf("unimplemented")
  942. }
  943. type mockFile struct {
  944. name, buildId string
  945. base uint64
  946. }
  947. // Name returns the underlyinf file name, if available
  948. func (m *mockFile) Name() string {
  949. return m.name
  950. }
  951. // Base returns the base address to use when looking up symbols in the file.
  952. func (m *mockFile) Base() uint64 {
  953. return m.base
  954. }
  955. // BuildID returns the GNU build ID of the file, or an empty string.
  956. func (m *mockFile) BuildID() string {
  957. return m.buildId
  958. }
  959. // SourceLine reports the source line information for a given
  960. // address in the file. Due to inlining, the source line information
  961. // is in general a list of positions representing a call stack,
  962. // with the leaf function first.
  963. func (*mockFile) SourceLine(addr uint64) ([]plugin.Frame, error) {
  964. return nil, fmt.Errorf("unimplemented")
  965. }
  966. // Symbols returns a list of symbols in the object file.
  967. // If r is not nil, Symbols restricts the list to symbols
  968. // with names matching the regular expression.
  969. // If addr is not zero, Symbols restricts the list to symbols
  970. // containing that address.
  971. func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  972. switch r.String() {
  973. case "line[13]":
  974. return []*plugin.Sym{
  975. {[]string{"line1000"}, m.name, 0x1000, 0x1003},
  976. {[]string{"line3000"}, m.name, 0x3000, 0x3004},
  977. }, nil
  978. }
  979. return nil, fmt.Errorf("unimplemented")
  980. }
  981. // Close closes the file, releasing associated resources.
  982. func (*mockFile) Close() error {
  983. return nil
  984. }