forked from cratonica/2goarray
-
Notifications
You must be signed in to change notification settings - Fork 1
/
go2array.go
288 lines (245 loc) · 7.58 KB
/
go2array.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
// Utility to convert files into a Go byte arrays
// Based on http://github.com/cratonica/2goarray by Clint Caywood
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
const (
GENERATED_BY = "// go2array Auto-generated file, do not edit"
)
type options struct {
variable string
variablePrefix string
platform string
packageName string
exportVariables bool
flatHierarchy bool
ignoreFilelist bool
asyncOutput bool
}
var (
Options = &options{}
preloadByteSymbols = make(map[byte]string)
)
func init() {
for c := byte(0x00); c < byte(0xFF); c++ {
preloadByteSymbols[c] = fmt.Sprintf("0x%02x, ", c)
}
preloadByteSymbols[0xFF] = fmt.Sprintf("0x%02x, ", 0xFF)
}
func main() {
flag.StringVar(&Options.variable, "var", "", "String for the fixed variable name")
flag.StringVar(&Options.variablePrefix, "prefix", "", "String to prefix the variable names")
flag.StringVar(&Options.platform, "platform", "", "Platform file name suffix to append")
flag.StringVar(&Options.packageName, "package", "binaries", "String to use as package name")
flag.BoolVar(&Options.exportVariables, "export", false, "Exports also variables")
flag.BoolVar(&Options.flatHierarchy, "flat", false, "Flatten hierarchy")
flag.BoolVar(&Options.ignoreFilelist, "nolist", false, "Don't produce list file")
flag.BoolVar(&Options.asyncOutput, "async", false, "Disable output to data file to be serialized")
flag.Parse()
if !flag.Parsed() {
log.Fatalf("Could not parse command lines\n")
}
if len(Options.variablePrefix) == 0 && len(Options.variable) == 0 {
log.Fatalf("Variables prefix value must be non-empty\n")
}
if len(Options.variablePrefix) > 0 && len(Options.variable) > 0 {
log.Fatalf("The variables prefix or the fixed name must be non-empty, not both\n")
}
if len(Options.packageName) == 0 {
log.Fatalf("Package name must be non-empty\n")
}
listFilename := fmt.Sprintf("%s_%s.go", Options.packageName, getSuffix("filelist", Options.platform))
listName := ""
dataFilename := ""
if len(Options.variable) > 0 {
listName = strings.Title(fmt.Sprintf("%sList", Options.variable))
dataFilename = fmt.Sprintf("%s_%s_%s.go", Options.packageName, Options.variable, getSuffix("data", Options.platform))
} else {
listName = strings.Title(fmt.Sprintf("%sList", Options.variablePrefix))
dataFilename = fmt.Sprintf("%s_%s.go", Options.packageName, getSuffix("data", Options.platform))
}
// list file create
var fList *os.File
var err error
if !Options.ignoreFilelist {
fList, err = os.Create(listFilename)
if err != nil {
log.Fatalf("Could not create file %s", listFilename)
}
defer fList.Close()
fList.WriteString(fmt.Sprintf("package %s\n\n", Options.packageName))
fList.WriteString(fmt.Sprintf("var %s map[string][]byte \n\n", listName))
fList.WriteString("func init(){ \n")
fList.WriteString(fmt.Sprintf("\t%s = make(map[string][]byte) \n", listName))
}
// data file create
fData, err := os.Create(dataFilename)
if err != nil {
log.Fatalf("Could not create file %s", dataFilename)
}
defer fData.Close()
fData.WriteString(fmt.Sprintf("package %s\n\n", Options.packageName))
// Serial FS scan
log.Println("list file: ", listFilename, "| ignored: ", Options.ignoreFilelist, "| data file: ", dataFilename)
harvestPaths := make(map[string][]string)
totalFiles := 0
for _, inFile := range flag.CommandLine.Args() {
f, err := os.Open(inFile)
if err != nil {
panic(err)
}
stat, err := f.Stat()
_ = f.Close()
if err != nil {
continue
}
if !stat.IsDir() {
harvestPaths[inFile] = []string{} // single file does not have any subresults
totalFiles++
continue
}
if stat.IsDir() && len(Options.variable) > 0 {
log.Fatalf("Cannot harvest directory with fixed variable name\n")
return
}
log.Printf("Will harvest the '%s' directory\n", inFile)
harvestPaths[inFile] = make([]string, 0, 32)
_ = filepath.WalkDir(inFile, func(path string, dEntry fs.DirEntry, err error) error {
if err != nil || dEntry.IsDir() {
return nil
}
harvestPaths[inFile] = append(harvestPaths[inFile], path)
totalFiles++
return nil
})
}
// Parallel load
wg := &sync.WaitGroup{}
wg.Add(totalFiles)
lock := &sync.Mutex{}
index := 0
current := 0
for root, harvestFiles := range harvestPaths {
if len(harvestFiles) == 0 {
go func(_index int, _path, _inFile string) {
// read asynchronously the hex buffer
buffer, filename, varname := readFileToPackage(_index, _path, _inFile)
// flush to the output file
if !Options.asyncOutput {
for current != _index {
time.Sleep(1 * time.Millisecond)
}
}
log.Printf("output | %v | %v | %v\n", current, filename, varname)
lock.Lock()
defer func() {
lock.Unlock()
wg.Done()
}()
// add the variable to the list if not ignored
if fList != nil {
_, _ = fList.WriteString(fmt.Sprintf("\t%s[\"%s\"] = %s \n", listName, filename, varname))
}
_, _ = fData.WriteString(buffer.String())
_ = fData.Sync()
current = _index + 1
}(index, root, "")
index++
continue
}
for _, harvestFile := range harvestFiles {
go func(_index int, _path, _inFile string) {
// read asynchronously the hex buffer
buffer, filename, varname := readFileToPackage(_index, _path, _inFile)
// flush to the output file
if !Options.asyncOutput {
for current != _index {
time.Sleep(1 * time.Millisecond)
}
}
log.Printf("output | %v | %v | %v\n", current, filename, varname)
lock.Lock()
defer func() {
lock.Unlock()
wg.Done()
}()
// add the variable to the list if not ignored
if fList != nil {
_, _ = fList.WriteString(fmt.Sprintf("\t%s[\"%s\"] = %s \n", listName, filename, varname))
}
_, _ = fData.WriteString(buffer.String())
_ = fData.Sync()
current = _index + 1
}(index, harvestFile, root)
index++
}
}
wg.Wait()
// close the list
if fList != nil {
fList.WriteString("}\n\n")
}
}
func readFileToPackage(inFileIndex int, inFileName, baseFilename string) (*bytes.Buffer, string, string) {
origFileName := inFileName
inFileName = strings.ReplaceAll(inFileName, baseFilename, "")
inFileName = strings.ReplaceAll(inFileName, `\`, "/")
inFileName = filepath.ToSlash(inFileName)
if inFileName[0] == '/' {
inFileName = inFileName[1:]
}
if Options.flatHierarchy {
inFileName = filepath.Base(inFileName)
}
varname := ""
if len(Options.variable) > 0 {
varname = Options.variable
} else {
varname = fmt.Sprintf("%s_%03d", Options.variablePrefix, inFileIndex)
}
if Options.exportVariables {
varname = strings.Title(varname)
}
log.Println("file: ", inFileName, "| base: ", baseFilename, "| varname: ", varname)
// open the input file
fInData, err := os.OpenFile(origFileName, os.O_RDONLY, 0777)
if err != nil {
log.Fatalf("Could not read file %s", inFileName)
}
defer fInData.Close()
//_, _ = fInData.Seek(0, syscall.FILE_BEGIN)
// fInData.Read()
// Read the bytes and convert the file
reader := bufio.NewReader(fInData)
buffer := bytes.NewBufferString("")
buffer.WriteString(fmt.Sprintf("// original file: %s\n", origFileName))
buffer.WriteString(fmt.Sprintf("var %s []byte = []byte{", varname))
count := 0
for char, err := reader.ReadByte(); err == nil; char, err = reader.ReadByte() {
if count%16 == 0 {
buffer.WriteString("\n\t")
}
buffer.WriteString(preloadByteSymbols[char])
count++
}
// close the variable
buffer.WriteString("\n}\n\n")
return buffer, inFileName, varname
}
func getSuffix(base, suffix string) string {
if len(suffix) > 0 {
return base + "_" + suffix
}
return base
}