Ei kuvausta

driver_test.go 41KB

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