You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
12 KiB

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