-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
220 lines (187 loc) · 5.3 KB
/
main.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
package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
)
const prefixPattern = "OlPrEfIx"
type SymbolCollection struct {
FileSymbols []BinaryFileSymbols `json:"file_symbols"`
}
type BinaryFileSymbols struct {
Name string `json:"name"`
Hash string `json:"hash"`
Symbols []string `json:"symbols"`
}
type Flags struct {
help bool
clobber bool
outputPath string
}
var flags = Flags{}
func init() {
flag.BoolVar(&flags.help, "help", false, "Show usage")
flag.BoolVar(&flags.clobber, "clobber", false, "Overwrite existing symbol collections")
flag.StringVar(&flags.outputPath, "output", "", "Process symbols into a single file")
flag.Parse()
}
func main() {
// Parse command-line flags
// add a --help flag to show the usage "Usage ./evrfindsymbols [FILE]..."
if flags.help || len(os.Args) == 1 {
fmt.Println("Usage: ./evrfindsymbols [FILE]...")
flag.PrintDefaults()
return
}
var jsonPath string
var symbolCollection SymbolCollection
// If using single file then open/create the json file
if flags.outputPath != "" {
jsonPath = flags.outputPath
// If the file exists, read it in
if _, err := os.Stat(jsonPath); !os.IsNotExist(err) {
// Read the file
jsonFile, err := os.Open(jsonPath)
if err != nil {
fmt.Println("Error opening JSON file:", err)
return
}
defer jsonFile.Close()
decoder := json.NewDecoder(jsonFile)
err = decoder.Decode(&symbolCollection)
if err != nil {
fmt.Println("Error reading JSON file:", err)
return
}
}
if symbolCollection.FileSymbols == nil {
symbolCollection.FileSymbols = make([]BinaryFileSymbols, 0)
}
}
// Process each binary file
for _, binaryPath := range flag.Args() {
// Create a json file to store the symbols that is named after the binary file but has .symbols.json on the end
if flags.outputPath == "" {
jsonPath = binaryPath + ".symbols.json"
if _, err := os.Stat(jsonPath); !os.IsNotExist(err) && !flags.clobber {
fmt.Println("Skipping existing file:", jsonPath)
continue
}
symbolCollection = SymbolCollection{
FileSymbols: make([]BinaryFileSymbols, 0),
}
}
symbols, hash, err := processFile(binaryPath)
if err != nil {
fmt.Println("Error processing file:", err)
return
}
// Write the JSON file
jsonFile, err := os.Create(jsonPath)
if err != nil {
fmt.Println("Error creating JSON file:", err)
return
}
defer jsonFile.Close()
// just the filename of the of the binary path
binaryFileSymbols := BinaryFileSymbols{
Name: filepath.Base(binaryPath),
Hash: hash,
Symbols: symbols,
}
// Check if this hash already exists in the collection, replace it
for i, fileSymbols := range symbolCollection.FileSymbols {
if fileSymbols.Hash == hash {
// Remove it from the sliceq
symbolCollection.FileSymbols = append(symbolCollection.FileSymbols[:i], symbolCollection.FileSymbols[i+1:]...)
}
}
symbolCollection.FileSymbols = append(symbolCollection.FileSymbols, binaryFileSymbols)
// Write the JSON data to the file
encoder := json.NewEncoder(jsonFile)
if err != nil {
fmt.Println("Error writing JSON data:", err)
return
}
encoder.SetIndent("", " ")
encoder.Encode(symbolCollection)
// Print a count of how many symbols
fmt.Printf("%s: %d symbols\n", binaryPath, len(symbols))
}
}
func processFile(binaryPath string) (symbols []string, hash string, err error) {
symbolScanner := NewSymbolScanner()
// Open the binary file
file, err := os.Open(binaryPath)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
hasher := sha256.New()
symbolmap := make(map[string]bool)
// Read the binary file 100MB at a time as to not load the entire file into memory
const chunkSize = 100 * 1024 * 1024
buffer := make([]byte, chunkSize)
for {
bytesRead, err := file.Read(buffer)
if err != nil {
break
}
// If the last byte isn't null, we need to read more to ensure we don't miss any symbols
if buffer[bytesRead-1] != 0 {
// Read until we find a null character
for buffer[bytesRead-1] != 0 {
n, err := file.Read(buffer[bytesRead : bytesRead+1])
if err != nil {
break
}
bytesRead += n
}
}
// Write the bytes to the hasher
hasher.Write(buffer[:bytesRead])
// Scan the bytes for symbols
symbolmap, err = symbolScanner.ScanBytes(buffer[:bytesRead], symbolmap)
if err != nil {
fmt.Println("Error scanning file:", err)
return nil, "", err
}
}
// Convert the map to a slice
symbols = make([]string, 0, len(symbolmap))
for k := range symbolmap {
symbols = append(symbols, k)
}
return symbols, fmt.Sprintf("%x", hasher.Sum(nil)), nil
}
type SymbolScanner struct{}
func NewSymbolScanner() *SymbolScanner {
return &SymbolScanner{}
}
func (s *SymbolScanner) ScanBytes(data []byte, symbols map[string]bool) (map[string]bool, error) {
if len(data) == 0 {
return symbols, nil
}
if symbols == nil {
symbols = make(map[string]bool)
}
// Search the binary for the prefix pattern
prefix := []byte(prefixPattern)
bytes.Split(data, prefix)
for _, b := range bytes.Split(data, prefix) {
// Search for the first null byte
for i, c := range b {
if c == 0 {
// If the byte is null, we have found the end of the symbol
symbols[string(b[:i])] = true
break
}
}
}
return symbols, nil
}