暂无描述

driver_test.go 32KB

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