Debian Codegraph @

internal/binutils/binutils_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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
15 package binutils
16
17 import (
18 "bytes"
19 "debug/elf"
20 "encoding/binary"
21 "errors"
22 "fmt"
23 "math"
24 "path/filepath"
25 "reflect"
26 "regexp"
27 "runtime"
28 "slices"
29 "strings"
30 "testing"
31
32 "github.com/google/pprof/internal/plugin"
33 )
34
35 var testAddrMap = map[int]string{
36 1000: "_Z3fooid.clone2",
37 2000: "_ZNSaIiEC1Ev.clone18",
38 3000: "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm",
39 }
40
41 func functionName(level int) (name string) {
42 if name = testAddrMap[level]; name != "" {
43 return name
44 }
45 return fmt.Sprintf("fun%d", level)
46 }
47
48 func TestAddr2Liner(t *testing.T) {
49 const offset = 0x500
50
51 a := addr2Liner{rw: &mockAddr2liner{}, base: offset}
52 for i := 1; i < 8; i++ {
53 addr := i*0x1000 + offset
54 s, err := a.addrInfo(uint64(addr))
55 if err != nil {
56 t.Fatalf("addrInfo(%#x): %v", addr, err)
57 }
58 if len(s) != i {
59 t.Fatalf("addrInfo(%#x): got len==%d, want %d", addr, len(s), i)
60 }
61 for l, f := range s {
62 level := (len(s) - l) * 1000
63 want := plugin.Frame{Func: functionName(level), File: fmt.Sprintf("file%d", level), Line: level}
64
65 if f != want {
66 t.Errorf("AddrInfo(%#x)[%d]: = %+v, want %+v", addr, l, f, want)
67 }
68 }
69 }
70 s, err := a.addrInfo(0xFFFF)
71 if err != nil {
72 t.Fatalf("addrInfo(0xFFFF): %v", err)
73 }
74 if len(s) != 0 {
75 t.Fatalf("AddrInfo(0xFFFF): got len==%d, want 0", len(s))
76 }
77 a.rw.close()
78 }
79
80 type mockAddr2liner struct {
81 output []string
82 }
83
84 func (a *mockAddr2liner) write(s string) error {
85 var lines []string
86 switch s {
87 case "1000":
88 lines = []string{"_Z3fooid.clone2", "file1000:1000"}
89 case "2000":
90 lines = []string{"_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
91 case "3000":
92 lines = []string{"_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
93 case "4000":
94 lines = []string{"fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
95 case "5000":
96 lines = []string{"fun5000", "file5000:5000", "fun4000", "file4000:4000", "_ZNSt6vectorIS_IS_IiSaIiEESaIS1_EESaIS3_EEixEm", "file3000:3000", "_ZNSaIiEC1Ev.clone18", "file2000:2000", "_Z3fooid.clone2", "file1000:1000"}
97 case "6000":
98 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"}
99 case "7000":
100 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"}
101 case "8000":
102 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"}
103 case "9000":
104 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"}
105 default:
106 lines = []string{"??", "??:0"}
107 }
108 a.output = append(a.output, "0x"+s)
109 a.output = append(a.output, lines...)
110 return nil
111 }
112
113 func (a *mockAddr2liner) readLine() (string, error) {
114 if len(a.output) == 0 {
115 return "", fmt.Errorf("end of file")
116 }
117 next := a.output[0]
118 a.output = a.output[1:]
119 return next, nil
120 }
121
122 func (a *mockAddr2liner) close() {
123 }
124
125 func TestAddr2LinerLookup(t *testing.T) {
126 for _, tc := range []struct {
127 desc string
128 nmOutput string
129 wantSymbolized map[uint64]string
130 wantUnsymbolized []uint64
131 }{
132 {
133 desc: "odd symbol count",
134 nmOutput: `
135 0x1000 T 1000 100
136 0x2000 T 2000 120
137 0x3000 T 3000 130
138 `,
139 wantSymbolized: map[uint64]string{
140 0x1000: "0x1000",
141 0x1001: "0x1000",
142 0x1FFF: "0x1000",
143 0x2000: "0x2000",
144 0x2001: "0x2000",
145 0x3000: "0x3000",
146 0x312f: "0x3000",
147 },
148 wantUnsymbolized: []uint64{0x0fff, 0x3130},
149 },
150 {
151 desc: "even symbol count",
152 nmOutput: `
153 0x1000 T 1000 100
154 0x2000 T 2000 120
155 0x3000 T 3000 130
156 0x4000 T 4000 140
157 `,
158 wantSymbolized: map[uint64]string{
159 0x1000: "0x1000",
160 0x1001: "0x1000",
161 0x1FFF: "0x1000",
162 0x2000: "0x2000",
163 0x2fff: "0x2000",
164 0x3000: "0x3000",
165 0x3fff: "0x3000",
166 0x4000: "0x4000",
167 0x413f: "0x4000",
168 },
169 wantUnsymbolized: []uint64{0x0fff, 0x4140},
170 },
171 {
172 desc: "different symbol types",
173 nmOutput: `
174 absolute_0x100 a 100
175 absolute_0x200 A 200
176 text_0x1000 t 1000 100
177 bss_0x2000 b 2000 120
178 data_0x3000 d 3000 130
179 rodata_0x4000 r 4000 140
180 weak_0x5000 v 5000 150
181 text_0x6000 T 6000 160
182 bss_0x7000 B 7000 170
183 data_0x8000 D 8000 180
184 rodata_0x9000 R 9000 190
185 weak_0xa000 V a000 1a0
186 weak_0xb000 W b000 1b0
187 `,
188 wantSymbolized: map[uint64]string{
189 0x1000: "text_0x1000",
190 0x1FFF: "text_0x1000",
191 0x2000: "bss_0x2000",
192 0x211f: "bss_0x2000",
193 0x3000: "data_0x3000",
194 0x312f: "data_0x3000",
195 0x4000: "rodata_0x4000",
196 0x413f: "rodata_0x4000",
197 0x5000: "weak_0x5000",
198 0x514f: "weak_0x5000",
199 0x6000: "text_0x6000",
200 0x6fff: "text_0x6000",
201 0x7000: "bss_0x7000",
202 0x716f: "bss_0x7000",
203 0x8000: "data_0x8000",
204 0x817f: "data_0x8000",
205 0x9000: "rodata_0x9000",
206 0x918f: "rodata_0x9000",
207 0xa000: "weak_0xa000",
208 0xa19f: "weak_0xa000",
209 0xb000: "weak_0xb000",
210 0xb1af: "weak_0xb000",
211 },
212 wantUnsymbolized: []uint64{0x100, 0x200, 0x0fff, 0x2120, 0x3130, 0x4140, 0x5150, 0x7170, 0x8180, 0x9190, 0xa1a0, 0xb1b0},
213 },
214 } {
215 t.Run(tc.desc, func(t *testing.T) {
216 a, err := parseAddr2LinerNM(0, bytes.NewBufferString(tc.nmOutput))
217 if err != nil {
218 t.Fatalf("nm parse error: %v", err)
219 }
220 for address, want := range tc.wantSymbolized {
221 if got, _ := a.addrInfo(address); !checkAddress(got, address, want) {
222 t.Errorf("%x: got %v, want %s", address, got, want)
223 }
224 }
225 for _, unknown := range tc.wantUnsymbolized {
226 if got, _ := a.addrInfo(unknown); got != nil {
227 t.Errorf("%x: got %v, want nil", unknown, got)
228 }
229 }
230 })
231 }
232 }
233
234 func checkAddress(got []plugin.Frame, address uint64, want string) bool {
235 if len(got) != 1 {
236 return false
237 }
238 return got[0].Func == want
239 }
240
241 func TestSetTools(t *testing.T) {
242 // Test that multiple calls work.
243 bu := &Binutils{}
244 bu.SetTools("")
245 bu.SetTools("")
246 }
247
248 func TestSetFastSymbolization(t *testing.T) {
249 // Test that multiple calls work.
250 bu := &Binutils{}
251 bu.SetFastSymbolization(true)
252 bu.SetFastSymbolization(false)
253 }
254
255 func skipUnlessLinuxAmd64(t *testing.T) {
256 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
257 t.Skip("This test only works on x86-64 Linux")
258 }
259 }
260
261 func skipUnlessDarwinAmd64(t *testing.T) {
262 if runtime.GOOS != "darwin" || runtime.GOARCH != "amd64" {
263 t.Skip("This test only works on x86-64 macOS")
264 }
265 }
266
267 func skipUnlessWindowsAmd64(t *testing.T) {
268 if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
269 t.Skip("This test only works on x86-64 Windows")
270 }
271 }
272
273 func testDisasm(t *testing.T, intelSyntax bool) {
274 _, llvmObjdump, buObjdump := findObjdump([]string{""})
275 if !llvmObjdump && !buObjdump {
276 t.Skip("cannot disasm: no objdump tool available")
277 }
278
279 bu := &Binutils{}
280 var testexe string
281 switch runtime.GOOS {
282 case "linux":
283 testexe = "exe_linux_64"
284 case "darwin":
285 testexe = "exe_mac_64"
286 case "windows":
287 testexe = "exe_windows_64.exe"
288 default:
289 t.Skipf("unsupported OS %q", runtime.GOOS)
290 }
291
292 insts, err := bu.Disasm(filepath.Join("testdata", testexe), 0, math.MaxUint64, intelSyntax)
293 if err != nil {
294 t.Fatalf("Disasm: unexpected error %v", err)
295 }
296 mainCount := 0
297 for _, x := range insts {
298 // macOS symbols have a leading underscore.
299 if x.Function == "main" || x.Function == "_main" {
300 mainCount++
301 }
302 }
303 if mainCount == 0 {
304 t.Error("Disasm: found no main instructions")
305 }
306 }
307
308 func TestDisasm(t *testing.T) {
309 if (runtime.GOOS != "linux" && runtime.GOOS != "darwin" && runtime.GOOS != "windows") || runtime.GOARCH != "amd64" {
310 t.Skip("This test only works on x86-64 Linux, macOS or Windows")
311 }
312 testDisasm(t, false)
313 }
314
315 func TestDisasmIntelSyntax(t *testing.T) {
316 if (runtime.GOOS != "linux" && runtime.GOOS != "darwin" && runtime.GOOS != "windows") || runtime.GOARCH != "amd64" {
317 t.Skip("This test only works on x86_64 Linux, macOS or Windows as it tests Intel asm syntax")
318 }
319 testDisasm(t, true)
320 }
321
322 func findSymbol(syms []*plugin.Sym, name string) *plugin.Sym {
323 for _, s := range syms {
324 if slices.Contains(s.Name, name) {
325 return s
326 }
327 }
328 return nil
329 }
330
331 func TestObjFile(t *testing.T) {
332 // If this test fails, check the address for main function in testdata/exe_linux_64
333 // using the command 'nm -n '. Update the hardcoded addresses below to match
334 // the addresses from the output.
335 skipUnlessLinuxAmd64(t)
336 for _, tc := range []struct {
337 desc string
338 start, limit, offset uint64
339 addr uint64
340 }{
341 {"fixed load address", 0x400000, 0x4006fc, 0, 0x40052d},
342 // True user-mode ASLR binaries are ET_DYN rather than ET_EXEC so this case
343 // is a bit artificial except that it approximates the
344 // vmlinux-with-kernel-ASLR case where the binary *is* ET_EXEC.
345 {"simulated ASLR address", 0x500000, 0x5006fc, 0, 0x50052d},
346 } {
347 t.Run(tc.desc, func(t *testing.T) {
348 bu := &Binutils{}
349 f, err := bu.Open(filepath.Join("testdata", "exe_linux_64"), tc.start, tc.limit, tc.offset, "")
350 if err != nil {
351 t.Fatalf("Open: unexpected error %v", err)
352 }
353 defer f.Close()
354 syms, err := f.Symbols(regexp.MustCompile("main"), 0)
355 if err != nil {
356 t.Fatalf("Symbols: unexpected error %v", err)
357 }
358
359 m := findSymbol(syms, "main")
360 if m == nil {
361 t.Fatalf("Symbols: did not find main")
362 }
363 addr, err := f.ObjAddr(tc.addr)
364 if err != nil {
365 t.Fatalf("ObjAddr(%x) failed: %v", tc.addr, err)
366 }
367 if addr != m.Start {
368 t.Errorf("ObjAddr(%x) got %x, want %x", tc.addr, addr, m.Start)
369 }
370 gotFrames, err := f.SourceLine(tc.addr)
371 if err != nil {
372 t.Fatalf("SourceLine: unexpected error %v", err)
373 }
374 wantFrames := []plugin.Frame{
•375 {Func: "main", File: "/tmp/hello.c", Line: 3, StartLine: 0},
376 }
377 if !reflect.DeepEqual(gotFrames, wantFrames) {
378 t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, wantFrames)
379 }
380 })
381 }
382 }
383
384 func TestMachoFiles(t *testing.T) {
385 // If this test fails, check the address for main function in testdata/exe_mac_64
386 // and testdata/lib_mac_64 using addr2line or gaddr2line. Update the
387 // hardcoded addresses below to match the addresses from the output.
388 skipUnlessDarwinAmd64(t)
389
390 // Load `file`, pretending it was mapped at `start`. Then get the symbol
391 // table. Check that it contains the symbol `sym` and that the address
392 // `addr` gives the `expected` stack trace.
393 for _, tc := range []struct {
394 desc string
395 file string
396 start, limit, offset uint64
397 addr uint64
398 sym string
399 expected []plugin.Frame
400 }{
401 {"normal mapping", "exe_mac_64", 0x100000000, math.MaxUint64, 0,
402 0x100000f50, "_main",
403 []plugin.Frame{
404 {Func: "main", File: "/tmp/hello.c", Line: 3, StartLine: 3},
405 }},
406 {"other mapping", "exe_mac_64", 0x200000000, math.MaxUint64, 0,
407 0x200000f50, "_main",
408 []plugin.Frame{
409 {Func: "main", File: "/tmp/hello.c", Line: 3, StartLine: 3},
410 }},
411 {"lib normal mapping", "lib_mac_64", 0, math.MaxUint64, 0,
412 0xfa0, "_bar",
413 []plugin.Frame{
414 {Func: "bar", File: "/tmp/lib.c", Line: 5, StartLine: 5},
415 }},
416 } {
417 t.Run(tc.desc, func(t *testing.T) {
418 bu := &Binutils{}
419 f, err := bu.Open(filepath.Join("testdata", tc.file), tc.start, tc.limit, tc.offset, "")
420 if err != nil {
421 t.Fatalf("Open: unexpected error %v", err)
422 }
423 t.Logf("binutils: %v", bu)
424 if runtime.GOOS == "darwin" && !bu.rep.addr2lineFound && !bu.rep.llvmSymbolizerFound {
425 // On macOS, user needs to install gaddr2line or llvm-symbolizer with
426 // Homebrew, skip the test when the environment doesn't have it
427 // installed.
428 t.Skip("couldn't find addr2line or gaddr2line")
429 }
430 defer f.Close()
431 syms, err := f.Symbols(nil, 0)
432 if err != nil {
433 t.Fatalf("Symbols: unexpected error %v", err)
434 }
435
436 m := findSymbol(syms, tc.sym)
437 if m == nil {
438 t.Fatalf("Symbols: could not find symbol %v", tc.sym)
439 }
440 gotFrames, err := f.SourceLine(tc.addr)
441 if err != nil {
442 t.Fatalf("SourceLine: unexpected error %v", err)
443 }
444 if !reflect.DeepEqual(gotFrames, tc.expected) {
445 t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, tc.expected)
446 }
447 })
448 }
449 }
450
451 func TestLLVMSymbolizer(t *testing.T) {
452 if runtime.GOOS != "linux" {
453 t.Skip("testtdata/llvm-symbolizer has only been tested on linux")
454 }
455
456 cmd := filepath.Join("testdata", "fake-llvm-symbolizer")
457 for _, c := range []struct {
458 addr uint64
459 isData bool
460 frames []plugin.Frame
461 }{
462 {0x10, false, []plugin.Frame{
463 {Func: "Inlined_0x10", File: "foo.h", Line: 0, Column: 0, StartLine: 0},
464 {Func: "Func_0x10", File: "foo.c", Line: 2, Column: 1, StartLine: 2},
465 }},
466 {0x20, true, []plugin.Frame{
467 {Func: "foo_0x20", File: "0x20 8"},
468 }},
469 } {
470 desc := fmt.Sprintf("Code %x", c.addr)
471 if c.isData {
472 desc = fmt.Sprintf("Data %x", c.addr)
473 }
474 t.Run(desc, func(t *testing.T) {
475 symbolizer, err := newLLVMSymbolizer(cmd, "foo", 0, c.isData)
476 if err != nil {
477 t.Fatalf("newLLVMSymbolizer: unexpected error %v", err)
478 }
479 defer symbolizer.rw.close()
480
481 frames, err := symbolizer.addrInfo(c.addr)
482 if err != nil {
483 t.Fatalf("LLVM: unexpected error %v", err)
484 }
485 if !reflect.DeepEqual(frames, c.frames) {
486 t.Errorf("LLVM: expect %v; got %v\n", c.frames, frames)
487 }
488 })
489 }
490 }
491
492 func TestPEFile(t *testing.T) {
493 // If this test fails, check the address for main function in testdata/exe_windows_64.exe
494 // using the command 'nm -n '. Update the hardcoded addresses below to match
495 // the addresses from the output.
496 skipUnlessWindowsAmd64(t)
497 for _, tc := range []struct {
498 desc string
499 start, limit, offset uint64
500 addr uint64
501 }{
502 {"fake mapping", 0, math.MaxUint64, 0, 0x140001594},
503 {"fixed load address", 0x140000000, 0x140002000, 0, 0x140001594},
504 {"simulated ASLR address", 0x150000000, 0x150002000, 0, 0x150001594},
505 } {
506 t.Run(tc.desc, func(t *testing.T) {
507 bu := &Binutils{}
508 f, err := bu.Open(filepath.Join("testdata", "exe_windows_64.exe"), tc.start, tc.limit, tc.offset, "")
509 if err != nil {
510 t.Fatalf("Open: unexpected error %v", err)
511 }
512 defer f.Close()
513 syms, err := f.Symbols(regexp.MustCompile("main"), 0)
514 if err != nil {
515 t.Fatalf("Symbols: unexpected error %v", err)
516 }
517
518 m := findSymbol(syms, "main")
519 if m == nil {
520 t.Fatalf("Symbols: did not find main")
521 }
522 addr, err := f.ObjAddr(tc.addr)
523 if err != nil {
524 t.Fatalf("ObjAddr(%x) failed: %v", tc.addr, err)
525 }
526 if addr != m.Start {
527 t.Errorf("ObjAddr(%x) got %x, want %x", tc.addr, addr, m.Start)
528 }
529 gotFrames, err := f.SourceLine(tc.addr)
530 if err != nil {
531 t.Fatalf("SourceLine: unexpected error %v", err)
532 }
533 wantFrames := []plugin.Frame{
534 {Func: "main", File: "hello.c", Line: 3, Column: 12, StartLine: 3},
535 }
536 if !reflect.DeepEqual(gotFrames, wantFrames) {
537 t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, wantFrames)
538 }
539 })
540 }
541 }
542
543 func TestOpenMalformedELF(t *testing.T) {
544 // Test that opening a malformed ELF file will report an error containing
545 // the word "ELF".
546 bu := &Binutils{}
547 _, err := bu.Open(filepath.Join("testdata", "malformed_elf"), 0, 0, 0, "")
548 if err == nil {
549 t.Fatalf("Open: unexpected success")
550 }
551
552 if !strings.Contains(err.Error(), "ELF") {
553 t.Errorf("Open: got %v, want error containing 'ELF'", err)
554 }
555 }
556
557 func TestOpenMalformedMachO(t *testing.T) {
558 // Test that opening a malformed Mach-O file will report an error containing
559 // the word "Mach-O".
560 bu := &Binutils{}
561 _, err := bu.Open(filepath.Join("testdata", "malformed_macho"), 0, 0, 0, "")
562 if err == nil {
563 t.Fatalf("Open: unexpected success")
564 }
565
566 if !strings.Contains(err.Error(), "Mach-O") {
567 t.Errorf("Open: got %v, want error containing 'Mach-O'", err)
568 }
569 }
570
571 func TestObjdumpVersionChecks(t *testing.T) {
572 // Test that the objdump version strings are parsed properly.
573 type testcase struct {
574 desc string
575 os string
576 ver string
577 want bool
578 }
579
580 for _, tc := range []testcase{
581 {
582 desc: "Valid Apple LLVM version string with usable version",
583 os: "darwin",
584 ver: "Apple LLVM version 11.0.3 (clang-1103.0.32.62)\nOptimized build.",
585 want: true,
586 },
587 {
588 desc: "Valid Apple LLVM version string with unusable version",
589 os: "darwin",
590 ver: "Apple LLVM version 10.0.0 (clang-1000.11.45.5)\nOptimized build.",
591 want: false,
592 },
593 {
594 desc: "Invalid Apple LLVM version string with usable version",
595 os: "darwin",
596 ver: "Apple LLVM versions 11.0.3 (clang-1103.0.32.62)\nOptimized build.",
597 want: false,
598 },
599 {
600 desc: "Valid LLVM version string with usable version",
601 os: "linux",
602 ver: "LLVM (http://llvm.org/):\nLLVM version 9.0.1\n\nOptimized build.",
603 want: true,
604 },
605 {
606 desc: "Valid LLVM version string with unusable version",
607 os: "linux",
608 ver: "LLVM (http://llvm.org/):\nLLVM version 6.0.1\n\nOptimized build.",
609 want: false,
610 },
611 {
612 desc: "Invalid LLVM version string with usable version",
613 os: "linux",
614 ver: "LLVM (http://llvm.org/):\nLLVM versions 9.0.1\n\nOptimized build.",
615 want: false,
616 },
617 {
618 desc: "Valid LLVM objdump version string with trunk",
619 os: runtime.GOOS,
620 ver: "LLVM (http://llvm.org/):\nLLVM version custom-trunk 124ffeb592a00bfe\nOptimized build.",
621 want: true,
622 },
623 {
624 desc: "Invalid LLVM objdump version string with trunk",
625 os: runtime.GOOS,
626 ver: "LLVM (http://llvm.org/):\nLLVM version custom-trank 124ffeb592a00bfe\nOptimized build.",
627 want: false,
628 },
629 {
630 desc: "Invalid LLVM objdump version string with trunk",
631 os: runtime.GOOS,
632 ver: "LLVM (http://llvm.org/):\nllvm version custom-trunk 124ffeb592a00bfe\nOptimized build.",
633 want: false,
634 },
635 } {
636 if runtime.GOOS == tc.os {
637 if got := isLLVMObjdump(tc.ver); got != tc.want {
638 t.Errorf("%v: got %v, want %v", tc.desc, got, tc.want)
639 }
640 }
641 }
642 for _, tc := range []testcase{
643 {
644 desc: "Valid GNU objdump version string",
645 ver: "GNU objdump (GNU Binutils) 2.34\nCopyright (C) 2020 Free Software Foundation, Inc.",
646 want: true,
647 },
648 {
649 desc: "Invalid GNU objdump version string",
650 ver: "GNU nm (GNU Binutils) 2.34\nCopyright (C) 2020 Free Software Foundation, Inc.",
651 want: false,
652 },
653 } {
654 if got := isBuObjdump(tc.ver); got != tc.want {
655 t.Errorf("%v: got %v, want %v", tc.desc, got, tc.want)
656 }
657 }
658 }
659
660 func TestComputeBase(t *testing.T) {
661 realELFOpen := elfOpen
662 defer func() {
663 elfOpen = realELFOpen
664 }()
665
666 tinyExecFile := &elf.File{
667 FileHeader: elf.FileHeader{Type: elf.ET_EXEC},
668 Progs: []*elf.Prog{
669 {ProgHeader: elf.ProgHeader{Type: elf.PT_PHDR, Flags: elf.PF_R | elf.PF_X, Off: 0x40, Vaddr: 0x400040, Paddr: 0x400040, Filesz: 0x1f8, Memsz: 0x1f8, Align: 8}},
670 {ProgHeader: elf.ProgHeader{Type: elf.PT_INTERP, Flags: elf.PF_R, Off: 0x238, Vaddr: 0x400238, Paddr: 0x400238, Filesz: 0x1c, Memsz: 0x1c, Align: 1}},
671 {ProgHeader: elf.ProgHeader{Type: elf.PT_LOAD, Flags: elf.PF_R | elf.PF_X, Off: 0, Vaddr: 0, Paddr: 0, Filesz: 0xc80, Memsz: 0xc80, Align: 0x200000}},
672 {ProgHeader: elf.ProgHeader{Type: elf.PT_LOAD, Flags: elf.PF_R | elf.PF_W, Off: 0xc80, Vaddr: 0x200c80, Paddr: 0x200c80, Filesz: 0x1f0, Memsz: 0x1f0, Align: 0x200000}},
673 },
674 }
675 tinyBadBSSExecFile := &elf.File{
676 FileHeader: elf.FileHeader{Type: elf.ET_EXEC},
677 Progs: []*elf.Prog{
678 {ProgHeader: elf.ProgHeader{Type: elf.PT_PHDR, Flags: elf.PF_R | elf.PF_X, Off: 0x40, Vaddr: 0x400040, Paddr: 0x400040, Filesz: 0x1f8, Memsz: 0x1f8, Align: 8}},
679 {ProgHeader: elf.ProgHeader{Type: elf.PT_INTERP, Flags: elf.PF_R, Off: 0x238, Vaddr: 0x400238, Paddr: 0x400238, Filesz: 0x1c, Memsz: 0x1c, Align: 1}},
680 {ProgHeader: elf.ProgHeader{Type: elf.PT_LOAD, Flags: elf.PF_R | elf.PF_X, Off: 0, Vaddr: 0, Paddr: 0, Filesz: 0xc80, Memsz: 0xc80, Align: 0x200000}},
681 {ProgHeader: elf.ProgHeader{Type: elf.PT_LOAD, Flags: elf.PF_R | elf.PF_W, Off: 0xc80, Vaddr: 0x200c80, Paddr: 0x200c80, Filesz: 0x100, Memsz: 0x1f0, Align: 0x200000}},
682 {ProgHeader: elf.ProgHeader{Type: elf.PT_LOAD, Flags: elf.PF_R | elf.PF_W, Off: 0xd80, Vaddr: 0x400d80, Paddr: 0x400d80, Filesz: 0x90, Memsz: 0x90, Align: 0x200000}},
683 },
684 }
685
686 for _, tc := range []struct {
687 desc string
688 file *elf.File
689 openErr error
690 mapping *elfMapping
691 addr uint64
692 wantError bool
693 wantBase uint64
694 wantIsData bool
695 }{
696 {
697 desc: "no elf mapping, no error",
698 mapping: nil,
699 addr: 0x1000,
700 wantBase: 0,
701 wantIsData: false,
702 },
703 {
704 desc: "address outside mapping bounds means error",
705 file: &elf.File{},
706 mapping: &elfMapping{start: 0x2000, limit: 0x5000, offset: 0x1000},
707 addr: 0x1000,
708 wantError: true,
709 },
710 {
711 desc: "elf.Open failing means error",
712 file: &elf.File{FileHeader: elf.FileHeader{Type: elf.ET_EXEC}},
713 openErr: errors.New("elf.Open failed"),
714 mapping: &elfMapping{start: 0x2000, limit: 0x5000, offset: 0x1000},
715 addr: 0x4000,
716 wantError: true,
717 },
718 {
719 desc: "no loadable segments, no error",
720 file: &elf.File{FileHeader: elf.FileHeader{Type: elf.ET_EXEC}},
721 mapping: &elfMapping{start: 0x2000, limit: 0x5000, offset: 0x1000},
722 addr: 0x4000,
723 wantBase: 0,
724 wantIsData: false,
725 },
726 {
727 desc: "unsupported executable type, Get Base returns error",
728 file: &elf.File{FileHeader: elf.FileHeader{Type: elf.ET_NONE}},
729 mapping: &elfMapping{start: 0x2000, limit: 0x5000, offset: 0x1000},
730 addr: 0x4000,
731 wantError: true,
732 },
733 {
734 desc: "tiny file select executable segment by offset",
735 file: tinyExecFile,
736 mapping: &elfMapping{start: 0x5000000, limit: 0x5001000, offset: 0x0},
737 addr: 0x5000c00,
738 wantBase: 0x5000000,
739 wantIsData: false,
740 },
741 {
742 desc: "tiny file select data segment by offset",
743 file: tinyExecFile,
744 mapping: &elfMapping{start: 0x5200000, limit: 0x5201000, offset: 0x0},
745 addr: 0x5200c80,
746 wantBase: 0x5000000,
747 wantIsData: true,
748 },
749 {
750 desc: "tiny file offset outside any segment means error",
751 file: tinyExecFile,
752 mapping: &elfMapping{start: 0x5200000, limit: 0x5201000, offset: 0x0},
753 addr: 0x5200e70,
754 wantError: true,
755 },
756 {
757 desc: "tiny file with bad BSS segment selects data segment by offset in initialized section",
758 file: tinyBadBSSExecFile,
759 mapping: &elfMapping{start: 0x5200000, limit: 0x5201000, offset: 0x0},
760 addr: 0x5200d79,
761 wantBase: 0x5000000,
762 wantIsData: true,
763 },
764 {
765 desc: "tiny file with bad BSS segment with offset in uninitialized section means error",
766 file: tinyBadBSSExecFile,
767 mapping: &elfMapping{start: 0x5200000, limit: 0x5201000, offset: 0x0},
768 addr: 0x5200d80,
769 wantError: true,
770 },
771 } {
772 t.Run(tc.desc, func(t *testing.T) {
773 elfOpen = func(_ string) (*elf.File, error) {
774 return tc.file, tc.openErr
775 }
776 f := file{m: tc.mapping}
777 err := f.computeBase(tc.addr)
778 if (err != nil) != tc.wantError {
779 t.Errorf("got error %v, want any error=%v", err, tc.wantError)
780 }
781 if err != nil {
782 return
783 }
784 if f.base != tc.wantBase {
785 t.Errorf("got base %x, want %x", f.base, tc.wantBase)
786 }
787 if f.isData != tc.wantIsData {
788 t.Errorf("got isData %v, want %v", f.isData, tc.wantIsData)
789 }
790 })
791 }
792 }
793
794 func TestELFObjAddr(t *testing.T) {
795 // The exe_linux_64 has two loadable program headers:
796 // LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
797 // 0x00000000000006fc 0x00000000000006fc R E 0x200000
798 // LOAD 0x0000000000000e10 0x0000000000600e10 0x0000000000600e10
799 // 0x0000000000000230 0x0000000000000238 RW 0x200000
800 name := filepath.Join("testdata", "exe_linux_64")
801
802 for _, tc := range []struct {
803 desc string
804 start, limit, offset uint64
805 wantOpenError bool
806 addr uint64
807 wantObjAddr uint64
808 wantAddrError bool
809 }{
810 {"exec mapping, good address", 0x5400000, 0x5401000, 0, false, 0x5400400, 0x400400, false},
811 {"exec mapping, address outside segment", 0x5400000, 0x5401000, 0, false, 0x5400800, 0, true},
812 {"short data mapping, good address", 0x5600e00, 0x5602000, 0xe00, false, 0x5600e10, 0x600e10, false},
813 {"short data mapping, address outside segment", 0x5600e00, 0x5602000, 0xe00, false, 0x5600e00, 0x600e00, false},
814 {"page aligned data mapping, good address", 0x5600000, 0x5602000, 0, false, 0x5601000, 0x601000, false},
815 {"page aligned data mapping, address outside segment", 0x5600000, 0x5602000, 0, false, 0x5601048, 0, true},
816 {"bad file offset, no matching segment", 0x5600000, 0x5602000, 0x2000, false, 0x5600e10, 0, true},
817 {"large mapping size, match by sample offset", 0x5600000, 0x5603000, 0, false, 0x5600e10, 0x600e10, false},
818 } {
819 t.Run(tc.desc, func(t *testing.T) {
820 b := binrep{}
821 o, err := b.openELF(name, tc.start, tc.limit, tc.offset, "")
822 if (err != nil) != tc.wantOpenError {
823 t.Errorf("openELF got error %v, want any error=%v", err, tc.wantOpenError)
824 }
825 if err != nil {
826 return
827 }
828 got, err := o.ObjAddr(tc.addr)
829 if (err != nil) != tc.wantAddrError {
830 t.Errorf("ObjAddr got error %v, want any error=%v", err, tc.wantAddrError)
831 }
832 if err != nil {
833 return
834 }
835 if got != tc.wantObjAddr {
836 t.Errorf("got ObjAddr %x; want %x\n", got, tc.wantObjAddr)
837 }
838 })
839 }
840 }
841
842 type buf struct {
843 data []byte
844 }
845
846 // write appends a null-terminated string and returns its starting index.
847 func (b *buf) write(s string) uint32 {
848 res := uint32(len(b.data))
849 b.data = append(b.data, s...)
850 b.data = append(b.data, '\x00')
851 return res
852 }
853
854 // fakeELFFile generates a minimal valid ELF file, with fake .head.text and
855 // .text sections, and their corresponding _text and _stext start symbols,
856 // mimicking a kernel vmlinux image.
857 func fakeELFFile(t *testing.T) *elf.File {
858 var (
859 sizeHeader64 = binary.Size(elf.Header64{})
860 sizeProg64 = binary.Size(elf.Prog64{})
861 sizeSection64 = binary.Size(elf.Section64{})
862 )
863
864 const (
865 textAddr = 0xffff000010080000
866 stextAddr = 0xffff000010081000
867 )
868
869 // Generate magic to identify as an ELF file.
870 var ident [16]uint8
871 ident[0] = '\x7f'
872 ident[1] = 'E'
873 ident[2] = 'L'
874 ident[3] = 'F'
875 ident[elf.EI_CLASS] = uint8(elf.ELFCLASS64)
876 ident[elf.EI_DATA] = uint8(elf.ELFDATA2LSB)
877 ident[elf.EI_VERSION] = uint8(elf.EV_CURRENT)
878 ident[elf.EI_OSABI] = uint8(elf.ELFOSABI_NONE)
879
880 // A single program header, containing code and starting at the _text address.
881 progs := []elf.Prog64{{
882 Type: uint32(elf.PT_LOAD), Flags: uint32(elf.PF_R | elf.PF_X), Off: 0x10000, Vaddr: textAddr, Paddr: textAddr, Filesz: 0x1234567, Memsz: 0x1234567, Align: 0x10000}}
883
884 symNames := buf{}
885 syms := []elf.Sym64{
886 {}, // first symbol empty by convention
887 {Name: symNames.write("_text"), Info: 0, Other: 0, Shndx: 0, Value: textAddr, Size: 0},
888 {Name: symNames.write("_stext"), Info: 0, Other: 0, Shndx: 0, Value: stextAddr, Size: 0},
889 }
890
891 const numSections = 5
892 // We'll write `textSize` zero bytes as contents of the .head.text and .text sections.
893 const textSize = 16
894 // Offset of section contents in the byte stream -- after header, program headers, and section headers.
895 sectionsStart := uint64(sizeHeader64 + len(progs)*sizeProg64 + numSections*sizeSection64)
896
897 secNames := buf{}
898 sections := [numSections]elf.Section64{
899 {Name: secNames.write(".head.text"), Type: uint32(elf.SHT_PROGBITS), Flags: uint64(elf.SHF_ALLOC | elf.SHF_EXECINSTR), Addr: textAddr, Off: sectionsStart, Size: textSize, Link: 0, Info: 0, Addralign: 2048, Entsize: 0},
900 {Name: secNames.write(".text"), Type: uint32(elf.SHT_PROGBITS), Flags: uint64(elf.SHF_ALLOC | elf.SHF_EXECINSTR), Addr: stextAddr, Off: sectionsStart + textSize, Size: textSize, Link: 0, Info: 0, Addralign: 2048, Entsize: 0},
901 {Name: secNames.write(".symtab"), Type: uint32(elf.SHT_SYMTAB), Flags: 0, Addr: 0, Off: sectionsStart + 2*textSize, Size: uint64(len(syms) * elf.Sym64Size), Link: 3 /*index of .strtab*/, Info: 0, Addralign: 8, Entsize: elf.Sym64Size},
902 {Name: secNames.write(".strtab"), Type: uint32(elf.SHT_STRTAB), Flags: 0, Addr: 0, Off: sectionsStart + 2*textSize + uint64(len(syms)*elf.Sym64Size), Size: uint64(len(symNames.data)), Link: 0, Info: 0, Addralign: 1, Entsize: 0},
903 {Name: secNames.write(".shstrtab"), Type: uint32(elf.SHT_STRTAB), Flags: 0, Addr: 0, Off: sectionsStart + 2*textSize + uint64(len(syms)*elf.Sym64Size+len(symNames.data)), Size: uint64(len(secNames.data)), Link: 0, Info: 0, Addralign: 1, Entsize: 0},
904 }
905
906 hdr := elf.Header64{
907 Ident: ident,
908 Type: uint16(elf.ET_DYN),
909 Machine: uint16(elf.EM_AARCH64),
910 Version: uint32(elf.EV_CURRENT),
911 Entry: textAddr,
912 Phoff: uint64(sizeHeader64),
913 Shoff: uint64(sizeHeader64 + len(progs)*sizeProg64),
914 Flags: 0,
915 Ehsize: uint16(sizeHeader64),
916 Phentsize: uint16(sizeProg64),
917 Phnum: uint16(len(progs)),
918 Shentsize: uint16(sizeSection64),
919 Shnum: uint16(len(sections)),
920 Shstrndx: 4, // index of .shstrtab
921 }
922
923 // Serialize all headers and sections into a single binary stream.
924 var data bytes.Buffer
925 for i, b := range []interface{}{hdr, progs, sections, [textSize]byte{}, [textSize]byte{}, syms, symNames.data, secNames.data} {
926 err := binary.Write(&data, binary.LittleEndian, b)
927 if err != nil {
928 t.Fatalf("Write(%v) got err %v, want nil", i, err)
929 }
930 }
931
932 // ... and parse it as and ELF file.
933 ef, err := elf.NewFile(bytes.NewReader(data.Bytes()))
934 if err != nil {
935 t.Fatalf("elf.NewFile got err %v, want nil", err)
936 }
937 return ef
938 }
939
940 func TestELFKernelOffset(t *testing.T) {
941 realELFOpen := elfOpen
942 defer func() {
943 elfOpen = realELFOpen
944 }()
945
946 wantAddr := uint64(0xffff000010082000)
947 elfOpen = func(_ string) (*elf.File, error) {
948 return fakeELFFile(t), nil
949 }
950
951 for _, tc := range []struct {
952 name string
953 relocationSymbol string
954 start uint64
955 }{
956 {"text", "_text", 0xffff000020080000},
957 {"stext", "_stext", 0xffff000020081000},
958 } {
959
960 b := binrep{}
961 o, err := b.openELF("vmlinux", tc.start, 0xffffffffffffffff, tc.start, tc.relocationSymbol)
962 if err != nil {
963 t.Errorf("%v: openELF got error %v, want nil", tc.name, err)
964 continue
965 }
966
967 addr, err := o.ObjAddr(0xffff000020082000)
968 if err != nil {
969 t.Errorf("%v: ObjAddr got err %v, want nil", tc.name, err)
970 continue
971 }
972 if addr != wantAddr {
973 t.Errorf("%v: ObjAddr got %x, want %x", tc.name, addr, wantAddr)
974 }
975
976 }
977 }