Nenhuma descrição

driver_test.go 41KB

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