Nessuna descrizione

binutils_test.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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/internal/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. bu := &Binutils{}
  174. insts, err := bu.Disasm(filepath.Join("testdata", "exe_linux_64"), 0, math.MaxUint64, intelSyntax)
  175. if err != nil {
  176. t.Fatalf("Disasm: unexpected error %v", err)
  177. }
  178. mainCount := 0
  179. for _, x := range insts {
  180. if x.Function == "main" {
  181. mainCount++
  182. }
  183. }
  184. if mainCount == 0 {
  185. t.Error("Disasm: found no main instructions")
  186. }
  187. }
  188. func TestDisasm(t *testing.T) {
  189. skipUnlessLinuxAmd64(t)
  190. testDisasm(t, true)
  191. testDisasm(t, false)
  192. }
  193. func findSymbol(syms []*plugin.Sym, name string) *plugin.Sym {
  194. for _, s := range syms {
  195. for _, n := range s.Name {
  196. if n == name {
  197. return s
  198. }
  199. }
  200. }
  201. return nil
  202. }
  203. func TestObjFile(t *testing.T) {
  204. // If this test fails, check the address for main function in testdata/exe_linux_64
  205. // using the command 'nm -n '. Update the hardcoded addresses below to match
  206. // the addresses from the output.
  207. skipUnlessLinuxAmd64(t)
  208. for _, tc := range []struct {
  209. desc string
  210. start, limit, offset uint64
  211. addr uint64
  212. }{
  213. {"fake mapping", 0, math.MaxUint64, 0, 0x40052d},
  214. {"fixed load address", 0x400000, 0x4006fc, 0, 0x40052d},
  215. // True user-mode ASLR binaries are ET_DYN rather than ET_EXEC so this case
  216. // is a bit artificial except that it approximates the
  217. // vmlinux-with-kernel-ASLR case where the binary *is* ET_EXEC.
  218. {"simulated ASLR address", 0x500000, 0x5006fc, 0, 0x50052d},
  219. } {
  220. t.Run(tc.desc, func(t *testing.T) {
  221. bu := &Binutils{}
  222. f, err := bu.Open(filepath.Join("testdata", "exe_linux_64"), tc.start, tc.limit, tc.offset)
  223. if err != nil {
  224. t.Fatalf("Open: unexpected error %v", err)
  225. }
  226. defer f.Close()
  227. syms, err := f.Symbols(regexp.MustCompile("main"), 0)
  228. if err != nil {
  229. t.Fatalf("Symbols: unexpected error %v", err)
  230. }
  231. m := findSymbol(syms, "main")
  232. if m == nil {
  233. t.Fatalf("Symbols: did not find main")
  234. }
  235. for _, addr := range []uint64{m.Start + f.Base(), tc.addr} {
  236. gotFrames, err := f.SourceLine(addr)
  237. if err != nil {
  238. t.Fatalf("SourceLine: unexpected error %v", err)
  239. }
  240. wantFrames := []plugin.Frame{
  241. {Func: "main", File: "/tmp/hello.c", Line: 3},
  242. }
  243. if !reflect.DeepEqual(gotFrames, wantFrames) {
  244. t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, wantFrames)
  245. }
  246. }
  247. })
  248. }
  249. }
  250. func TestMachoFiles(t *testing.T) {
  251. // If this test fails, check the address for main function in testdata/exe_mac_64
  252. // and testdata/lib_mac_64 using addr2line or gaddr2line. Update the
  253. // hardcoded addresses below to match the addresses from the output.
  254. skipUnlessDarwinAmd64(t)
  255. // Load `file`, pretending it was mapped at `start`. Then get the symbol
  256. // table. Check that it contains the symbol `sym` and that the address
  257. // `addr` gives the `expected` stack trace.
  258. for _, tc := range []struct {
  259. desc string
  260. file string
  261. start, limit, offset uint64
  262. addr uint64
  263. sym string
  264. expected []plugin.Frame
  265. }{
  266. {"normal mapping", "exe_mac_64", 0x100000000, math.MaxUint64, 0,
  267. 0x100000f50, "_main",
  268. []plugin.Frame{
  269. {Func: "main", File: "/tmp/hello.c", Line: 3},
  270. }},
  271. {"other mapping", "exe_mac_64", 0x200000000, math.MaxUint64, 0,
  272. 0x200000f50, "_main",
  273. []plugin.Frame{
  274. {Func: "main", File: "/tmp/hello.c", Line: 3},
  275. }},
  276. {"lib normal mapping", "lib_mac_64", 0, math.MaxUint64, 0,
  277. 0xfa0, "_bar",
  278. []plugin.Frame{
  279. {Func: "bar", File: "/tmp/lib.c", Line: 5},
  280. }},
  281. } {
  282. t.Run(tc.desc, func(t *testing.T) {
  283. bu := &Binutils{}
  284. f, err := bu.Open(filepath.Join("testdata", tc.file), tc.start, tc.limit, tc.offset)
  285. if err != nil {
  286. t.Fatalf("Open: unexpected error %v", err)
  287. }
  288. t.Logf("binutils: %v", bu)
  289. if runtime.GOOS == "darwin" && !bu.rep.addr2lineFound && !bu.rep.llvmSymbolizerFound {
  290. // On OSX user needs to install gaddr2line or llvm-symbolizer with
  291. // Homebrew, skip the test when the environment doesn't have it
  292. // installed.
  293. t.Skip("couldn't find addr2line or gaddr2line")
  294. }
  295. defer f.Close()
  296. syms, err := f.Symbols(nil, 0)
  297. if err != nil {
  298. t.Fatalf("Symbols: unexpected error %v", err)
  299. }
  300. m := findSymbol(syms, tc.sym)
  301. if m == nil {
  302. t.Fatalf("Symbols: could not find symbol %v", tc.sym)
  303. }
  304. gotFrames, err := f.SourceLine(tc.addr)
  305. if err != nil {
  306. t.Fatalf("SourceLine: unexpected error %v", err)
  307. }
  308. if !reflect.DeepEqual(gotFrames, tc.expected) {
  309. t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, tc.expected)
  310. }
  311. })
  312. }
  313. }
  314. func TestLLVMSymbolizer(t *testing.T) {
  315. if runtime.GOOS != "linux" {
  316. t.Skip("testtdata/llvm-symbolizer has only been tested on linux")
  317. }
  318. cmd := filepath.Join("testdata", "fake-llvm-symbolizer")
  319. symbolizer, err := newLLVMSymbolizer(cmd, "foo", 0)
  320. if err != nil {
  321. t.Fatalf("newLLVMSymbolizer: unexpected error %v", err)
  322. }
  323. defer symbolizer.rw.close()
  324. for _, c := range []struct {
  325. addr uint64
  326. frames []plugin.Frame
  327. }{
  328. {0x10, []plugin.Frame{
  329. {Func: "Inlined_0x10", File: "foo.h", Line: 0},
  330. {Func: "Func_0x10", File: "foo.c", Line: 2},
  331. }},
  332. {0x20, []plugin.Frame{
  333. {Func: "Inlined_0x20", File: "foo.h", Line: 0},
  334. {Func: "Func_0x20", File: "foo.c", Line: 2},
  335. }},
  336. } {
  337. frames, err := symbolizer.addrInfo(c.addr)
  338. if err != nil {
  339. t.Errorf("LLVM: unexpected error %v", err)
  340. continue
  341. }
  342. if !reflect.DeepEqual(frames, c.frames) {
  343. t.Errorf("LLVM: expect %v; got %v\n", c.frames, frames)
  344. }
  345. }
  346. }
  347. func TestOpenMalformedELF(t *testing.T) {
  348. // Test that opening a malformed ELF file will report an error containing
  349. // the word "ELF".
  350. bu := &Binutils{}
  351. _, err := bu.Open(filepath.Join("testdata", "malformed_elf"), 0, 0, 0)
  352. if err == nil {
  353. t.Fatalf("Open: unexpected success")
  354. }
  355. if !strings.Contains(err.Error(), "ELF") {
  356. t.Errorf("Open: got %v, want error containing 'ELF'", err)
  357. }
  358. }
  359. func TestOpenMalformedMachO(t *testing.T) {
  360. // Test that opening a malformed Mach-O file will report an error containing
  361. // the word "Mach-O".
  362. bu := &Binutils{}
  363. _, err := bu.Open(filepath.Join("testdata", "malformed_macho"), 0, 0, 0)
  364. if err == nil {
  365. t.Fatalf("Open: unexpected success")
  366. }
  367. if !strings.Contains(err.Error(), "Mach-O") {
  368. t.Errorf("Open: got %v, want error containing 'Mach-O'", err)
  369. }
  370. }