Brak opisu

driver_test.go 44KB

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