forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinpatch.ts
More file actions
238 lines (211 loc) · 7.14 KB
/
binpatch.ts
File metadata and controls
238 lines (211 loc) · 7.14 KB
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
import {
DeviceConfig,
ArchConfig,
compileDcfg,
serializeDcfg,
decodeDcfg,
decompileDcfg,
DcfgSettings,
parseAnyInt,
UF2File,
DCFG_MAGIC0,
DCFG_MAGIC1,
} from "@devicescript/compiler"
import { HexInt } from "@devicescript/srvcfg"
import { readFile, writeFile } from "fs/promises"
import { JSONTryParse, read32, toHex } from "jacdac-ts"
import { basename, dirname, join, resolve } from "path"
import { error, isVerbose, log, verboseLog } from "./command"
import { EspImage } from "./esp"
export interface FileTypes {
uf2?: string
bin?: string
esp?: string
}
export interface BinPatchOptions extends FileTypes {
outdir?: string
elf?: string
generic?: boolean
}
function fatal(msg: string) {
error("fatal: " + msg)
process.exit(1)
}
function isDCFG(data: Uint8Array, off = 0) {
return (
read32(data, off) == DCFG_MAGIC0 && read32(data, off + 4) == DCFG_MAGIC1
)
}
async function patchUF2File(
uf2: Uint8Array,
arch: ArchConfig,
devcfg: DcfgSettings
) {
const off = parseAnyInt(arch.dcfgOffset)
const buf = serializeDcfg(devcfg)
if (!UF2File.isUF2(uf2)) throw new Error("not a UF2 file")
const f = UF2File.fromFile(uf2)
// needed for RP2040-E14
const align = parseAnyInt(arch.uf2Align)
if (align) {
const amask = align - 1
let maxAddr = 0
for (const b of f.fromBlocks) {
maxAddr = Math.max(b.targetAddr + b.payloadSize, maxAddr)
}
if (maxAddr & amask) {
const left = align - (maxAddr & amask)
const filler = new Uint8Array(left)
filler.fill(0xff)
f.writeBytes(maxAddr, filler)
}
}
//const aligned = new Uint8Array((buf.length + amask) & ~amask)
//aligned.set(buf)
f.writeBytes(off, buf)
return f.serialize()
}
async function patchBinFile(
binFile: Uint8Array,
arch: ArchConfig,
devcfg: DcfgSettings
) {
const off0 = parseAnyInt(arch.dcfgOffset)
const shift = parseAnyInt(arch.binFlashOffset) ?? 0
const off = off0 - shift
const buf = serializeDcfg(devcfg)
if (UF2File.isUF2(binFile)) throw new Error("expecting BIN, not UF2 file")
if (off > 16 * 1024 * 1024) throw new Error("offset too large for BIN")
if (binFile.length > off) {
if (isDCFG(binFile, off)) verboseLog("patching existing")
else if (
toHex(binFile.slice(off, off + 8)) == "0000000000000000" ||
toHex(binFile.slice(off, off + 8)) == "ffffffffffffffff"
)
verboseLog("patching 00 or ff")
else throw new Error("data already at patch point!")
const res = new Uint8Array(binFile)
res.set(buf, off)
return res
} else {
verboseLog("appending to existing file")
}
const res = new Uint8Array(off + buf.length)
res.fill(0xff)
res.set(binFile)
res.set(buf, off)
return res
}
async function patchEspFile(
binFile: Uint8Array,
arch: ArchConfig,
devcfg: DcfgSettings
) {
if (UF2File.isUF2(binFile)) throw new Error("expecting BIN, not UF2 file")
let imgoffset = 0
let img = EspImage.fromBuffer(binFile)
if (!img.looksValid) {
imgoffset = 0x10000
img = EspImage.fromBuffer(binFile.slice(imgoffset))
}
if (!img.looksValid) throw new Error("image doesn't look valid")
verboseLog(`patching at 0x${imgoffset.toString(16)}`)
const cfgoff = parseAnyInt(arch.dcfgOffset)
const seg = img.getLastDROM()
const exoff = cfgoff - seg.addr
if (isDCFG(seg.data, exoff)) {
verboseLog("patching existing config")
} else {
if (seg.data.length > exoff)
throw new Error(
`no space for dcfg; ${seg.data.length - exoff} B missing\n` +
img.toString()
)
}
const cfg = serializeDcfg(devcfg)
const newdata = new Uint8Array(exoff + cfg.length)
newdata.set(seg.data)
newdata.set(cfg, exoff)
seg.data = newdata
const res = await img.toBuffer()
return binFile
// return bufferConcat(binFile.slice(0, imgoffset), res)
}
export async function compileDcfgFile(fn: string) {
const folder = dirname(fn)
return await compileDcfg(basename(fn), f =>
readFile(resolve(folder, f), "utf-8")
)
}
export async function binPatch(files: string[], options: BinPatchOptions) {
const patch: Record<
keyof FileTypes,
(
binFile: Uint8Array,
arch: ArchConfig,
devcfg: DcfgSettings
) => Promise<Uint8Array>
> = {
bin: patchBinFile,
uf2: patchUF2File,
esp: patchEspFile,
}
let binFn = ""
let ft: keyof FileTypes = undefined
for (const k of Object.keys(patch) as (keyof FileTypes)[]) {
const opt = options[k]
if (!opt) continue
if (ft) fatal(`both --${ft} and --${k} provided`)
ft = k
binFn = opt
}
if (!ft) fatal("no file type provided")
const binFileBuf = await readFile(binFn)
const patchFile = patch[ft]
const outpath = options.outdir || "dist"
const outext = options.uf2 ? ".uf2" : ".bin"
const binext = (off: HexInt) => {
const v = parseAnyInt(off)
return v == undefined ? outext : `-0x${v.toString(16)}${outext}`
}
for (const fn of files) {
log(`processing ${fn}...`)
if (!fn.endsWith(".board.json")) fatal("file has to match *.board.json")
const devid = basename(fn, ".board.json")
const archName = join(dirname(fn), "arch.json")
const arch: ArchConfig = JSONTryParse(await readFile(archName, "utf-8"))
if (arch?.dcfgOffset === undefined)
fatal(`no dcfgOffset in ${archName}`)
const suff = binext(arch.binFlashOffset)
const outname = (devid: string, ext = suff) =>
join(outpath, `devicescript-${arch.id}-${devid}${ext}`)
const compiled = await compileDcfgFile(fn)
if (!compiled["devName"]) fatal(`no devName in ${fn}`)
if (!compiled["devClass"]) fatal(`no devClass in ${fn}`)
if (isVerbose) {
verboseLog(JSON.stringify(compiled, null, 4))
const ser = serializeDcfg(compiled)
const dec = decodeDcfg(ser)
verboseLog(dec.errors.join("\n"))
verboseLog(JSON.stringify(decompileDcfg(dec.settings), null, 4))
}
const patched = await patchFile(binFileBuf, arch, compiled)
const outp = outname(devid)
log(`writing ${outp}: ${patched.length} bytes`)
await writeFile(outp, patched)
if (options.generic || arch.binGenericFlashOffset !== undefined) {
const offpatched = parseAnyInt(arch.binFlashOffset)
const offgen = parseAnyInt(arch.binGenericFlashOffset)
let off = 0
if (offgen !== undefined) off = offgen - offpatched
await writeFile(
outname("generic", binext(offgen ?? offpatched)),
binFileBuf.slice(off)
)
const elfFileBuf = await readFile(
options.elf ?? binFn.replace(/\.[^\.]+$/, ".elf")
)
await writeFile(outname("generic", ".elf"), elfFileBuf)
}
}
}