暂无描述

driver_test.go 29KB

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