暂无描述

binutils_test.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 binutils
  15. import (
  16. "bytes"
  17. "fmt"
  18. "math"
  19. "path/filepath"
  20. "reflect"
  21. "regexp"
  22. "runtime"
  23. "strings"
  24. "testing"
  25. "github.com/google/pprof/pkg/plugin"
  26. )
  27. var testAddrMap = map[int]string{
  28. 1000: "_Z3fooid.clone2",
  29. 2000: "_ZNSaIiEC1Ev.clone18",
  30. 3000: "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm",
  31. }
  32. func functionName(level int) (name string) {
  33. if name = testAddrMap[level]; name != "" {
  34. return name
  35. }
  36. return fmt.Sprintf("fun%d", level)
  37. }
  38. func TestAddr2Liner(t *testing.T) {
  39. const offset = 0x500
  40. a := addr2Liner{rw: &mockAddr2liner{}, base: offset}
  41. for i := 1; i < 8; i++ {
  42. addr := i*0x1000 + offset
  43. s, err := a.addrInfo(uint64(addr))
  44. if err != nil {
  45. t.Fatalf("addrInfo(%#x): %v", addr, err)
  46. }
  47. if len(s) != i {
  48. t.Fatalf("addrInfo(%#x): got len==%d, want %d", addr, len(s), i)
  49. }
  50. for l, f := range s {
  51. level := (len(s) - l) * 1000
  52. want := plugin.Frame{Func: functionName(level), File: fmt.Sprintf("file%d", level), Line: level}
  53. if f != want {
  54. t.Errorf("AddrInfo(%#x)[%d]: = %+v, want %+v", addr, l, f, want)
  55. }
  56. }
  57. }
  58. s, err := a.addrInfo(0xFFFF)
  59. if err != nil {
  60. t.Fatalf("addrInfo(0xFFFF): %v", err)
  61. }
  62. if len(s) != 0 {
  63. t.Fatalf("AddrInfo(0xFFFF): got len==%d, want 0", len(s))
  64. }
  65. a.rw.close()
  66. }
  67. type mockAddr2liner struct {
  68. output []string
  69. }
  70. func (a *mockAddr2liner) write(s string) error {
  71. var lines []string
  72. switch s {
  73. case "1000":
  74. lines = []string{"_Z3fooid.clone2", "file1000:1000"}
  75. case "2000":
  76. lines = []string{"_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  77. case "3000":
  78. lines = []string{"_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  79. case "4000":
  80. lines = []string{"fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  81. case "5000":
  82. lines = []string{"fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  83. case "6000":
  84. lines = []string{"fun6000", "file6000:6000", "fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  85. case "7000":
  86. lines = []string{"fun7000", "file7000:7000", "fun6000", "file6000:6000", "fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  87. case "8000":
  88. lines = []string{"fun8000", "file8000:8000", "fun7000", "file7000:7000", "fun6000", "file6000:6000", "fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  89. case "9000":
  90. lines = []string{"fun9000", "file9000:9000", "fun8000", "file8000:8000", "fun7000", "file7000:7000", "fun6000", "file6000:6000", "fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
  91. default:
  92. lines = []string{"??", "??:0"}
  93. }
  94. a.output = append(a.output, "0x"+s)
  95. a.output = append(a.output, lines...)
  96. return nil
  97. }
  98. func (a *mockAddr2liner) readLine() (string, error) {
  99. if len(a.output) == 0 {
  100. return "", fmt.Errorf("end of file")
  101. }
  102. next := a.output[0]
  103. a.output = a.output[1:]
  104. return next, nil
  105. }
  106. func (a *mockAddr2liner) close() {
  107. }
  108. func TestAddr2LinerLookup(t *testing.T) {
  109. const oddSizedData = `
  110. 00001000 T 0x1000
  111. 00002000 T 0x2000
  112. 00003000 T 0x3000
  113. `
  114. const evenSizedData = `
  115. 0000000000001000 T 0x1000
  116. 0000000000002000 T 0x2000
  117. 0000000000003000 T 0x3000
  118. 0000000000004000 T 0x4000
  119. `
  120. for _, d := range []string{oddSizedData, evenSizedData} {
  121. a, err := parseAddr2LinerNM(0, bytes.NewBufferString(d))
  122. if err != nil {
  123. t.Errorf("nm parse error: %v", err)
  124. continue
  125. }
  126. for address, want := range map[uint64]string{
  127. 0x1000: "0x1000",
  128. 0x1001: "0x1000",
  129. 0x1FFF: "0x1000",
  130. 0x2000: "0x2000",
  131. 0x2001: "0x2000",
  132. } {
  133. if got, _ := a.addrInfo(address); !checkAddress(got, address, want) {
  134. t.Errorf("%x: got %v, want %s", address, got, want)
  135. }
  136. }
  137. for _, unknown := range []uint64{0x0fff, 0x4001} {
  138. if got, _ := a.addrInfo(unknown); got != nil {
  139. t.Errorf("%x: got %v, want nil", unknown, got)
  140. }
  141. }
  142. }
  143. }
  144. func checkAddress(got []plugin.Frame, address uint64, want string) bool {
  145. if len(got) != 1 {
  146. return false
  147. }
  148. return got[0].Func == want
  149. }
  150. func TestSetTools(t *testing.T) {
  151. // Test that multiple calls work.
  152. bu := &Binutils{}
  153. bu.SetTools("")
  154. bu.SetTools("")
  155. }
  156. func TestSetFastSymbolization(t *testing.T) {
  157. // Test that multiple calls work.
  158. bu := &Binutils{}
  159. bu.SetFastSymbolization(true)
  160. bu.SetFastSymbolization(false)
  161. }
  162. func skipUnlessLinuxAmd64(t *testing.T) {
  163. if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
  164. t.Skip("This test only works on x86-64 Linux")
  165. }
  166. }
  167. func skipUnlessDarwinAmd64(t *testing.T) {
  168. if runtime.GOOS != "darwin" || runtime.GOARCH != "amd64" {
  169. t.Skip("This test only works on x86-64 Mac")
  170. }
  171. }
  172. func testDisasm(t *testing.T, intelSyntax bool) {
  173. _, llvmObjdump, buObjdump := findObjdump([]string{""})
  174. if !(llvmObjdump || buObjdump) {
  175. t.Skip("cannot disasm: no objdump tool available")
  176. }
  177. bu := &Binutils{}
  178. testexe := "exe_linux_64"
  179. if runtime.GOOS == "darwin" {
  180. testexe = "exe_mac_64"
  181. }
  182. insts, err := bu.Disasm(filepath.Join("testdata", testexe), 0, math.MaxUint64, intelSyntax)
  183. if err != nil {
  184. t.Fatalf("Disasm: unexpected error %v", err)
  185. }
  186. mainCount := 0
  187. for _, x := range insts {
  188. // Mac symbols have a leading underscore.
  189. if x.Function == "main" || x.Function == "_main" {
  190. mainCount++
  191. }
  192. }
  193. if mainCount == 0 {
  194. t.Error("Disasm: found no main instructions")
  195. }
  196. }
  197. func TestDisasm(t *testing.T) {
  198. if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
  199. t.Skip("This test only works on Linux or Mac")
  200. }
  201. testDisasm(t, true)
  202. testDisasm(t, false)
  203. }
  204. func findSymbol(syms []*plugin.Sym, name string) *plugin.Sym {
  205. for _, s := range syms {
  206. for _, n := range s.Name {
  207. if n == name {
  208. return s
  209. }
  210. }
  211. }
  212. return nil
  213. }
  214. func TestObjFile(t *testing.T) {
  215. // If this test fails, check the address for main function in testdata/exe_linux_64
  216. // using the command 'nm -n '. Update the hardcoded addresses below to match
  217. // the addresses from the output.
  218. skipUnlessLinuxAmd64(t)
  219. for _, tc := range []struct {
  220. desc string
  221. start, limit, offset uint64
  222. addr uint64
  223. }{
  224. {"fake mapping", 0, math.MaxUint64, 0, 0x40052d},
  225. {"fixed load address", 0x400000, 0x4006fc, 0, 0x40052d},
  226. // True user-mode ASLR binaries are ET_DYN rather than ET_EXEC so this case
  227. // is a bit artificial except that it approximates the
  228. // vmlinux-with-kernel-ASLR case where the binary *is* ET_EXEC.
  229. {"simulated ASLR address", 0x500000, 0x5006fc, 0, 0x50052d},
  230. } {
  231. t.Run(tc.desc, func(t *testing.T) {
  232. bu := &Binutils{}
  233. f, err := bu.Open(filepath.Join("testdata", "exe_linux_64"), tc.start, tc.limit, tc.offset)
  234. if err != nil {
  235. t.Fatalf("Open: unexpected error %v", err)
  236. }
  237. defer f.Close()
  238. syms, err := f.Symbols(regexp.MustCompile("main"), 0)
  239. if err != nil {
  240. t.Fatalf("Symbols: unexpected error %v", err)
  241. }
  242. m := findSymbol(syms, "main")
  243. if m == nil {
  244. t.Fatalf("Symbols: did not find main")
  245. }
  246. for _, addr := range []uint64{m.Start + f.Base(), tc.addr} {
  247. gotFrames, err := f.SourceLine(addr)
  248. if err != nil {
  249. t.Fatalf("SourceLine: unexpected error %v", err)
  250. }
  251. wantFrames := []plugin.Frame{
  252. {Func: "main", File: "/tmp/hello.c", Line: 3},
  253. }
  254. if !reflect.DeepEqual(gotFrames, wantFrames) {
  255. t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, wantFrames)
  256. }
  257. }
  258. })
  259. }
  260. }
  261. func TestMachoFiles(t *testing.T) {
  262. // If this test fails, check the address for main function in testdata/exe_mac_64
  263. // and testdata/lib_mac_64 using addr2line or gaddr2line. Update the
  264. // hardcoded addresses below to match the addresses from the output.
  265. skipUnlessDarwinAmd64(t)
  266. // Load `file`, pretending it was mapped at `start`. Then get the symbol
  267. // table. Check that it contains the symbol `sym` and that the address
  268. // `addr` gives the `expected` stack trace.
  269. for _, tc := range []struct {
  270. desc string
  271. file string
  272. start, limit, offset uint64
  273. addr uint64
  274. sym string
  275. expected []plugin.Frame
  276. }{
  277. {"normal mapping", "exe_mac_64", 0x100000000, math.MaxUint64, 0,
  278. 0x100000f50, "_main",
  279. []plugin.Frame{
  280. {Func: "main", File: "/tmp/hello.c", Line: 3},
  281. }},
  282. {"other mapping", "exe_mac_64", 0x200000000, math.MaxUint64, 0,
  283. 0x200000f50, "_main",
  284. []plugin.Frame{
  285. {Func: "main", File: "/tmp/hello.c", Line: 3},
  286. }},
  287. {"lib normal mapping", "lib_mac_64", 0, math.MaxUint64, 0,
  288. 0xfa0, "_bar",
  289. []plugin.Frame{
  290. {Func: "bar", File: "/tmp/lib.c", Line: 5},
  291. }},
  292. } {
  293. t.Run(tc.desc, func(t *testing.T) {
  294. bu := &Binutils{}
  295. f, err := bu.Open(filepath.Join("testdata", tc.file), tc.start, tc.limit, tc.offset)
  296. if err != nil {
  297. t.Fatalf("Open: unexpected error %v", err)
  298. }
  299. t.Logf("binutils: %v", bu)
  300. if runtime.GOOS == "darwin" && !bu.rep.addr2lineFound && !bu.rep.llvmSymbolizerFound {
  301. // On OSX user needs to install gaddr2line or llvm-symbolizer with
  302. // Homebrew, skip the test when the environment doesn't have it
  303. // installed.
  304. t.Skip("couldn't find addr2line or gaddr2line")
  305. }
  306. defer f.Close()
  307. syms, err := f.Symbols(nil, 0)
  308. if err != nil {
  309. t.Fatalf("Symbols: unexpected error %v", err)
  310. }
  311. m := findSymbol(syms, tc.sym)
  312. if m == nil {
  313. t.Fatalf("Symbols: could not find symbol %v", tc.sym)
  314. }
  315. gotFrames, err := f.SourceLine(tc.addr)
  316. if err != nil {
  317. t.Fatalf("SourceLine: unexpected error %v", err)
  318. }
  319. if !reflect.DeepEqual(gotFrames, tc.expected) {
  320. t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, tc.expected)
  321. }
  322. })
  323. }
  324. }
  325. func TestLLVMSymbolizer(t *testing.T) {
  326. if runtime.GOOS != "linux" {
  327. t.Skip("testtdata/llvm-symbolizer has only been tested on linux")
  328. }
  329. cmd := filepath.Join("testdata", "fake-llvm-symbolizer")
  330. symbolizer, err := newLLVMSymbolizer(cmd, "foo", 0)
  331. if err != nil {
  332. t.Fatalf("newLLVMSymbolizer: unexpected error %v", err)
  333. }
  334. defer symbolizer.rw.close()
  335. for _, c := range []struct {
  336. addr uint64
  337. frames []plugin.Frame
  338. }{
  339. {0x10, []plugin.Frame{
  340. {Func: "Inlined_0x10", File: "foo.h", Line: 0},
  341. {Func: "Func_0x10", File: "foo.c", Line: 2},
  342. }},
  343. {0x20, []plugin.Frame{
  344. {Func: "Inlined_0x20", File: "foo.h", Line: 0},
  345. {Func: "Func_0x20", File: "foo.c", Line: 2},
  346. }},
  347. } {
  348. frames, err := symbolizer.addrInfo(c.addr)
  349. if err != nil {
  350. t.Errorf("LLVM: unexpected error %v", err)
  351. continue
  352. }
  353. if !reflect.DeepEqual(frames, c.frames) {
  354. t.Errorf("LLVM: expect %v; got %v\n", c.frames, frames)
  355. }
  356. }
  357. }
  358. func TestOpenMalformedELF(t *testing.T) {
  359. // Test that opening a malformed ELF file will report an error containing
  360. // the word "ELF".
  361. bu := &Binutils{}
  362. _, err := bu.Open(filepath.Join("testdata", "malformed_elf"), 0, 0, 0)
  363. if err == nil {
  364. t.Fatalf("Open: unexpected success")
  365. }
  366. if !strings.Contains(err.Error(), "ELF") {
  367. t.Errorf("Open: got %v, want error containing 'ELF'", err)
  368. }
  369. }
  370. func TestOpenMalformedMachO(t *testing.T) {
  371. // Test that opening a malformed Mach-O file will report an error containing
  372. // the word "Mach-O".
  373. bu := &Binutils{}
  374. _, err := bu.Open(filepath.Join("testdata", "malformed_macho"), 0, 0, 0)
  375. if err == nil {
  376. t.Fatalf("Open: unexpected success")
  377. }
  378. if !strings.Contains(err.Error(), "Mach-O") {
  379. t.Errorf("Open: got %v, want error containing 'Mach-O'", err)
  380. }
  381. }
  382. func TestObjdumpVersionChecks(t *testing.T) {
  383. // Test that the objdump version strings are parsed properly.
  384. type testcase struct {
  385. desc string
  386. os string
  387. ver string
  388. want bool
  389. }
  390. for _, tc := range []testcase{
  391. {
  392. desc: "Valid Apple LLVM version string with usable version",
  393. os: "darwin",
  394. ver: "Apple LLVM version 11.0.3 (clang-1103.0.32.62)\nOptimized build.",
  395. want: true,
  396. },
  397. {
  398. desc: "Valid Apple LLVM version string with unusable version",
  399. os: "darwin",
  400. ver: "Apple LLVM version 10.0.0 (clang-1000.11.45.5)\nOptimized build.",
  401. want: false,
  402. },
  403. {
  404. desc: "Invalid Apple LLVM version string with usable version",
  405. os: "darwin",
  406. ver: "Apple LLVM versions 11.0.3 (clang-1103.0.32.62)\nOptimized build.",
  407. want: false,
  408. },
  409. {
  410. desc: "Valid LLVM version string with usable version",
  411. os: "linux",
  412. ver: "LLVM (http://llvm.org/):\nLLVM version 9.0.1\n\nOptimized build.",
  413. want: true,
  414. },
  415. {
  416. desc: "Valid LLVM version string with unusable version",
  417. os: "linux",
  418. ver: "LLVM (http://llvm.org/):\nLLVM version 6.0.1\n\nOptimized build.",
  419. want: false,
  420. },
  421. {
  422. desc: "Invalid LLVM version string with usable version",
  423. os: "linux",
  424. ver: "LLVM (http://llvm.org/):\nLLVM versions 9.0.1\n\nOptimized build.",
  425. want: false,
  426. },
  427. {
  428. desc: "Valid LLVM objdump version string with trunk",
  429. os: runtime.GOOS,
  430. ver: "LLVM (http://llvm.org/):\nLLVM version custom-trunk 124ffeb592a00bfe\nOptimized build.",
  431. want: true,
  432. },
  433. {
  434. desc: "Invalid LLVM objdump version string with trunk",
  435. os: runtime.GOOS,
  436. ver: "LLVM (http://llvm.org/):\nLLVM version custom-trank 124ffeb592a00bfe\nOptimized build.",
  437. want: false,
  438. },
  439. {
  440. desc: "Invalid LLVM objdump version string with trunk",
  441. os: runtime.GOOS,
  442. ver: "LLVM (http://llvm.org/):\nllvm version custom-trunk 124ffeb592a00bfe\nOptimized build.",
  443. want: false,
  444. },
  445. } {
  446. if runtime.GOOS == tc.os {
  447. if got := isLLVMObjdump(tc.ver); got != tc.want {
  448. t.Errorf("%v: got %v, want %v", tc.desc, got, tc.want)
  449. }
  450. }
  451. }
  452. for _, tc := range []testcase{
  453. {
  454. desc: "Valid GNU objdump version string",
  455. ver: "GNU objdump (GNU Binutils) 2.34\nCopyright (C) 2020 Free Software Foundation, Inc.",
  456. want: true,
  457. },
  458. {
  459. desc: "Invalid GNU objdump version string",
  460. ver: "GNU nm (GNU Binutils) 2.34\nCopyright (C) 2020 Free Software Foundation, Inc.",
  461. want: false,
  462. },
  463. } {
  464. if got := isBuObjdump(tc.ver); got != tc.want {
  465. t.Errorf("%v: got %v, want %v", tc.desc, got, tc.want)
  466. }
  467. }
  468. }