暂无描述

driver_test.go 29KB

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