暫無描述

driver_test.go 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package driver
  15. import (
  16. "bytes"
  17. "flag"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. _ "net/http/pprof"
  22. "os"
  23. "reflect"
  24. "regexp"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "testing"
  29. "time"
  30. "github.com/google/pprof/internal/plugin"
  31. "github.com/google/pprof/internal/proftest"
  32. "github.com/google/pprof/internal/symbolz"
  33. "github.com/google/pprof/profile"
  34. )
  35. var updateFlag = flag.Bool("update", false, "Update the golden files")
  36. func TestParse(t *testing.T) {
  37. // Override weblist command to collect output in buffer
  38. pprofCommands["weblist"].postProcess = nil
  39. // Our mockObjTool.Open will always return success, causing
  40. // driver.locateBinaries to "find" the binaries below in a non-existent
  41. // directory. As a workaround, point the search path to the fake
  42. // directory containing out fake binaries.
  43. savePath := os.Getenv("PPROF_BINARY_PATH")
  44. os.Setenv("PPROF_BINARY_PATH", "/path/to")
  45. defer os.Setenv("PPROF_BINARY_PATH", savePath)
  46. testcase := []struct {
  47. flags, source string
  48. }{
  49. {"text,functions,flat", "cpu"},
  50. {"tree,addresses,flat,nodecount=4", "cpusmall"},
  51. {"text,functions,flat,nodecount=5,call_tree", "unknown"},
  52. {"text,alloc_objects,flat", "heap_alloc"},
  53. {"text,files,flat", "heap"},
  54. {"text,files,flat,focus=[12]00,taghide=[X3]00", "heap"},
  55. {"text,inuse_objects,flat", "heap"},
  56. {"text,lines,cum,hide=line[X3]0", "cpu"},
  57. {"text,lines,cum,show=[12]00", "cpu"},
  58. {"text,lines,cum,hide=line[X3]0,focus=[12]00", "cpu"},
  59. {"topproto,lines,cum,hide=mangled[X3]0", "cpu"},
  60. {"topproto,lines", "cpu"},
  61. {"tree,lines,cum,focus=[24]00", "heap"},
  62. {"tree,relative_percentages,cum,focus=[24]00", "heap"},
  63. {"tree,lines,cum,show_from=line2", "cpu"},
  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,unit=minimum", "heap_sizetags"},
  71. {"dot,addresses,flat,ignore=[X3]002,focus=[X1]000", "contention"},
  72. {"dot,files,cum", "contention"},
  73. {"comments,add_comment=some-comment", "cpu"},
  74. {"comments", "heap"},
  75. {"tags", "cpu"},
  76. {"tags,tagignore=tag[13],tagfocus=key[12]", "cpu"},
  77. {"tags", "heap"},
  78. {"tags,unit=bytes", "heap"},
  79. {"traces", "cpu"},
  80. {"traces", "heap_tags"},
  81. {"dot,alloc_space,flat,focus=[234]00", "heap_alloc"},
  82. {"dot,alloc_space,flat,tagshow=[2]00", "heap_alloc"},
  83. {"dot,alloc_space,flat,hide=line.*1?23?", "heap_alloc"},
  84. {"dot,inuse_space,flat,tagfocus=1mb:2gb", "heap"},
  85. {"dot,inuse_space,flat,tagfocus=30kb:,tagignore=1mb:2mb", "heap"},
  86. {"disasm=line[13],addresses,flat", "cpu"},
  87. {"peek=line.*01", "cpu"},
  88. {"weblist=line[13],addresses,flat", "cpu"},
  89. {"tags,tagfocus=400kb:", "heap_request"},
  90. }
  91. baseVars := pprofVariables
  92. defer func() { pprofVariables = baseVars }()
  93. for _, tc := range testcase {
  94. t.Run(tc.flags+":"+tc.source, func(t *testing.T) {
  95. // Reset the pprof variables before processing
  96. pprofVariables = baseVars.makeCopy()
  97. testUI := &proftest.TestUI{T: t, AllowRx: "Generating report in|Ignoring local file|expression matched no samples|Interpreted .* as range, not regexp"}
  98. f := baseFlags()
  99. f.args = []string{tc.source}
  100. flags := strings.Split(tc.flags, ",")
  101. // Encode profile into a protobuf and decode it again.
  102. protoTempFile, err := ioutil.TempFile("", "profile_proto")
  103. if err != nil {
  104. t.Errorf("cannot create tempfile: %v", err)
  105. }
  106. defer os.Remove(protoTempFile.Name())
  107. defer protoTempFile.Close()
  108. f.strings["output"] = protoTempFile.Name()
  109. if flags[0] == "topproto" {
  110. f.bools["proto"] = false
  111. f.bools["topproto"] = true
  112. f.bools["addresses"] = true
  113. }
  114. // First pprof invocation to save the profile into a profile.proto.
  115. o1 := setDefaults(nil)
  116. o1.Flagset = f
  117. o1.Fetch = testFetcher{}
  118. o1.Sym = testSymbolizer{}
  119. o1.UI = testUI
  120. if err := PProf(o1); err != nil {
  121. t.Fatalf("%s %q: %v", tc.source, tc.flags, err)
  122. }
  123. // Reset the pprof variables after the proto invocation
  124. pprofVariables = baseVars.makeCopy()
  125. // Read the profile from the encoded protobuf
  126. outputTempFile, err := ioutil.TempFile("", "profile_output")
  127. if err != nil {
  128. t.Errorf("cannot create tempfile: %v", err)
  129. }
  130. defer os.Remove(outputTempFile.Name())
  131. defer outputTempFile.Close()
  132. f = baseFlags()
  133. f.strings["output"] = outputTempFile.Name()
  134. f.args = []string{protoTempFile.Name()}
  135. delete(f.bools, "proto")
  136. addFlags(&f, flags)
  137. solution := solutionFilename(tc.source, &f)
  138. // Apply the flags for the second pprof run, and identify name of
  139. // the file containing expected results
  140. if flags[0] == "topproto" {
  141. addFlags(&f, flags)
  142. solution = solutionFilename(tc.source, &f)
  143. delete(f.bools, "topproto")
  144. f.bools["text"] = true
  145. }
  146. // Second pprof invocation to read the profile from profile.proto
  147. // and generate a report.
  148. o2 := setDefaults(nil)
  149. o2.Flagset = f
  150. o2.Sym = testSymbolizeDemangler{}
  151. o2.Obj = new(mockObjTool)
  152. o2.UI = testUI
  153. if err := PProf(o2); err != nil {
  154. t.Errorf("%s: %v", tc.source, err)
  155. }
  156. b, err := ioutil.ReadFile(outputTempFile.Name())
  157. if err != nil {
  158. t.Errorf("Failed to read profile %s: %v", outputTempFile.Name(), err)
  159. }
  160. // Read data file with expected solution
  161. solution = "testdata/" + solution
  162. sbuf, err := ioutil.ReadFile(solution)
  163. if err != nil {
  164. t.Fatalf("reading solution file %s: %v", solution, err)
  165. }
  166. if runtime.GOOS == "windows" {
  167. sbuf = bytes.Replace(sbuf, []byte("testdata/"), []byte("testdata\\"), -1)
  168. sbuf = bytes.Replace(sbuf, []byte("/path/to/"), []byte("\\path\\to\\"), -1)
  169. }
  170. if flags[0] == "svg" {
  171. b = removeScripts(b)
  172. sbuf = removeScripts(sbuf)
  173. }
  174. if string(b) != string(sbuf) {
  175. t.Errorf("diff %s %s", solution, tc.source)
  176. d, err := proftest.Diff(sbuf, b)
  177. if err != nil {
  178. t.Fatalf("diff %s %v", solution, err)
  179. }
  180. t.Errorf("%s\n%s\n", solution, d)
  181. if *updateFlag {
  182. err := ioutil.WriteFile(solution, b, 0644)
  183. if err != nil {
  184. t.Errorf("failed to update the solution file %q: %v", solution, err)
  185. }
  186. }
  187. }
  188. })
  189. }
  190. }
  191. // removeScripts removes <script > .. </script> pairs from its input
  192. func removeScripts(in []byte) []byte {
  193. beginMarker := []byte("<script")
  194. endMarker := []byte("</script>")
  195. if begin := bytes.Index(in, beginMarker); begin > 0 {
  196. if end := bytes.Index(in[begin:], endMarker); end > 0 {
  197. in = append(in[:begin], removeScripts(in[begin+end+len(endMarker):])...)
  198. }
  199. }
  200. return in
  201. }
  202. // addFlags parses flag descriptions and adds them to the testFlags
  203. func addFlags(f *testFlags, flags []string) {
  204. for _, flag := range flags {
  205. fields := strings.SplitN(flag, "=", 2)
  206. switch len(fields) {
  207. case 1:
  208. f.bools[fields[0]] = true
  209. case 2:
  210. if i, err := strconv.Atoi(fields[1]); err == nil {
  211. f.ints[fields[0]] = i
  212. } else {
  213. f.strings[fields[0]] = fields[1]
  214. }
  215. }
  216. }
  217. }
  218. func testSourceURL(port int) string {
  219. return fmt.Sprintf("http://%s/", net.JoinHostPort(testSourceAddress, strconv.Itoa(port)))
  220. }
  221. // solutionFilename returns the name of the solution file for the test
  222. func solutionFilename(source string, f *testFlags) string {
  223. name := []string{"pprof", strings.TrimPrefix(source, testSourceURL(8000))}
  224. name = addString(name, f, []string{"flat", "cum"})
  225. name = addString(name, f, []string{"functions", "files", "lines", "addresses"})
  226. name = addString(name, f, []string{"inuse_space", "inuse_objects", "alloc_space", "alloc_objects"})
  227. name = addString(name, f, []string{"relative_percentages"})
  228. name = addString(name, f, []string{"seconds"})
  229. name = addString(name, f, []string{"call_tree"})
  230. name = addString(name, f, []string{"text", "tree", "callgrind", "dot", "svg", "tags", "dot", "traces", "disasm", "peek", "weblist", "topproto", "comments"})
  231. if f.strings["focus"] != "" || f.strings["tagfocus"] != "" {
  232. name = append(name, "focus")
  233. }
  234. if f.strings["ignore"] != "" || f.strings["tagignore"] != "" {
  235. name = append(name, "ignore")
  236. }
  237. if f.strings["show_from"] != "" {
  238. name = append(name, "show_from")
  239. }
  240. name = addString(name, f, []string{"hide", "show"})
  241. if f.strings["unit"] != "minimum" {
  242. name = addString(name, f, []string{"unit"})
  243. }
  244. return strings.Join(name, ".")
  245. }
  246. func addString(name []string, f *testFlags, components []string) []string {
  247. for _, c := range components {
  248. if f.bools[c] || f.strings[c] != "" || f.ints[c] != 0 {
  249. return append(name, c)
  250. }
  251. }
  252. return name
  253. }
  254. // testFlags implements the plugin.FlagSet interface.
  255. type testFlags struct {
  256. bools map[string]bool
  257. ints map[string]int
  258. floats map[string]float64
  259. strings map[string]string
  260. args []string
  261. stringLists map[string][]string
  262. }
  263. func (testFlags) ExtraUsage() string { return "" }
  264. func (f testFlags) Bool(s string, d bool, c string) *bool {
  265. if b, ok := f.bools[s]; ok {
  266. return &b
  267. }
  268. return &d
  269. }
  270. func (f testFlags) Int(s string, d int, c string) *int {
  271. if i, ok := f.ints[s]; ok {
  272. return &i
  273. }
  274. return &d
  275. }
  276. func (f testFlags) Float64(s string, d float64, c string) *float64 {
  277. if g, ok := f.floats[s]; ok {
  278. return &g
  279. }
  280. return &d
  281. }
  282. func (f testFlags) String(s, d, c string) *string {
  283. if t, ok := f.strings[s]; ok {
  284. return &t
  285. }
  286. return &d
  287. }
  288. func (f testFlags) BoolVar(p *bool, s string, d bool, c string) {
  289. if b, ok := f.bools[s]; ok {
  290. *p = b
  291. } else {
  292. *p = d
  293. }
  294. }
  295. func (f testFlags) IntVar(p *int, s string, d int, c string) {
  296. if i, ok := f.ints[s]; ok {
  297. *p = i
  298. } else {
  299. *p = d
  300. }
  301. }
  302. func (f testFlags) Float64Var(p *float64, s string, d float64, c string) {
  303. if g, ok := f.floats[s]; ok {
  304. *p = g
  305. } else {
  306. *p = d
  307. }
  308. }
  309. func (f testFlags) StringVar(p *string, s, d, c string) {
  310. if t, ok := f.strings[s]; ok {
  311. *p = t
  312. } else {
  313. *p = d
  314. }
  315. }
  316. func (f testFlags) StringList(s, d, c string) *[]*string {
  317. if t, ok := f.stringLists[s]; ok {
  318. // convert slice of strings to slice of string pointers before returning.
  319. tp := make([]*string, len(t))
  320. for i, v := range t {
  321. tp[i] = &v
  322. }
  323. return &tp
  324. }
  325. return &[]*string{}
  326. }
  327. func (f testFlags) Parse(func()) []string {
  328. return f.args
  329. }
  330. func baseFlags() testFlags {
  331. return testFlags{
  332. bools: map[string]bool{
  333. "proto": true,
  334. "trim": true,
  335. "compact_labels": true,
  336. },
  337. ints: map[string]int{
  338. "nodecount": 20,
  339. },
  340. floats: map[string]float64{
  341. "nodefraction": 0.05,
  342. "edgefraction": 0.01,
  343. "divide_by": 1.0,
  344. },
  345. strings: map[string]string{
  346. "unit": "minimum",
  347. },
  348. }
  349. }
  350. const testStart = 0x1000
  351. const testOffset = 0x5000
  352. type testFetcher struct{}
  353. func (testFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) {
  354. var p *profile.Profile
  355. switch s {
  356. case "cpu", "unknown":
  357. p = cpuProfile()
  358. case "cpusmall":
  359. p = cpuProfileSmall()
  360. case "heap":
  361. p = heapProfile()
  362. case "heap_alloc":
  363. p = heapProfile()
  364. p.SampleType = []*profile.ValueType{
  365. {Type: "alloc_objects", Unit: "count"},
  366. {Type: "alloc_space", Unit: "bytes"},
  367. }
  368. case "heap_request":
  369. p = heapProfile()
  370. for _, s := range p.Sample {
  371. s.NumLabel["request"] = s.NumLabel["bytes"]
  372. }
  373. case "heap_sizetags":
  374. p = heapProfile()
  375. tags := []int64{2, 4, 8, 16, 32, 64, 128, 256}
  376. for _, s := range p.Sample {
  377. numValues := append(s.NumLabel["bytes"], tags...)
  378. s.NumLabel["bytes"] = numValues
  379. }
  380. case "heap_tags":
  381. p = heapProfile()
  382. for i := 0; i < len(p.Sample); i += 2 {
  383. s := p.Sample[i]
  384. if s.Label == nil {
  385. s.Label = make(map[string][]string)
  386. }
  387. s.NumLabel["request"] = s.NumLabel["bytes"]
  388. s.Label["key1"] = []string{"tag"}
  389. }
  390. case "contention":
  391. p = contentionProfile()
  392. case "symbolz":
  393. p = symzProfile()
  394. default:
  395. return nil, "", fmt.Errorf("unexpected source: %s", s)
  396. }
  397. return p, testSourceURL(8000) + s, nil
  398. }
  399. type testSymbolizer struct{}
  400. func (testSymbolizer) Symbolize(_ string, _ plugin.MappingSources, _ *profile.Profile) error {
  401. return nil
  402. }
  403. type testSymbolizeDemangler struct{}
  404. func (testSymbolizeDemangler) Symbolize(_ string, _ plugin.MappingSources, p *profile.Profile) error {
  405. for _, fn := range p.Function {
  406. if fn.Name == "" || fn.SystemName == fn.Name {
  407. fn.Name = fakeDemangler(fn.SystemName)
  408. }
  409. }
  410. return nil
  411. }
  412. func testFetchSymbols(source, post string) ([]byte, error) {
  413. var buf bytes.Buffer
  414. switch source {
  415. case testSourceURL(8000) + "symbolz":
  416. for _, address := range strings.Split(post, "+") {
  417. a, _ := strconv.ParseInt(address, 0, 64)
  418. fmt.Fprintf(&buf, "%v\t", address)
  419. if a-testStart > testOffset {
  420. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  421. continue
  422. }
  423. fmt.Fprintf(&buf, "%#x\n", a-testStart)
  424. }
  425. return buf.Bytes(), nil
  426. case testSourceURL(8001) + "symbolz":
  427. for _, address := range strings.Split(post, "+") {
  428. a, _ := strconv.ParseInt(address, 0, 64)
  429. fmt.Fprintf(&buf, "%v\t", address)
  430. if a-testStart < testOffset {
  431. fmt.Fprintf(&buf, "wrong_source_%v_", address)
  432. continue
  433. }
  434. fmt.Fprintf(&buf, "%#x\n", a-testStart-testOffset)
  435. }
  436. return buf.Bytes(), nil
  437. default:
  438. return nil, fmt.Errorf("unexpected source: %s", source)
  439. }
  440. }
  441. type testSymbolzSymbolizer struct{}
  442. func (testSymbolzSymbolizer) Symbolize(variables string, sources plugin.MappingSources, p *profile.Profile) error {
  443. return symbolz.Symbolize(p, false, sources, testFetchSymbols, nil)
  444. }
  445. func fakeDemangler(name string) string {
  446. switch name {
  447. case "mangled1000":
  448. return "line1000"
  449. case "mangled2000":
  450. return "line2000"
  451. case "mangled2001":
  452. return "line2001"
  453. case "mangled3000":
  454. return "line3000"
  455. case "mangled3001":
  456. return "line3001"
  457. case "mangled3002":
  458. return "line3002"
  459. case "mangledNEW":
  460. return "operator new"
  461. case "mangledMALLOC":
  462. return "malloc"
  463. default:
  464. return name
  465. }
  466. }
  467. func cpuProfile() *profile.Profile {
  468. var cpuM = []*profile.Mapping{
  469. {
  470. ID: 1,
  471. Start: 0x1000,
  472. Limit: 0x4000,
  473. File: "/path/to/testbinary",
  474. HasFunctions: true,
  475. HasFilenames: true,
  476. HasLineNumbers: true,
  477. HasInlineFrames: true,
  478. },
  479. }
  480. var cpuF = []*profile.Function{
  481. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  482. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  483. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  484. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  485. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  486. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  487. }
  488. var cpuL = []*profile.Location{
  489. {
  490. ID: 1000,
  491. Mapping: cpuM[0],
  492. Address: 0x1000,
  493. Line: []profile.Line{
  494. {Function: cpuF[0], Line: 1},
  495. },
  496. },
  497. {
  498. ID: 2000,
  499. Mapping: cpuM[0],
  500. Address: 0x2000,
  501. Line: []profile.Line{
  502. {Function: cpuF[2], Line: 9},
  503. {Function: cpuF[1], Line: 4},
  504. },
  505. },
  506. {
  507. ID: 3000,
  508. Mapping: cpuM[0],
  509. Address: 0x3000,
  510. Line: []profile.Line{
  511. {Function: cpuF[5], Line: 2},
  512. {Function: cpuF[4], Line: 5},
  513. {Function: cpuF[3], Line: 6},
  514. },
  515. },
  516. {
  517. ID: 3001,
  518. Mapping: cpuM[0],
  519. Address: 0x3001,
  520. Line: []profile.Line{
  521. {Function: cpuF[4], Line: 8},
  522. {Function: cpuF[3], Line: 9},
  523. },
  524. },
  525. {
  526. ID: 3002,
  527. Mapping: cpuM[0],
  528. Address: 0x3002,
  529. Line: []profile.Line{
  530. {Function: cpuF[5], Line: 5},
  531. {Function: cpuF[3], Line: 9},
  532. },
  533. },
  534. }
  535. return &profile.Profile{
  536. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  537. Period: 1,
  538. DurationNanos: 10e9,
  539. SampleType: []*profile.ValueType{
  540. {Type: "samples", Unit: "count"},
  541. {Type: "cpu", Unit: "milliseconds"},
  542. },
  543. Sample: []*profile.Sample{
  544. {
  545. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  546. Value: []int64{1000, 1000},
  547. Label: map[string][]string{
  548. "key1": {"tag1"},
  549. "key2": {"tag1"},
  550. },
  551. },
  552. {
  553. Location: []*profile.Location{cpuL[0], cpuL[3]},
  554. Value: []int64{100, 100},
  555. Label: map[string][]string{
  556. "key1": {"tag2"},
  557. "key3": {"tag2"},
  558. },
  559. },
  560. {
  561. Location: []*profile.Location{cpuL[1], cpuL[4]},
  562. Value: []int64{10, 10},
  563. Label: map[string][]string{
  564. "key1": {"tag3"},
  565. "key2": {"tag2"},
  566. },
  567. },
  568. {
  569. Location: []*profile.Location{cpuL[2]},
  570. Value: []int64{10, 10},
  571. Label: map[string][]string{
  572. "key1": {"tag4"},
  573. "key2": {"tag1"},
  574. },
  575. },
  576. },
  577. Location: cpuL,
  578. Function: cpuF,
  579. Mapping: cpuM,
  580. }
  581. }
  582. func cpuProfileSmall() *profile.Profile {
  583. var cpuM = []*profile.Mapping{
  584. {
  585. ID: 1,
  586. Start: 0x1000,
  587. Limit: 0x4000,
  588. File: "/path/to/testbinary",
  589. HasFunctions: true,
  590. HasFilenames: true,
  591. HasLineNumbers: true,
  592. HasInlineFrames: true,
  593. },
  594. }
  595. var cpuL = []*profile.Location{
  596. {
  597. ID: 1000,
  598. Mapping: cpuM[0],
  599. Address: 0x1000,
  600. },
  601. {
  602. ID: 2000,
  603. Mapping: cpuM[0],
  604. Address: 0x2000,
  605. },
  606. {
  607. ID: 3000,
  608. Mapping: cpuM[0],
  609. Address: 0x3000,
  610. },
  611. {
  612. ID: 4000,
  613. Mapping: cpuM[0],
  614. Address: 0x4000,
  615. },
  616. {
  617. ID: 5000,
  618. Mapping: cpuM[0],
  619. Address: 0x5000,
  620. },
  621. }
  622. return &profile.Profile{
  623. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  624. Period: 1,
  625. DurationNanos: 10e9,
  626. SampleType: []*profile.ValueType{
  627. {Type: "samples", Unit: "count"},
  628. {Type: "cpu", Unit: "milliseconds"},
  629. },
  630. Sample: []*profile.Sample{
  631. {
  632. Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]},
  633. Value: []int64{1000, 1000},
  634. },
  635. {
  636. Location: []*profile.Location{cpuL[3], cpuL[1], cpuL[4]},
  637. Value: []int64{1000, 1000},
  638. },
  639. {
  640. Location: []*profile.Location{cpuL[2]},
  641. Value: []int64{1000, 1000},
  642. },
  643. {
  644. Location: []*profile.Location{cpuL[4]},
  645. Value: []int64{1000, 1000},
  646. },
  647. },
  648. Location: cpuL,
  649. Function: nil,
  650. Mapping: cpuM,
  651. }
  652. }
  653. func heapProfile() *profile.Profile {
  654. var heapM = []*profile.Mapping{
  655. {
  656. ID: 1,
  657. BuildID: "buildid",
  658. Start: 0x1000,
  659. Limit: 0x4000,
  660. HasFunctions: true,
  661. HasFilenames: true,
  662. HasLineNumbers: true,
  663. HasInlineFrames: true,
  664. },
  665. }
  666. var heapF = []*profile.Function{
  667. {ID: 1, Name: "pruneme", SystemName: "pruneme", Filename: "prune.h"},
  668. {ID: 2, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  669. {ID: 3, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  670. {ID: 4, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  671. {ID: 5, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  672. {ID: 6, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  673. {ID: 7, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  674. {ID: 8, Name: "mangledMALLOC", SystemName: "mangledMALLOC", Filename: "malloc.h"},
  675. {ID: 9, Name: "mangledNEW", SystemName: "mangledNEW", Filename: "new.h"},
  676. }
  677. var heapL = []*profile.Location{
  678. {
  679. ID: 1000,
  680. Mapping: heapM[0],
  681. Address: 0x1000,
  682. Line: []profile.Line{
  683. {Function: heapF[0], Line: 100},
  684. {Function: heapF[7], Line: 100},
  685. {Function: heapF[1], Line: 1},
  686. },
  687. },
  688. {
  689. ID: 2000,
  690. Mapping: heapM[0],
  691. Address: 0x2000,
  692. Line: []profile.Line{
  693. {Function: heapF[8], Line: 100},
  694. {Function: heapF[3], Line: 2},
  695. {Function: heapF[2], Line: 3},
  696. },
  697. },
  698. {
  699. ID: 3000,
  700. Mapping: heapM[0],
  701. Address: 0x3000,
  702. Line: []profile.Line{
  703. {Function: heapF[8], Line: 100},
  704. {Function: heapF[6], Line: 3},
  705. {Function: heapF[5], Line: 2},
  706. {Function: heapF[4], Line: 4},
  707. },
  708. },
  709. {
  710. ID: 3001,
  711. Mapping: heapM[0],
  712. Address: 0x3001,
  713. Line: []profile.Line{
  714. {Function: heapF[0], Line: 100},
  715. {Function: heapF[8], Line: 100},
  716. {Function: heapF[5], Line: 2},
  717. {Function: heapF[4], Line: 4},
  718. },
  719. },
  720. {
  721. ID: 3002,
  722. Mapping: heapM[0],
  723. Address: 0x3002,
  724. Line: []profile.Line{
  725. {Function: heapF[6], Line: 3},
  726. {Function: heapF[4], Line: 4},
  727. },
  728. },
  729. }
  730. return &profile.Profile{
  731. Comments: []string{"comment", "#hidden comment"},
  732. PeriodType: &profile.ValueType{Type: "allocations", Unit: "bytes"},
  733. Period: 524288,
  734. SampleType: []*profile.ValueType{
  735. {Type: "inuse_objects", Unit: "count"},
  736. {Type: "inuse_space", Unit: "bytes"},
  737. },
  738. Sample: []*profile.Sample{
  739. {
  740. Location: []*profile.Location{heapL[0], heapL[1], heapL[2]},
  741. Value: []int64{10, 1024000},
  742. NumLabel: map[string][]int64{"bytes": {102400}},
  743. },
  744. {
  745. Location: []*profile.Location{heapL[0], heapL[3]},
  746. Value: []int64{20, 4096000},
  747. NumLabel: map[string][]int64{"bytes": {204800}},
  748. },
  749. {
  750. Location: []*profile.Location{heapL[1], heapL[4]},
  751. Value: []int64{40, 65536000},
  752. NumLabel: map[string][]int64{"bytes": {1638400}},
  753. },
  754. {
  755. Location: []*profile.Location{heapL[2]},
  756. Value: []int64{80, 32768000},
  757. NumLabel: map[string][]int64{"bytes": {409600}},
  758. },
  759. },
  760. DropFrames: ".*operator new.*|malloc",
  761. Location: heapL,
  762. Function: heapF,
  763. Mapping: heapM,
  764. }
  765. }
  766. func contentionProfile() *profile.Profile {
  767. var contentionM = []*profile.Mapping{
  768. {
  769. ID: 1,
  770. BuildID: "buildid-contention",
  771. Start: 0x1000,
  772. Limit: 0x4000,
  773. HasFunctions: true,
  774. HasFilenames: true,
  775. HasLineNumbers: true,
  776. HasInlineFrames: true,
  777. },
  778. }
  779. var contentionF = []*profile.Function{
  780. {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"},
  781. {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"},
  782. {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"},
  783. {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"},
  784. {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"},
  785. {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"},
  786. }
  787. var contentionL = []*profile.Location{
  788. {
  789. ID: 1000,
  790. Mapping: contentionM[0],
  791. Address: 0x1000,
  792. Line: []profile.Line{
  793. {Function: contentionF[0], Line: 1},
  794. },
  795. },
  796. {
  797. ID: 2000,
  798. Mapping: contentionM[0],
  799. Address: 0x2000,
  800. Line: []profile.Line{
  801. {Function: contentionF[2], Line: 2},
  802. {Function: contentionF[1], Line: 3},
  803. },
  804. },
  805. {
  806. ID: 3000,
  807. Mapping: contentionM[0],
  808. Address: 0x3000,
  809. Line: []profile.Line{
  810. {Function: contentionF[5], Line: 2},
  811. {Function: contentionF[4], Line: 3},
  812. {Function: contentionF[3], Line: 5},
  813. },
  814. },
  815. {
  816. ID: 3001,
  817. Mapping: contentionM[0],
  818. Address: 0x3001,
  819. Line: []profile.Line{
  820. {Function: contentionF[4], Line: 3},
  821. {Function: contentionF[3], Line: 5},
  822. },
  823. },
  824. {
  825. ID: 3002,
  826. Mapping: contentionM[0],
  827. Address: 0x3002,
  828. Line: []profile.Line{
  829. {Function: contentionF[5], Line: 4},
  830. {Function: contentionF[3], Line: 3},
  831. },
  832. },
  833. }
  834. return &profile.Profile{
  835. PeriodType: &profile.ValueType{Type: "contentions", Unit: "count"},
  836. Period: 524288,
  837. SampleType: []*profile.ValueType{
  838. {Type: "contentions", Unit: "count"},
  839. {Type: "delay", Unit: "nanoseconds"},
  840. },
  841. Sample: []*profile.Sample{
  842. {
  843. Location: []*profile.Location{contentionL[0], contentionL[1], contentionL[2]},
  844. Value: []int64{10, 10240000},
  845. },
  846. {
  847. Location: []*profile.Location{contentionL[0], contentionL[3]},
  848. Value: []int64{20, 40960000},
  849. },
  850. {
  851. Location: []*profile.Location{contentionL[1], contentionL[4]},
  852. Value: []int64{40, 65536000},
  853. },
  854. {
  855. Location: []*profile.Location{contentionL[2]},
  856. Value: []int64{80, 32768000},
  857. },
  858. },
  859. Location: contentionL,
  860. Function: contentionF,
  861. Mapping: contentionM,
  862. Comments: []string{"Comment #1", "Comment #2"},
  863. }
  864. }
  865. func symzProfile() *profile.Profile {
  866. var symzM = []*profile.Mapping{
  867. {
  868. ID: 1,
  869. Start: testStart,
  870. Limit: 0x4000,
  871. File: "/path/to/testbinary",
  872. },
  873. }
  874. var symzL = []*profile.Location{
  875. {ID: 1, Mapping: symzM[0], Address: testStart},
  876. {ID: 2, Mapping: symzM[0], Address: testStart + 0x1000},
  877. {ID: 3, Mapping: symzM[0], Address: testStart + 0x2000},
  878. }
  879. return &profile.Profile{
  880. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  881. Period: 1,
  882. DurationNanos: 10e9,
  883. SampleType: []*profile.ValueType{
  884. {Type: "samples", Unit: "count"},
  885. {Type: "cpu", Unit: "milliseconds"},
  886. },
  887. Sample: []*profile.Sample{
  888. {
  889. Location: []*profile.Location{symzL[0], symzL[1], symzL[2]},
  890. Value: []int64{1, 1},
  891. },
  892. },
  893. Location: symzL,
  894. Mapping: symzM,
  895. }
  896. }
  897. var autoCompleteTests = []struct {
  898. in string
  899. out string
  900. }{
  901. {"", ""},
  902. {"xyz", "xyz"}, // no match
  903. {"dis", "disasm"}, // single match
  904. {"t", "t"}, // many matches
  905. {"top abc", "top abc"}, // no function name match
  906. {"top mangledM", "top mangledMALLOC"}, // single function name match
  907. {"top cmd cmd mangledM", "top cmd cmd mangledMALLOC"},
  908. {"top mangled", "top mangled"}, // many function name matches
  909. {"cmd mangledM", "cmd mangledM"}, // invalid command
  910. {"top mangledM cmd", "top mangledM cmd"}, // cursor misplaced
  911. {"top edMA", "top mangledMALLOC"}, // single infix function name match
  912. {"top -mangledM", "top -mangledMALLOC"}, // ignore sign handled
  913. {"lin", "lines"}, // single variable match
  914. {"EdGeF", "edgefraction"}, // single capitalized match
  915. {"help dis", "help disasm"}, // help command match
  916. {"help relative_perc", "help relative_percentages"}, // help variable match
  917. {"help coMpa", "help compact_labels"}, // help variable capitalized match
  918. }
  919. func TestAutoComplete(t *testing.T) {
  920. complete := newCompleter(functionNames(heapProfile()))
  921. for _, test := range autoCompleteTests {
  922. if out := complete(test.in); out != test.out {
  923. t.Errorf("autoComplete(%s) = %s; want %s", test.in, out, test.out)
  924. }
  925. }
  926. }
  927. func TestTagFilter(t *testing.T) {
  928. var tagFilterTests = []struct {
  929. desc, value string
  930. tags map[string][]string
  931. want bool
  932. }{
  933. {
  934. "1 key with 1 matching value",
  935. "tag2",
  936. map[string][]string{"value1": {"tag1", "tag2"}},
  937. true,
  938. },
  939. {
  940. "1 key with no matching values",
  941. "tag3",
  942. map[string][]string{"value1": {"tag1", "tag2"}},
  943. false,
  944. },
  945. {
  946. "two keys, each with value matching different one value in list",
  947. "tag1,tag3",
  948. map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}},
  949. true,
  950. },
  951. {"two keys, all value matching different regex value in list",
  952. "t..[12],t..3",
  953. map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}},
  954. true,
  955. },
  956. {
  957. "one key, not all values in list matched",
  958. "tag2,tag3",
  959. map[string][]string{"value1": {"tag1", "tag2"}},
  960. false,
  961. },
  962. {
  963. "key specified, list of tags where all tags in list matched",
  964. "key1=tag1,tag2",
  965. map[string][]string{"key1": {"tag1", "tag2"}},
  966. true,
  967. },
  968. {"key specified, list of tag values where not all are matched",
  969. "key1=tag1,tag2",
  970. map[string][]string{"key1": {"tag1"}},
  971. true,
  972. },
  973. {
  974. "key included for regex matching, list of values where all values in list matched",
  975. "key1:tag1,tag2",
  976. map[string][]string{"key1": {"tag1", "tag2"}},
  977. true,
  978. },
  979. {
  980. "key included for regex matching, list of values where not only second value matched",
  981. "key1:tag1,tag2",
  982. map[string][]string{"key1": {"tag2"}},
  983. false,
  984. },
  985. {
  986. "key included for regex matching, list of values where not only first value matched",
  987. "key1:tag1,tag2",
  988. map[string][]string{"key1": {"tag1"}},
  989. false,
  990. },
  991. }
  992. for _, test := range tagFilterTests {
  993. t.Run(test.desc, func(*testing.T) {
  994. filter, err := compileTagFilter(test.desc, test.value, nil, &proftest.TestUI{T: t}, nil)
  995. if err != nil {
  996. t.Fatalf("tagFilter %s:%v", test.desc, err)
  997. }
  998. s := profile.Sample{
  999. Label: test.tags,
  1000. }
  1001. if got := filter(&s); got != test.want {
  1002. t.Errorf("tagFilter %s: got %v, want %v", test.desc, got, test.want)
  1003. }
  1004. })
  1005. }
  1006. }
  1007. func TestIdentifyNumLabelUnits(t *testing.T) {
  1008. var tagFilterTests = []struct {
  1009. desc string
  1010. tagVals []map[string][]int64
  1011. tagUnits []map[string][]string
  1012. wantUnits map[string]string
  1013. allowedRx string
  1014. wantIgnoreErrCount int
  1015. }{
  1016. {
  1017. "Multiple keys, no units for all keys",
  1018. []map[string][]int64{{"keyA": {131072}, "keyB": {128}}},
  1019. []map[string][]string{{"keyA": {}, "keyB": {""}}},
  1020. map[string]string{"keyA": "keyA", "keyB": "keyB"},
  1021. "",
  1022. 0,
  1023. },
  1024. {
  1025. "Multiple keys, different units for each key",
  1026. []map[string][]int64{{"keyA": {131072}, "keyB": {128}}},
  1027. []map[string][]string{{"keyA": {"bytes"}, "keyB": {"kilobytes"}}},
  1028. map[string]string{"keyA": "bytes", "keyB": "kilobytes"},
  1029. "",
  1030. 0,
  1031. },
  1032. {
  1033. "Multiple keys with multiple values, different units for each key",
  1034. []map[string][]int64{{"keyC": {131072, 1}, "keyD": {128, 252}}},
  1035. []map[string][]string{{"keyC": {"bytes", "bytes"}, "keyD": {"kilobytes", "kilobytes"}}},
  1036. map[string]string{"keyC": "bytes", "keyD": "kilobytes"},
  1037. "",
  1038. 0,
  1039. },
  1040. {
  1041. "Multiple keys with multiple values, some units missing",
  1042. []map[string][]int64{{"key1": {131072, 1}, "A": {128, 252}, "key3": {128}, "key4": {1}}, {"key3": {128}, "key4": {1}}},
  1043. []map[string][]string{{"key1": {"", "bytes"}, "A": {"kilobytes", ""}, "key3": {""}, "key4": {"hour"}}, {"key3": {"seconds"}, "key4": {""}}},
  1044. map[string]string{"key1": "bytes", "A": "kilobytes", "key3": "seconds", "key4": "hour"},
  1045. "",
  1046. 0,
  1047. },
  1048. {
  1049. "One key with three units in same sample",
  1050. []map[string][]int64{{"key": {8, 8, 16}}},
  1051. []map[string][]string{{"key": {"bytes", "megabytes", "kilobytes"}}},
  1052. map[string]string{"key": "bytes"},
  1053. `(For tag key used unit bytes, also encountered unit\(s\) kilobytes, megabytes)`,
  1054. 1,
  1055. },
  1056. {
  1057. "One key with four units in same sample",
  1058. []map[string][]int64{{"key": {8, 8, 16, 32}}},
  1059. []map[string][]string{{"key": {"bytes", "kilobytes", "a", "megabytes"}}},
  1060. map[string]string{"key": "bytes"},
  1061. `(For tag key used unit bytes, also encountered unit\(s\) a, kilobytes, megabytes)`,
  1062. 1,
  1063. },
  1064. {
  1065. "One key with two units in same sample",
  1066. []map[string][]int64{{"key": {8, 8}}},
  1067. []map[string][]string{{"key": {"bytes", "seconds"}}},
  1068. map[string]string{"key": "bytes"},
  1069. `(For tag key used unit bytes, also encountered unit\(s\) seconds)`,
  1070. 1,
  1071. },
  1072. {
  1073. "One key with different units in different samples",
  1074. []map[string][]int64{{"key1": {8}}, {"key1": {8}}, {"key1": {8}}},
  1075. []map[string][]string{{"key1": {"bytes"}}, {"key1": {"kilobytes"}}, {"key1": {"megabytes"}}},
  1076. map[string]string{"key1": "bytes"},
  1077. `(For tag key1 used unit bytes, also encountered unit\(s\) kilobytes, megabytes)`,
  1078. 1,
  1079. },
  1080. {
  1081. "Key alignment, unit not specified",
  1082. []map[string][]int64{{"alignment": {8}}},
  1083. []map[string][]string{nil},
  1084. map[string]string{"alignment": "bytes"},
  1085. "",
  1086. 0,
  1087. },
  1088. {
  1089. "Key request, unit not specified",
  1090. []map[string][]int64{{"request": {8}}, {"request": {8, 8}}},
  1091. []map[string][]string{nil, nil},
  1092. map[string]string{"request": "bytes"},
  1093. "",
  1094. 0,
  1095. },
  1096. {
  1097. "Check units not over-written for keys with default units",
  1098. []map[string][]int64{{
  1099. "alignment": {8},
  1100. "request": {8},
  1101. "bytes": {8},
  1102. }},
  1103. []map[string][]string{{
  1104. "alignment": {"seconds"},
  1105. "request": {"minutes"},
  1106. "bytes": {"hours"},
  1107. }},
  1108. map[string]string{
  1109. "alignment": "seconds",
  1110. "request": "minutes",
  1111. "bytes": "hours",
  1112. },
  1113. "",
  1114. 0,
  1115. },
  1116. }
  1117. for _, test := range tagFilterTests {
  1118. t.Run(test.desc, func(*testing.T) {
  1119. p := profile.Profile{Sample: make([]*profile.Sample, len(test.tagVals))}
  1120. for i, numLabel := range test.tagVals {
  1121. s := profile.Sample{
  1122. NumLabel: numLabel,
  1123. NumUnit: test.tagUnits[i],
  1124. }
  1125. p.Sample[i] = &s
  1126. }
  1127. testUI := &proftest.TestUI{T: t, AllowRx: test.allowedRx}
  1128. units := identifyNumLabelUnits(&p, testUI)
  1129. if !reflect.DeepEqual(test.wantUnits, units) {
  1130. t.Errorf("got %v units, want %v", units, test.wantUnits)
  1131. }
  1132. if got, want := testUI.NumAllowRxMatches, test.wantIgnoreErrCount; want != got {
  1133. t.Errorf("got %d errors logged, want %d errors logged", got, want)
  1134. }
  1135. })
  1136. }
  1137. }
  1138. func TestNumericTagFilter(t *testing.T) {
  1139. var tagFilterTests = []struct {
  1140. desc, value string
  1141. tags map[string][]int64
  1142. identifiedUnits map[string]string
  1143. want bool
  1144. }{
  1145. {
  1146. "Match when unit conversion required",
  1147. "128kb",
  1148. map[string][]int64{"key1": {131072}, "key2": {128}},
  1149. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  1150. true,
  1151. },
  1152. {
  1153. "Match only when values equal after unit conversion",
  1154. "512kb",
  1155. map[string][]int64{"key1": {512}, "key2": {128}},
  1156. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  1157. false,
  1158. },
  1159. {
  1160. "Match when values and units initially equal",
  1161. "10bytes",
  1162. map[string][]int64{"key1": {10}, "key2": {128}},
  1163. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  1164. true,
  1165. },
  1166. {
  1167. "Match range without lower bound, no unit conversion required",
  1168. ":10bytes",
  1169. map[string][]int64{"key1": {8}},
  1170. map[string]string{"key1": "bytes"},
  1171. true,
  1172. },
  1173. {
  1174. "Match range without lower bound, unit conversion required",
  1175. ":10kb",
  1176. map[string][]int64{"key1": {8}},
  1177. map[string]string{"key1": "bytes"},
  1178. true,
  1179. },
  1180. {
  1181. "Match range without upper bound, unit conversion required",
  1182. "10b:",
  1183. map[string][]int64{"key1": {8}},
  1184. map[string]string{"key1": "kilobytes"},
  1185. true,
  1186. },
  1187. {
  1188. "Match range without upper bound, no unit conversion required",
  1189. "10b:",
  1190. map[string][]int64{"key1": {12}},
  1191. map[string]string{"key1": "bytes"},
  1192. true,
  1193. },
  1194. {
  1195. "Don't match range without upper bound, no unit conversion required",
  1196. "10b:",
  1197. map[string][]int64{"key1": {8}},
  1198. map[string]string{"key1": "bytes"},
  1199. false,
  1200. },
  1201. {
  1202. "Multiple keys with different units, don't match range without upper bound",
  1203. "10kb:",
  1204. map[string][]int64{"key1": {8}},
  1205. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  1206. false,
  1207. },
  1208. {
  1209. "Match range without upper bound, unit conversion required",
  1210. "10b:",
  1211. map[string][]int64{"key1": {8}},
  1212. map[string]string{"key1": "kilobytes"},
  1213. true,
  1214. },
  1215. {
  1216. "Don't match range without lower bound, no unit conversion required",
  1217. ":10b",
  1218. map[string][]int64{"key1": {12}},
  1219. map[string]string{"key1": "bytes"},
  1220. false,
  1221. },
  1222. {
  1223. "Match specific key, key present, one of two values match",
  1224. "bytes=5b",
  1225. map[string][]int64{"bytes": {10, 5}},
  1226. map[string]string{"bytes": "bytes"},
  1227. true,
  1228. },
  1229. {
  1230. "Match specific key, key present and value matches",
  1231. "bytes=1024b",
  1232. map[string][]int64{"bytes": {1024}},
  1233. map[string]string{"bytes": "kilobytes"},
  1234. false,
  1235. },
  1236. {
  1237. "Match specific key, matching key present and value matches, also non-matching key",
  1238. "bytes=1024b",
  1239. map[string][]int64{"bytes": {1024}, "key2": {5}},
  1240. map[string]string{"bytes": "bytes", "key2": "bytes"},
  1241. true,
  1242. },
  1243. {
  1244. "Match specific key and range of values, value matches",
  1245. "bytes=512b:1024b",
  1246. map[string][]int64{"bytes": {780}},
  1247. map[string]string{"bytes": "bytes"},
  1248. true,
  1249. },
  1250. {
  1251. "Match specific key and range of values, value too large",
  1252. "key1=1kb:2kb",
  1253. map[string][]int64{"key1": {4096}},
  1254. map[string]string{"key1": "bytes"},
  1255. false,
  1256. },
  1257. {
  1258. "Match specific key and range of values, value too small",
  1259. "key1=1kb:2kb",
  1260. map[string][]int64{"key1": {256}},
  1261. map[string]string{"key1": "bytes"},
  1262. false,
  1263. },
  1264. {
  1265. "Match specific key and value, unit conversion required",
  1266. "bytes=1024b",
  1267. map[string][]int64{"bytes": {1}},
  1268. map[string]string{"bytes": "kilobytes"},
  1269. true,
  1270. },
  1271. {
  1272. "Match specific key and value, key does not appear",
  1273. "key2=256bytes",
  1274. map[string][]int64{"key1": {256}},
  1275. map[string]string{"key1": "bytes"},
  1276. false,
  1277. },
  1278. }
  1279. for _, test := range tagFilterTests {
  1280. t.Run(test.desc, func(*testing.T) {
  1281. wantErrMsg := strings.Join([]string{"(", test.desc, ":Interpreted '", test.value[strings.Index(test.value, "=")+1:], "' as range, not regexp", ")"}, "")
  1282. filter, err := compileTagFilter(test.desc, test.value, test.identifiedUnits, &proftest.TestUI{T: t,
  1283. AllowRx: wantErrMsg}, nil)
  1284. if err != nil {
  1285. t.Fatalf("%v", err)
  1286. }
  1287. s := profile.Sample{
  1288. NumLabel: test.tags,
  1289. }
  1290. if got := filter(&s); got != test.want {
  1291. t.Fatalf("got %v, want %v", got, test.want)
  1292. }
  1293. })
  1294. }
  1295. }
  1296. type testSymbolzMergeFetcher struct{}
  1297. func (testSymbolzMergeFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) {
  1298. var p *profile.Profile
  1299. switch s {
  1300. case testSourceURL(8000) + "symbolz":
  1301. p = symzProfile()
  1302. case testSourceURL(8001) + "symbolz":
  1303. p = symzProfile()
  1304. p.Mapping[0].Start += testOffset
  1305. p.Mapping[0].Limit += testOffset
  1306. for i := range p.Location {
  1307. p.Location[i].Address += testOffset
  1308. }
  1309. default:
  1310. return nil, "", fmt.Errorf("unexpected source: %s", s)
  1311. }
  1312. return p, s, nil
  1313. }
  1314. func TestSymbolzAfterMerge(t *testing.T) {
  1315. baseVars := pprofVariables
  1316. pprofVariables = baseVars.makeCopy()
  1317. defer func() { pprofVariables = baseVars }()
  1318. f := baseFlags()
  1319. f.args = []string{
  1320. testSourceURL(8000) + "symbolz",
  1321. testSourceURL(8001) + "symbolz",
  1322. }
  1323. o := setDefaults(nil)
  1324. o.Flagset = f
  1325. o.Obj = new(mockObjTool)
  1326. src, cmd, err := parseFlags(o)
  1327. if err != nil {
  1328. t.Fatalf("parseFlags: %v", err)
  1329. }
  1330. if len(cmd) != 1 || cmd[0] != "proto" {
  1331. t.Fatalf("parseFlags returned command %v, want [proto]", cmd)
  1332. }
  1333. o.Fetch = testSymbolzMergeFetcher{}
  1334. o.Sym = testSymbolzSymbolizer{}
  1335. p, err := fetchProfiles(src, o)
  1336. if err != nil {
  1337. t.Fatalf("fetchProfiles: %v", err)
  1338. }
  1339. if len(p.Location) != 3 {
  1340. t.Errorf("Got %d locations after merge, want %d", len(p.Location), 3)
  1341. }
  1342. for i, l := range p.Location {
  1343. if len(l.Line) != 1 {
  1344. t.Errorf("Number of lines for symbolz %#x in iteration %d, got %d, want %d", l.Address, i, len(l.Line), 1)
  1345. continue
  1346. }
  1347. address := l.Address - l.Mapping.Start
  1348. if got, want := l.Line[0].Function.Name, fmt.Sprintf("%#x", address); got != want {
  1349. t.Errorf("symbolz %#x, got %s, want %s", address, got, want)
  1350. }
  1351. }
  1352. }
  1353. type mockObjTool struct{}
  1354. func (*mockObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  1355. return &mockFile{file, "abcdef", 0}, nil
  1356. }
  1357. func (m *mockObjTool) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  1358. switch start {
  1359. case 0x1000:
  1360. return []plugin.Inst{
  1361. {Addr: 0x1000, Text: "instruction one", File: "file1000.src", Line: 1},
  1362. {Addr: 0x1001, Text: "instruction two", File: "file1000.src", Line: 1},
  1363. {Addr: 0x1002, Text: "instruction three", File: "file1000.src", Line: 2},
  1364. {Addr: 0x1003, Text: "instruction four", File: "file1000.src", Line: 1},
  1365. }, nil
  1366. case 0x3000:
  1367. return []plugin.Inst{
  1368. {Addr: 0x3000, Text: "instruction one"},
  1369. {Addr: 0x3001, Text: "instruction two"},
  1370. {Addr: 0x3002, Text: "instruction three"},
  1371. {Addr: 0x3003, Text: "instruction four"},
  1372. {Addr: 0x3004, Text: "instruction five"},
  1373. }, nil
  1374. }
  1375. return nil, fmt.Errorf("unimplemented")
  1376. }
  1377. type mockFile struct {
  1378. name, buildID string
  1379. base uint64
  1380. }
  1381. // Name returns the underlyinf file name, if available
  1382. func (m *mockFile) Name() string {
  1383. return m.name
  1384. }
  1385. // Base returns the base address to use when looking up symbols in the file.
  1386. func (m *mockFile) Base() uint64 {
  1387. return m.base
  1388. }
  1389. // BuildID returns the GNU build ID of the file, or an empty string.
  1390. func (m *mockFile) BuildID() string {
  1391. return m.buildID
  1392. }
  1393. // SourceLine reports the source line information for a given
  1394. // address in the file. Due to inlining, the source line information
  1395. // is in general a list of positions representing a call stack,
  1396. // with the leaf function first.
  1397. func (*mockFile) SourceLine(addr uint64) ([]plugin.Frame, error) {
  1398. return nil, fmt.Errorf("unimplemented")
  1399. }
  1400. // Symbols returns a list of symbols in the object file.
  1401. // If r is not nil, Symbols restricts the list to symbols
  1402. // with names matching the regular expression.
  1403. // If addr is not zero, Symbols restricts the list to symbols
  1404. // containing that address.
  1405. func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  1406. switch r.String() {
  1407. case "line[13]":
  1408. return []*plugin.Sym{
  1409. {
  1410. Name: []string{"line1000"}, File: m.name,
  1411. Start: 0x1000, End: 0x1003,
  1412. },
  1413. {
  1414. Name: []string{"line3000"}, File: m.name,
  1415. Start: 0x3000, End: 0x3004,
  1416. },
  1417. }, nil
  1418. }
  1419. return nil, fmt.Errorf("unimplemented")
  1420. }
  1421. // Close closes the file, releasing associated resources.
  1422. func (*mockFile) Close() error {
  1423. return nil
  1424. }