暂无描述

driver_test.go 32KB

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