-
Notifications
You must be signed in to change notification settings - Fork 0
/
elf.go
471 lines (414 loc) · 11.9 KB
/
elf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package file
import (
"encoding/binary"
"fmt"
"github.com/vsoch/gosmeagle/pkg/debug/dwarf"
"github.com/vsoch/gosmeagle/pkg/debug/elf"
"io"
"log"
"reflect"
"unsafe"
)
type ElfFile struct {
elf *elf.File
}
// Parse dwarf into the file object
func (f *ElfFile) ParseDwarf() map[string]map[string]DwarfEntry {
dwf, err := f.Dwarf()
if err != nil {
log.Fatalf("Error parsing dwarf %v", err)
}
return ParseDwarf(dwf)
}
func OpenElf(r io.ReaderAt) (rawFile, error) {
f, err := elf.NewFile(r)
if err != nil {
return nil, err
}
return &ElfFile{f}, nil
}
// GetRelocations from te entire elf file - yes this is ugly and redundant, please improve!
func (f *ElfFile) GetRelocations() []Relocation {
elfsyms, _ := f.elf.Symbols()
syms, _ := f.parseSymbols(elfsyms)
elfsyms, _ = f.elf.DynamicSymbols()
dynamicSyms, _ := f.parseSymbols(elfsyms)
// Offset, Info, Type, Symbol Value, Symbol Name
relocations := []Relocation{}
// idx is section index
for idx, s := range f.elf.Sections {
// First top level - section32 vs section64
switch f.elf.Class {
case elf.ELFCLASS32:
switch s.Type {
case elf.SHT_REL:
var rel elf.Rela32
numRels := s.Size / uint64(unsafe.Sizeof(rel))
relocs := make([]elf.Rel32, numRels)
err := binary.Read(s.Open(), f.elf.ByteOrder, relocs)
if err != nil {
log.Fatalf("%x", err)
}
for _, r := range relocs {
offset := r.Off
relocType := elf.R_TYPE32(r.Info)
sym := elf.R_SYM32(r.Info)
info := elf.R_INFO(sym, relocType)
relocName := getRelocationType(relocType, f.elf.Machine)
var symName string
var symValue uint64
secIdx := f.elf.Sections[idx].Link
switch f.elf.Sections[secIdx].Name {
case ".dynsym", ".dynstr":
symbol := dynamicSyms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
case ".symtab":
symbol := syms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
default:
fmt.Printf("Cannot find section name", f.elf.Sections[secIdx].Name)
continue
}
newReloc := Relocation{SymbolName: symName, Offset: uint64(offset), SymbolValue: symValue, RelocType: relocName, Info: info}
relocations = append(relocations, newReloc)
}
case elf.SHT_RELA:
var rel elf.Rela32
numRels := s.Size / uint64(unsafe.Sizeof(rel))
relocs := make([]elf.Rela32, numRels)
err := binary.Read(s.Open(), f.elf.ByteOrder, relocs)
if err != nil {
log.Fatalf("%x", err)
}
for _, r := range relocs {
offset := r.Off
relocType := elf.R_TYPE32(r.Info)
sym := elf.R_SYM32(r.Info)
info := elf.R_INFO(sym, relocType)
relocName := getRelocationType(relocType, f.elf.Machine)
var symName string
var symValue uint64
secIdx := f.elf.Sections[idx].Link
switch f.elf.Sections[secIdx].Name {
case ".dynsym", ".dynstr":
symbol := dynamicSyms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
case ".symtab":
symbol := syms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
default:
fmt.Printf("Cannot find section name", f.elf.Sections[secIdx].Name)
continue
}
newReloc := Relocation{SymbolName: symName, Offset: uint64(offset), SymbolValue: symValue, RelocType: relocName, Info: info}
relocations = append(relocations, newReloc)
}
}
case elf.ELFCLASS64:
switch s.Type {
case elf.SHT_REL:
var rel elf.Rela64
numRels := s.Size / uint64(unsafe.Sizeof(rel))
relocs := make([]elf.Rel64, numRels)
err := binary.Read(s.Open(), f.elf.ByteOrder, relocs)
if err != nil {
log.Fatalf("%x", err)
}
for _, r := range relocs {
offset := r.Off
relocType := elf.R_TYPE64(r.Info)
sym := elf.R_SYM64(r.Info)
info := elf.R_INFO(sym, relocType)
relocName := getRelocationType(relocType, f.elf.Machine)
var symName string
var symValue uint64
secIdx := f.elf.Sections[idx].Link
switch f.elf.Sections[secIdx].Name {
case ".dynsym", ".dynstr":
symbol := dynamicSyms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
case ".symtab":
symbol := syms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
default:
fmt.Printf("Cannot find section name", f.elf.Sections[secIdx].Name)
continue
}
newReloc := Relocation{SymbolName: symName, Offset: uint64(offset), SymbolValue: symValue, RelocType: relocName, Info: info}
relocations = append(relocations, newReloc)
}
case elf.SHT_RELA:
var rel elf.Rela64
numRels := s.Size / uint64(unsafe.Sizeof(rel))
relocs := make([]elf.Rela64, numRels)
err := binary.Read(s.Open(), f.elf.ByteOrder, relocs)
if err != nil {
log.Fatalf("%x", err)
}
for _, r := range relocs {
offset := r.Off
relocType := elf.R_TYPE64(r.Info)
sym := elf.R_SYM64(r.Info)
info := elf.R_INFO(sym, relocType)
relocName := getRelocationType(relocType, f.elf.Machine)
var symName string
var symValue uint64
secIdx := f.elf.Sections[idx].Link
switch f.elf.Sections[secIdx].Name {
case ".dynsym", ".dynstr":
symbol := dynamicSyms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
case ".symtab":
symbol := syms[sym-1]
symName = symbol.GetName()
symValue = symbol.GetAddress()
default:
fmt.Printf("Cannot find section name", f.elf.Sections[secIdx].Name)
continue
}
newReloc := Relocation{SymbolName: symName, Offset: uint64(offset), SymbolValue: symValue, RelocType: relocName, Info: info}
relocations = append(relocations, newReloc)
}
}
default:
log.Fatalf("Unknown section type.", reflect.TypeOf(s))
}
}
return relocations
}
// An Elf Symbol found in a file (e.g., ELF?)
type ElfSymbol struct {
Name string // symbol name
Address uint64 // virtual address of symbol
Size int64 // size in bytes
Code rune // nm code (T for text, D for data, and so on)
Type string // string of type calculated from s.Info
Binding string // binding calculated from s.Info
Library string // Library name
Version string // Library name
Relocations []Relocation // in increasing Addr order
Original elf.Symbol // hold the original symbol
ArchInt int
}
// And functions required for an elf symbol
func (s *ElfSymbol) GetName() string {
return s.Name
}
func (s *ElfSymbol) GetLibrary() string {
return s.Library
}
func (s *ElfSymbol) GetVersion() string {
return s.Version
}
func (s *ElfSymbol) GetIntArch() int {
return s.ArchInt
}
// GetDirection determines if we have import/export based on definition
func (s *ElfSymbol) GetDirection() string {
// imports are undefined (U)
direction := "export"
if s.GetCode() == 'U' {
direction = "import"
}
return direction
}
func (s *ElfSymbol) GetAddress() uint64 {
return s.Address
}
func (s *ElfSymbol) GetSize() int64 {
return s.Size
}
func (s *ElfSymbol) GetCode() rune {
return s.Code
}
func (s *ElfSymbol) GetType() string {
return s.Type
}
func (s *ElfSymbol) GetBinding() string {
return s.Binding
}
func (s *ElfSymbol) GetRelocations() []Relocation {
return s.Relocations
}
func (s *ElfSymbol) GetOriginal() interface{} {
return s.Original
}
// getSymbolType from a s.Info, which also can derive the binding
// https://refspecs.linuxfoundation.org/elf/elf.pdf section 1-18
func getSymbolType(s elf.Symbol) string {
symType := int(s.Info) & 0xf
// Return a human friendly string (this is what Type expects)
switch symType {
case 0:
return "STT_NOTYPE"
case 1:
return "STT_OBJECT"
case 2:
return "STT_FUNC"
case 4:
return "STT_FILE"
case 13:
return "STT_LOPROC"
case 15:
return "STT_HIPROC"
}
return "UNKNOWN"
}
// getSymbolBinding from s.Info
func getSymbolBinding(s elf.Symbol) string {
binding := s.Info >> 4
switch binding {
case 0:
return "STB_LOCAL"
case 1:
return "STB_GLOBAL"
case 2:
return "STB_WEAK"
case 13:
return "STB_LOPROC"
case 15:
return "STB_HIPROC"
}
return "UNKNOWN"
}
// setSymbolCode for the symbol and file
func setSymbolCode(s *elf.Symbol, symbol *ElfSymbol, f *ElfFile) {
switch s.Section {
case elf.SHN_UNDEF:
symbol.Code = 'U'
case elf.SHN_COMMON:
symbol.Code = 'B'
default:
i := int(s.Section)
if i < 0 || i >= len(f.elf.Sections) {
break
}
sect := f.elf.Sections[i]
switch sect.Flags & (elf.SHF_WRITE | elf.SHF_ALLOC | elf.SHF_EXECINSTR) {
case elf.SHF_ALLOC | elf.SHF_EXECINSTR:
symbol.Code = 'T'
case elf.SHF_ALLOC:
symbol.Code = 'R'
case elf.SHF_ALLOC | elf.SHF_WRITE:
symbol.Code = 'D'
}
}
if elf.ST_BIND(s.Info) == elf.STB_LOCAL {
symbol.Code += 'a' - 'A'
}
}
// Get dynamic symbols for the elf file
func (f *ElfFile) DynamicSymbols() ([]Symbol, error) {
elfSyms, err := f.elf.DynamicSymbols()
if err != nil {
return nil, err
}
return f.parseSymbols(elfSyms)
}
// parseSymbols is a shared function for parsing dynamic or all symbols
func (f *ElfFile) parseSymbols(elfSyms []elf.Symbol) ([]Symbol, error) {
// TODO look up imported symbols to give direction
// https://cs.opensource.google/go/go/+/master:src/debug/elf/file.go;l=1285?q=DynamicSymbols&ss=go%2Fgo
var syms []Symbol
for _, s := range elfSyms {
// Convert the s.Info (we can use to calculate binding and type) to unsigned int, then string
symType := getSymbolType(s)
binding := getSymbolBinding(s)
// Assume to start we don't know the code
symbol := ElfSymbol{Address: s.Value, Type: symType, Binding: binding, Version: s.Version,
Name: s.Name, Size: int64(s.Size), Code: '?', Original: s, Library: s.Library, ArchInt: int(f.elf.Machine)}
// Add the correct code for the symbol
setSymbolCode(&s, &symbol, f)
syms = append(syms, &symbol)
}
return syms, nil
}
// Get all symbols for the elf file (but not imported)
func (f *ElfFile) Symbols() ([]Symbol, error) {
elfSyms, err := f.elf.Symbols()
if err != nil {
return nil, err
}
return f.parseSymbols(elfSyms)
}
// getString extracts a string from an ELF string table.
// https://cs.opensource.google/go/go/+/master:src/debug/elf/file.go;drc=master;l=576
func getString(section []byte, start int) (string, bool) {
if start < 0 || start >= len(section) {
return "", false
}
for end := start; end < len(section); end++ {
if section[end] == 0 {
return string(section[start:end]), true
}
}
return "", false
}
// PCLineTable is renamed from pcln
func (f *ElfFile) PCLineTable() (textStart uint64, symtab, pclntab []byte, err error) {
if sect := f.elf.Section(".text"); sect != nil {
textStart = sect.Addr
}
if sect := f.elf.Section(".gosymtab"); sect != nil {
if symtab, err = sect.Data(); err != nil {
return 0, nil, nil, err
}
}
if sect := f.elf.Section(".gopclntab"); sect != nil {
if pclntab, err = sect.Data(); err != nil {
return 0, nil, nil, err
}
}
return textStart, symtab, pclntab, nil
}
// Return text section of the ELF file
func (f *ElfFile) text() (textStart uint64, text []byte, err error) {
sect := f.elf.Section(".text")
if sect == nil {
return 0, nil, fmt.Errorf("text section not found")
}
textStart = sect.Addr
text, err = sect.Data()
return
}
// GoArch returns the architecture of the elf file
func (f *ElfFile) GoArch() string {
switch f.elf.Machine {
case elf.EM_386:
return "386"
case elf.EM_X86_64:
return "amd64"
case elf.EM_ARM:
return "arm"
case elf.EM_AARCH64:
return "arm64"
case elf.EM_PPC64:
if f.elf.ByteOrder == binary.LittleEndian {
return "ppc64le"
}
return "ppc64"
case elf.EM_S390:
return "s390x"
}
return ""
}
// Return integer of
// loadAddress returns the load address
func (f *ElfFile) loadAddress() (uint64, error) {
for _, p := range f.elf.Progs {
if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 {
return p.Vaddr, nil
}
}
return 0, fmt.Errorf("unknown load address")
}
func (f *ElfFile) Dwarf() (*dwarf.Data, error) {
return f.elf.DWARF()
}