Aucune description

driver_test.go 41KB

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