Nav apraksta

driver_test.go 30KB

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