暂无描述

driver_test.go 30KB

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