/
string_table.go
58 lines (52 loc) · 1.16 KB
/
string_table.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
package elf
import (
"bytes"
"errors"
"io"
"strings"
)
type StringTable struct {
data []byte
}
func NewStringTable(data []byte) *StringTable {
return &StringTable{data}
}
func (s *StringTable) String() string {
result := []string{}
current := []byte{}
for _, b := range s.data {
if b == '\x00' {
result = append(result, string(current))
current = []byte{}
} else {
current = append(current, b)
}
}
return strings.Join(result, "\n")
}
func ParseStringTable(header *ELFHeader, sectionHeader *SectionHeader, r *bytes.Reader) (*StringTable, error) {
_, err := r.Seek(int64(sectionHeader.Offset), io.SeekStart)
if err != nil {
return nil, err
}
data := make([]byte, sectionHeader.Size)
n, err := r.Read(data)
if err != nil {
return nil, err
}
if n != int(sectionHeader.Size) {
return nil, errors.New("Mismatching string table size")
}
return NewStringTable(data), nil
}
func (s *StringTable) GetString(ix int) (string, error) {
result := []byte{}
if ix >= len(s.data) {
return "", errors.New("index out of bounds")
}
for ix < len(s.data) && s.data[ix] != 0 {
result = append(result, s.data[ix])
ix++
}
return string(result), nil
}