Няма описание

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