暂无描述

driver_test.go 40KB

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