Açıklama Yok

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. const testStart = 0x1000
  332. const testOffset = 0x5000
  333. type testFetcher struct{}
  334. func (testFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) {
  335. var p *profile.Profile
  336. s = strings.TrimPrefix(s, "http://host:8000/")
  337. switch s {
  338. case "cpu", "unknown":
  339. p = cpuProfile()
  340. case "cpusmall":
  341. p = cpuProfileSmall()
  342. case "heap":
  343. p = heapProfile()
  344. case "heap_alloc":
  345. p = heapProfile()
  346. p.SampleType = []*profile.ValueType{
  347. {Type: "alloc_objects", Unit: "count"},
  348. {Type: "alloc_space", Unit: "bytes"},
  349. }
  350. case "contention":
  351. p = contentionProfile()
  352. case "symbolz":
  353. p = symzProfile()
  354. case "http://host2/symbolz":
  355. p = symzProfile()
  356. p.Mapping[0].Start += testOffset
  357. p.Mapping[0].Limit += testOffset
  358. for i := range p.Location {
  359. p.Location[i].Address += testOffset
  360. }
  361. default:
  362. return nil, "", fmt.Errorf("unexpected source: %s", s)
  363. }
  364. return p, s, nil
  365. }
  366. type testSymbolizer struct{}
  367. func (testSymbolizer) Symbolize(_ string, _ plugin.MappingSources, _ *profile.Profile) error {
  368. return nil
  369. }
  370. type testSymbolizeDemangler struct{}
  371. func (testSymbolizeDemangler) Symbolize(_ string, _ plugin.MappingSources, p *profile.Profile) error {
  372. for _, fn := range p.Function {
  373. if fn.Name == "" || fn.SystemName == fn.Name {
  374. fn.Name = fakeDemangler(fn.SystemName)
  375. }
  376. }
  377. return nil
  378. }
  379. func testFetchSymbols(source, post string) ([]byte, error) {
  380. var buf bytes.Buffer
  381. if source == "http://host2/symbolz" {
  382. for _, address := range strings.Split(post, "+") {
  383. a, _ := strconv.ParseInt(address, 0, 64)
  384. fmt.Fprintf(&buf, "%v\t", address)
  385. if a-testStart < testOffset {
  386. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  387. continue
  388. }
  389. fmt.Fprintf(&buf, "%#x\n", a-testStart-testOffset)
  390. }
  391. return buf.Bytes(), nil
  392. }
  393. for _, address := range strings.Split(post, "+") {
  394. a, _ := strconv.ParseInt(address, 0, 64)
  395. fmt.Fprintf(&buf, "%v\t", address)
  396. if a-testStart > testOffset {
  397. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  398. continue
  399. }
  400. fmt.Fprintf(&buf, "%#x\n", a-testStart)
  401. }
  402. return buf.Bytes(), nil
  403. }
  404. type testSymbolzSymbolizer struct{}
  405. func (testSymbolzSymbolizer) Symbolize(variables string, sources plugin.MappingSources, p *profile.Profile) error {
  406. return symbolz.Symbolize(sources, testFetchSymbols, p, nil)
  407. }
  408. func fakeDemangler(name string) string {
  409. switch name {
  410. case "mangled1000":
  411. return "line1000"
  412. case "mangled2000":
  413. return "line2000"
  414. case "mangled2001":
  415. return "line2001"
  416. case "mangled3000":
  417. return "line3000"
  418. case "mangled3001":
  419. return "line3001"
  420. case "mangled3002":
  421. return "line3002"
  422. case "mangledNEW":
  423. return "operator new"
  424. case "mangledMALLOC":
  425. return "malloc"
  426. default:
  427. return name
  428. }
  429. }
  430. func cpuProfile() *profile.Profile {
  431. var cpuM = []*profile.Mapping{
  432. {
  433. ID: 1,
  434. Start: 0x1000,
  435. Limit: 0x4000,
  436. File: "/path/to/testbinary",
  437. HasFunctions: true,
  438. HasFilenames: true,
  439. HasLineNumbers: true,
  440. HasInlineFrames: true,
  441. },
  442. }
  443. var cpuF = []*profile.Function{
  444. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  445. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  446. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  447. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  448. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  449. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  450. }
  451. var cpuL = []*profile.Location{
  452. {
  453. ID: 1000,
  454. Mapping: cpuM[0],
  455. Address: 0x1000,
  456. Line: []profile.Line{
  457. {Function: cpuF[0], Line: 1},
  458. },
  459. },
  460. {
  461. ID: 2000,
  462. Mapping: cpuM[0],
  463. Address: 0x2000,
  464. Line: []profile.Line{
  465. {Function: cpuF[2], Line: 9},
  466. {Function: cpuF[1], Line: 4},
  467. },
  468. },
  469. {
  470. ID: 3000,
  471. Mapping: cpuM[0],
  472. Address: 0x3000,
  473. Line: []profile.Line{
  474. {Function: cpuF[5], Line: 2},
  475. {Function: cpuF[4], Line: 5},
  476. {Function: cpuF[3], Line: 6},
  477. },
  478. },
  479. {
  480. ID: 3001,
  481. Mapping: cpuM[0],
  482. Address: 0x3001,
  483. Line: []profile.Line{
  484. {Function: cpuF[4], Line: 8},
  485. {Function: cpuF[3], Line: 9},
  486. },
  487. },
  488. {
  489. ID: 3002,
  490. Mapping: cpuM[0],
  491. Address: 0x3002,
  492. Line: []profile.Line{
  493. {Function: cpuF[5], Line: 5},
  494. {Function: cpuF[3], Line: 9},
  495. },
  496. },
  497. }
  498. return &profile.Profile{
  499. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  500. Period: 1,
  501. DurationNanos: 10e9,
  502. SampleType: []*profile.ValueType{
  503. {Type: "samples", Unit: "count"},
  504. {Type: "cpu", Unit: "milliseconds"},
  505. },
  506. Sample: []*profile.Sample{
  507. {
  508. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  509. Value: []int64{1000, 1000},
  510. Label: map[string][]string{
  511. "key1": {"tag1"},
  512. "key2": {"tag1"},
  513. },
  514. },
  515. {
  516. Location: []*profile.Location{cpuL[0], cpuL[3]},
  517. Value: []int64{100, 100},
  518. Label: map[string][]string{
  519. "key1": {"tag2"},
  520. "key3": {"tag2"},
  521. },
  522. },
  523. {
  524. Location: []*profile.Location{cpuL[1], cpuL[4]},
  525. Value: []int64{10, 10},
  526. Label: map[string][]string{
  527. "key1": {"tag3"},
  528. "key2": {"tag2"},
  529. },
  530. },
  531. {
  532. Location: []*profile.Location{cpuL[2]},
  533. Value: []int64{10, 10},
  534. Label: map[string][]string{
  535. "key1": {"tag4"},
  536. "key2": {"tag1"},
  537. },
  538. },
  539. },
  540. Location: cpuL,
  541. Function: cpuF,
  542. Mapping: cpuM,
  543. }
  544. }
  545. func cpuProfileSmall() *profile.Profile {
  546. var cpuM = []*profile.Mapping{
  547. {
  548. ID: 1,
  549. Start: 0x1000,
  550. Limit: 0x4000,
  551. File: "/path/to/testbinary",
  552. HasFunctions: true,
  553. HasFilenames: true,
  554. HasLineNumbers: true,
  555. HasInlineFrames: true,
  556. },
  557. }
  558. var cpuL = []*profile.Location{
  559. {
  560. ID: 1000,
  561. Mapping: cpuM[0],
  562. Address: 0x1000,
  563. },
  564. {
  565. ID: 2000,
  566. Mapping: cpuM[0],
  567. Address: 0x2000,
  568. },
  569. {
  570. ID: 3000,
  571. Mapping: cpuM[0],
  572. Address: 0x3000,
  573. },
  574. {
  575. ID: 4000,
  576. Mapping: cpuM[0],
  577. Address: 0x4000,
  578. },
  579. {
  580. ID: 5000,
  581. Mapping: cpuM[0],
  582. Address: 0x5000,
  583. },
  584. }
  585. return &profile.Profile{
  586. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  587. Period: 1,
  588. DurationNanos: 10e9,
  589. SampleType: []*profile.ValueType{
  590. {Type: "samples", Unit: "count"},
  591. {Type: "cpu", Unit: "milliseconds"},
  592. },
  593. Sample: []*profile.Sample{
  594. {
  595. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  596. Value: []int64{1000, 1000},
  597. },
  598. {
  599. Location: []*profile.Location{cpuL[3], cpuL[1], cpuL[4]},
  600. Value: []int64{1000, 1000},
  601. },
  602. {
  603. Location: []*profile.Location{cpuL[2]},
  604. Value: []int64{1000, 1000},
  605. },
  606. {
  607. Location: []*profile.Location{cpuL[4]},
  608. Value: []int64{1000, 1000},
  609. },
  610. },
  611. Location: cpuL,
  612. Function: nil,
  613. Mapping: cpuM,
  614. }
  615. }
  616. func heapProfile() *profile.Profile {
  617. var heapM = []*profile.Mapping{
  618. {
  619. ID: 1,
  620. BuildID: "buildid",
  621. Start: 0x1000,
  622. Limit: 0x4000,
  623. HasFunctions: true,
  624. HasFilenames: true,
  625. HasLineNumbers: true,
  626. HasInlineFrames: true,
  627. },
  628. }
  629. var heapF = []*profile.Function{
  630. {ID: 1, Name: "pruneme", SystemName: "pruneme", Filename: "prune.h"},
  631. {ID: 2, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  632. {ID: 3, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  633. {ID: 4, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  634. {ID: 5, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  635. {ID: 6, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  636. {ID: 7, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  637. {ID: 8, Name: "mangledMALLOC", SystemName: "mangledMALLOC", Filename: "malloc.h"},
  638. {ID: 9, Name: "mangledNEW", SystemName: "mangledNEW", Filename: "new.h"},
  639. }
  640. var heapL = []*profile.Location{
  641. {
  642. ID: 1000,
  643. Mapping: heapM[0],
  644. Address: 0x1000,
  645. Line: []profile.Line{
  646. {Function: heapF[0], Line: 100},
  647. {Function: heapF[7], Line: 100},
  648. {Function: heapF[1], Line: 1},
  649. },
  650. },
  651. {
  652. ID: 2000,
  653. Mapping: heapM[0],
  654. Address: 0x2000,
  655. Line: []profile.Line{
  656. {Function: heapF[8], Line: 100},
  657. {Function: heapF[3], Line: 2},
  658. {Function: heapF[2], Line: 3},
  659. },
  660. },
  661. {
  662. ID: 3000,
  663. Mapping: heapM[0],
  664. Address: 0x3000,
  665. Line: []profile.Line{
  666. {Function: heapF[8], Line: 100},
  667. {Function: heapF[6], Line: 3},
  668. {Function: heapF[5], Line: 2},
  669. {Function: heapF[4], Line: 4},
  670. },
  671. },
  672. {
  673. ID: 3001,
  674. Mapping: heapM[0],
  675. Address: 0x3001,
  676. Line: []profile.Line{
  677. {Function: heapF[0], Line: 100},
  678. {Function: heapF[8], Line: 100},
  679. {Function: heapF[5], Line: 2},
  680. {Function: heapF[4], Line: 4},
  681. },
  682. },
  683. {
  684. ID: 3002,
  685. Mapping: heapM[0],
  686. Address: 0x3002,
  687. Line: []profile.Line{
  688. {Function: heapF[6], Line: 3},
  689. {Function: heapF[4], Line: 4},
  690. },
  691. },
  692. }
  693. return &profile.Profile{
  694. Comments: []string{"comment", "#hidden comment"},
  695. PeriodType: &profile.ValueType{Type: "allocations", Unit: "bytes"},
  696. Period: 524288,
  697. SampleType: []*profile.ValueType{
  698. {Type: "inuse_objects", Unit: "count"},
  699. {Type: "inuse_space", Unit: "bytes"},
  700. },
  701. Sample: []*profile.Sample{
  702. {
  703. Location: []*profile.Location{heapL[0], heapL[1], heapL[2]},
  704. Value: []int64{10, 1024000},
  705. NumLabel: map[string][]int64{
  706. "bytes": {102400},
  707. },
  708. },
  709. {
  710. Location: []*profile.Location{heapL[0], heapL[3]},
  711. Value: []int64{20, 4096000},
  712. NumLabel: map[string][]int64{
  713. "bytes": {204800},
  714. },
  715. },
  716. {
  717. Location: []*profile.Location{heapL[1], heapL[4]},
  718. Value: []int64{40, 65536000},
  719. NumLabel: map[string][]int64{
  720. "bytes": {1638400},
  721. },
  722. },
  723. {
  724. Location: []*profile.Location{heapL[2]},
  725. Value: []int64{80, 32768000},
  726. NumLabel: map[string][]int64{
  727. "bytes": {409600},
  728. },
  729. },
  730. },
  731. DropFrames: ".*operator new.*|malloc",
  732. Location: heapL,
  733. Function: heapF,
  734. Mapping: heapM,
  735. }
  736. }
  737. func contentionProfile() *profile.Profile {
  738. var contentionM = []*profile.Mapping{
  739. {
  740. ID: 1,
  741. BuildID: "buildid-contention",
  742. Start: 0x1000,
  743. Limit: 0x4000,
  744. HasFunctions: true,
  745. HasFilenames: true,
  746. HasLineNumbers: true,
  747. HasInlineFrames: true,
  748. },
  749. }
  750. var contentionF = []*profile.Function{
  751. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  752. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  753. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  754. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  755. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  756. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  757. }
  758. var contentionL = []*profile.Location{
  759. {
  760. ID: 1000,
  761. Mapping: contentionM[0],
  762. Address: 0x1000,
  763. Line: []profile.Line{
  764. {Function: contentionF[0], Line: 1},
  765. },
  766. },
  767. {
  768. ID: 2000,
  769. Mapping: contentionM[0],
  770. Address: 0x2000,
  771. Line: []profile.Line{
  772. {Function: contentionF[2], Line: 2},
  773. {Function: contentionF[1], Line: 3},
  774. },
  775. },
  776. {
  777. ID: 3000,
  778. Mapping: contentionM[0],
  779. Address: 0x3000,
  780. Line: []profile.Line{
  781. {Function: contentionF[5], Line: 2},
  782. {Function: contentionF[4], Line: 3},
  783. {Function: contentionF[3], Line: 5},
  784. },
  785. },
  786. {
  787. ID: 3001,
  788. Mapping: contentionM[0],
  789. Address: 0x3001,
  790. Line: []profile.Line{
  791. {Function: contentionF[4], Line: 3},
  792. {Function: contentionF[3], Line: 5},
  793. },
  794. },
  795. {
  796. ID: 3002,
  797. Mapping: contentionM[0],
  798. Address: 0x3002,
  799. Line: []profile.Line{
  800. {Function: contentionF[5], Line: 4},
  801. {Function: contentionF[3], Line: 3},
  802. },
  803. },
  804. }
  805. return &profile.Profile{
  806. PeriodType: &profile.ValueType{Type: "contentions", Unit: "count"},
  807. Period: 524288,
  808. SampleType: []*profile.ValueType{
  809. {Type: "contentions", Unit: "count"},
  810. {Type: "delay", Unit: "nanoseconds"},
  811. },
  812. Sample: []*profile.Sample{
  813. {
  814. Location: []*profile.Location{contentionL[0], contentionL[1], contentionL[2]},
  815. Value: []int64{10, 10240000},
  816. },
  817. {
  818. Location: []*profile.Location{contentionL[0], contentionL[3]},
  819. Value: []int64{20, 40960000},
  820. },
  821. {
  822. Location: []*profile.Location{contentionL[1], contentionL[4]},
  823. Value: []int64{40, 65536000},
  824. },
  825. {
  826. Location: []*profile.Location{contentionL[2]},
  827. Value: []int64{80, 32768000},
  828. },
  829. },
  830. Location: contentionL,
  831. Function: contentionF,
  832. Mapping: contentionM,
  833. Comments: []string{"Comment #1", "Comment #2"},
  834. }
  835. }
  836. func symzProfile() *profile.Profile {
  837. var symzM = []*profile.Mapping{
  838. {
  839. ID: 1,
  840. Start: testStart,
  841. Limit: 0x4000,
  842. File: "/path/to/testbinary",
  843. },
  844. }
  845. var symzL = []*profile.Location{
  846. {ID: 1, Mapping: symzM[0], Address: testStart},
  847. {ID: 2, Mapping: symzM[0], Address: testStart + 0x1000},
  848. {ID: 3, Mapping: symzM[0], Address: testStart + 0x2000},
  849. }
  850. return &profile.Profile{
  851. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  852. Period: 1,
  853. DurationNanos: 10e9,
  854. SampleType: []*profile.ValueType{
  855. {Type: "samples", Unit: "count"},
  856. {Type: "cpu", Unit: "milliseconds"},
  857. },
  858. Sample: []*profile.Sample{
  859. {
  860. Location: []*profile.Location{symzL[0], symzL[1], symzL[2]},
  861. Value: []int64{1, 1},
  862. },
  863. },
  864. Location: symzL,
  865. Mapping: symzM,
  866. }
  867. }
  868. var autoCompleteTests = []struct {
  869. in string
  870. out string
  871. }{
  872. {"", ""},
  873. {"xyz", "xyz"}, // no match
  874. {"dis", "disasm"}, // single match
  875. {"t", "t"}, // many matches
  876. {"top abc", "top abc"}, // no function name match
  877. {"top mangledM", "top mangledMALLOC"}, // single function name match
  878. {"top cmd cmd mangledM", "top cmd cmd mangledMALLOC"},
  879. {"top mangled", "top mangled"}, // many function name matches
  880. {"cmd mangledM", "cmd mangledM"}, // invalid command
  881. {"top mangledM cmd", "top mangledM cmd"}, // cursor misplaced
  882. {"top edMA", "top mangledMALLOC"}, // single infix function name match
  883. {"top -mangledM", "top -mangledMALLOC"}, // ignore sign handled
  884. {"lin", "lines"}, // single variable match
  885. {"EdGeF", "edgefraction"}, // single capitalized match
  886. {"help dis", "help disasm"}, // help command match
  887. {"help relative_perc", "help relative_percentages"}, // help variable match
  888. {"help coMpa", "help compact_labels"}, // help variable capitalized match
  889. }
  890. func TestAutoComplete(t *testing.T) {
  891. complete := newCompleter(functionNames(heapProfile()))
  892. for _, test := range autoCompleteTests {
  893. if out := complete(test.in); out != test.out {
  894. t.Errorf("autoComplete(%s) = %s; want %s", test.in, out, test.out)
  895. }
  896. }
  897. }
  898. func TestTagFilter(t *testing.T) {
  899. var tagFilterTests = []struct {
  900. name, value string
  901. tags map[string][]string
  902. want bool
  903. }{
  904. {"test1", "tag2", map[string][]string{"value1": {"tag1", "tag2"}}, true},
  905. {"test2", "tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false},
  906. {"test3", "tag1,tag3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true},
  907. {"test4", "t..[12],t..3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true},
  908. {"test5", "tag2,tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false},
  909. }
  910. for _, test := range tagFilterTests {
  911. filter, err := compileTagFilter(test.name, test.value, &proftest.TestUI{T: t}, nil)
  912. if err != nil {
  913. t.Errorf("tagFilter %s:%v", test.name, err)
  914. continue
  915. }
  916. s := profile.Sample{
  917. Label: test.tags,
  918. }
  919. if got := filter(&s); got != test.want {
  920. t.Errorf("tagFilter %s: got %v, want %v", test.name, got, test.want)
  921. }
  922. }
  923. }
  924. func TestSymbolzAfterMerge(t *testing.T) {
  925. baseVars := pprofVariables
  926. pprofVariables = baseVars.makeCopy()
  927. defer func() { pprofVariables = baseVars }()
  928. f := baseFlags()
  929. f.args = []string{"symbolz", "http://host2/symbolz"}
  930. o := setDefaults(nil)
  931. o.Flagset = f
  932. o.Obj = new(mockObjTool)
  933. src, cmd, err := parseFlags(o)
  934. if err != nil {
  935. t.Fatalf("parseFlags: %v", err)
  936. }
  937. if len(cmd) != 1 || cmd[0] != "proto" {
  938. t.Fatalf("parseFlags returned command %v, want [proto]", cmd)
  939. }
  940. o.Fetch = testFetcher{}
  941. o.Sym = testSymbolzSymbolizer{}
  942. p, err := fetchProfiles(src, o)
  943. if err != nil {
  944. t.Fatalf("fetchProfiles: %v", err)
  945. }
  946. if len(p.Location) != 3 {
  947. t.Errorf("Got %d locations after merge, want %d", len(p.Location), 3)
  948. }
  949. for i, l := range p.Location {
  950. if len(l.Line) != 1 {
  951. t.Errorf("Number of lines for symbolz %#x in iteration %d, got %d, want %d", l.Address, i, len(l.Line), 1)
  952. continue
  953. }
  954. address := l.Address - l.Mapping.Start
  955. if got, want := l.Line[0].Function.Name, fmt.Sprintf("%#x", address); got != want {
  956. t.Errorf("symbolz %#x, got %s, want %s", address, got, want)
  957. }
  958. }
  959. }
  960. func TestHttpsInsecure(t *testing.T) {
  961. baseVars := pprofVariables
  962. pprofVariables = baseVars.makeCopy()
  963. defer func() { pprofVariables = baseVars }()
  964. tlsConfig := &tls.Config{Certificates: []tls.Certificate{selfSignedCert(t)}}
  965. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  966. if err != nil {
  967. t.Fatalf("net.Listen: got error %v, want no error", err)
  968. }
  969. donec := make(chan error, 1)
  970. go func(donec chan<- error) {
  971. donec <- http.Serve(l, nil)
  972. }(donec)
  973. defer func() {
  974. if got, want := <-donec, "use of closed"; !strings.Contains(got.Error(), want) {
  975. t.Fatalf("Serve got error %v, want %q", got, want)
  976. }
  977. }()
  978. defer l.Close()
  979. go func() {
  980. deadline := time.Now().Add(5 * time.Second)
  981. for time.Now().Before(deadline) {
  982. // Simulate a hotspot function.
  983. }
  984. }()
  985. outputTempFile, err := ioutil.TempFile("", "profile_output")
  986. if err != nil {
  987. t.Fatalf("Failed to create tempfile: %v", err)
  988. }
  989. defer os.Remove(outputTempFile.Name())
  990. defer outputTempFile.Close()
  991. f := emptyFlags()
  992. o := setDefaults(nil)
  993. o.Flagset = &f
  994. f.args = []string{"https+insecure://" + l.Addr().String() + "/debug/pprof/profile?seconds=5"}
  995. addFlags(&f, []string{
  996. "top",
  997. "symbolize=remote",
  998. "output=" + outputTempFile.Name(),
  999. })
  1000. if err := PProf(o); err != nil {
  1001. t.Fatalf("PProf(%v): got error %v, want no error", o, err)
  1002. }
  1003. b, err := ioutil.ReadFile(outputTempFile.Name())
  1004. if err != nil {
  1005. t.Fatalf("ReadFile(%s) got error %v, want no error", outputTempFile.Name(), err)
  1006. }
  1007. // TODO(aalexand): Fix to reqiure "TestHttpsInsecure" in the output once #120
  1008. // is fixed which causes symbolization issues on OSX with Go 1.8.
  1009. if got, want := string(b), "Showing nodes accounting"; !strings.Contains(got, want) {
  1010. t.Fatalf("Pprof(%v): got %v, want %q substring", o, got, want)
  1011. }
  1012. }
  1013. func selfSignedCert(t *testing.T) tls.Certificate {
  1014. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1015. if err != nil {
  1016. t.Fatalf("failed to generate private key: %v", err)
  1017. }
  1018. b, err := x509.MarshalECPrivateKey(privKey)
  1019. if err != nil {
  1020. t.Fatalf("failed to marshal private key: %v", err)
  1021. }
  1022. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  1023. tmpl := x509.Certificate{
  1024. SerialNumber: big.NewInt(1),
  1025. NotBefore: time.Now(),
  1026. NotAfter: time.Now().Add(10 * time.Minute),
  1027. }
  1028. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  1029. if err != nil {
  1030. t.Fatalf("failed to create cert: %v", err)
  1031. }
  1032. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  1033. cert, err := tls.X509KeyPair(bc, bk)
  1034. if err != nil {
  1035. t.Fatalf("failed to create TLS key pair: %v", err)
  1036. }
  1037. return cert
  1038. }
  1039. type mockObjTool struct{}
  1040. func (*mockObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  1041. return &mockFile{file, "abcdef", 0}, nil
  1042. }
  1043. func (m *mockObjTool) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  1044. switch start {
  1045. case 0x1000:
  1046. return []plugin.Inst{
  1047. {Addr: 0x1000, Text: "instruction one"},
  1048. {Addr: 0x1001, Text: "instruction two"},
  1049. {Addr: 0x1002, Text: "instruction three"},
  1050. {Addr: 0x1003, Text: "instruction four"},
  1051. }, nil
  1052. case 0x3000:
  1053. return []plugin.Inst{
  1054. {Addr: 0x3000, Text: "instruction one"},
  1055. {Addr: 0x3001, Text: "instruction two"},
  1056. {Addr: 0x3002, Text: "instruction three"},
  1057. {Addr: 0x3003, Text: "instruction four"},
  1058. {Addr: 0x3004, Text: "instruction five"},
  1059. }, nil
  1060. }
  1061. return nil, fmt.Errorf("unimplemented")
  1062. }
  1063. type mockFile struct {
  1064. name, buildID string
  1065. base uint64
  1066. }
  1067. // Name returns the underlyinf file name, if available
  1068. func (m *mockFile) Name() string {
  1069. return m.name
  1070. }
  1071. // Base returns the base address to use when looking up symbols in the file.
  1072. func (m *mockFile) Base() uint64 {
  1073. return m.base
  1074. }
  1075. // BuildID returns the GNU build ID of the file, or an empty string.
  1076. func (m *mockFile) BuildID() string {
  1077. return m.buildID
  1078. }
  1079. // SourceLine reports the source line information for a given
  1080. // address in the file. Due to inlining, the source line information
  1081. // is in general a list of positions representing a call stack,
  1082. // with the leaf function first.
  1083. func (*mockFile) SourceLine(addr uint64) ([]plugin.Frame, error) {
  1084. return nil, fmt.Errorf("unimplemented")
  1085. }
  1086. // Symbols returns a list of symbols in the object file.
  1087. // If r is not nil, Symbols restricts the list to symbols
  1088. // with names matching the regular expression.
  1089. // If addr is not zero, Symbols restricts the list to symbols
  1090. // containing that address.
  1091. func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  1092. switch r.String() {
  1093. case "line[13]":
  1094. return []*plugin.Sym{
  1095. {[]string{"line1000"}, m.name, 0x1000, 0x1003},
  1096. {[]string{"line3000"}, m.name, 0x3000, 0x3004},
  1097. }, nil
  1098. }
  1099. return nil, fmt.Errorf("unimplemented")
  1100. }
  1101. // Close closes the file, releasing associated resources.
  1102. func (*mockFile) Close() error {
  1103. return nil
  1104. }