interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / tools / ck_gsp_bindata_extract.c

1155 lines · 65507 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* ck_gsp_bindata_extract.c -- hosted extractor for the GB10 GSP firmware
18 * arrays that the pinned NVIDIA open kernel driver (580.173.02) carries as
19 * generated C source (aienos#286 cut C, host work only). Never loads anything.
20 *
21 * Input: one generated file src/nvidia/generated/g_bindata_<func>.c, e.g.
22 * g_bindata_kgspGetBinArchiveGspRmBoot_GB10B.c (4 arrays)
23 * g_bindata_kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B.c (4 arrays)
24 *
25 * The file format is the driver's own bindata layout: for every array a
26 * comment header (FUNCTION, FILE NAME, FILE TYPE, COMPRESSION, COMPLEX_STRUCT,
27 * DATA SIZE, COMPRESSED SIZE), the `static BINDATA_CONST NvU8 <ident>_data[]`
28 * hex array, a BINDATA_STORAGE_PVT record (uncompressed size, compressed
29 * size, pointer, bCompressed, ...) and at the end one BINDATA_ARCHIVE with
30 * entryNum and the { label, storage } list (SOURCE: the two files above;
31 * bin_data_pvt.h; bin_data.c:36-45 inflates compressed storage with the
32 * driver's zlib). Every one of those fields is cross-checked and any
33 * disagreement is a refusal: this tool never guesses sizes.
34 *
35 * Compressed arrays are gzip members without the 10-byte gzip header: a raw
36 * DEFLATE stream (RFC 1951) followed by the 8-byte gzip trailer CRC-32 and
37 * ISIZE, both little-endian (SOURCE: the driver's own
38 * extract-firmware-nouveau.py at tag 580.173.02, lines 107-108, prepends a
39 * synthetic gzip header and gzip-decompresses; OBSERVED 2026-10-12 on the
40 * 28-byte GB10B descriptor arrays: 20 bytes of fixed-Huffman deflate, CRC-32,
41 * then 0x54 = 84). The decoder and the CRC below are our own (no zlib, no
42 * outside dependency); the trailer is verified, never trusted.
43 *
44 * Semantic checks by label (SOURCE: rmRiscvUcode.h RM_RISCV_UCODE_DESC;
45 * kernel_gsp_gh100.c:303-333 kgspPopulateWprMeta_GH100 and :718-740 the
46 * RISC-V BootROM DMA programming, which shifts every offset by
47 * RISCV_BR_ADDR_ALIGNMENT = 8; kernel_gsp_gb10b.c:507-527 the chain-of-trust
48 * payload fields hash384 / publicKey / signature):
49 * UCODE_DESC_* 84 bytes, version 5, monitor enabled, manifest + monitor
50 * data + monitor code inside the matching UCODE_IMAGE_* and
51 * 256-byte aligned
52 * UCODE_HASH 48 bytes and equal to SHA-384 of UCODE_IMAGE (OBSERVED
53 * 2026-10-12 on the GB10B file; enforced here)
54 * UCODE_SIG, UCODE_PKEY 384 bytes (RSA-3072)
55 *
56 * Usage:
57 * ck_gsp_bindata_extract extract FILE [--out DIR]
58 * Prints one `array` line per label (size, compression, SHA-256), one
59 * `desc` line per descriptor and `RESULT OK`; with --out writes
60 * DIR/<func>.<label>.bin (the uncompressed bytes). Exit 2 + `REFUSED:`.
61 * ck_gsp_bindata_extract selftest
62 * Known-answer tests for SHA-384 and the inflater (stored, fixed and
63 * dynamic Huffman blocks, the real descriptor stream), a synthetic
64 * bindata file that must extract, and every mutation that must be refused.
65 *
66 * Licence note: the driver files are MIT (SPDX in their header). This tool
67 * reads them at run time; nothing from them is vendored into AIENOS.
68 */
69#include <errno.h>
70#include <stdint.h>
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74
75#include "sha256.h"
76
77#define MAX_BLOCKS 16
78#define MAX_ARRAY (8u * 1024u * 1024u)
79#define MAX_LINE 512
80#define DESC_BYTES 84u
81#define DESC_VERSION 5u
82#define RISCV_BR_ALIGN 256u
83#define HASH384_BYTES 48u
84#define RSA3072_BYTES 384u
85
86/* ------------------------------------------------------------------------ */
87/* SHA-384 (FIPS 180-4), our own */
88/* ------------------------------------------------------------------------ */
89static const uint64_t K512[80] = {
90 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
91 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
92 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
93 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
94 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
95 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
96 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
97 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
98 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
99 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
100 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
101 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
102 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
103 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
104 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
105 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
106 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
107 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
108 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
109 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL,
110};
111
112typedef struct {
113 uint64_t h[8];
114 uint64_t total;
115 uint8_t buf[128];
116 size_t buflen;
117} sha384_ctx;
118
119static uint64_t ror64(uint64_t x, int n) { return (x >> n) | (x << (64 - n)); }
120
121static void sha384_block(sha384_ctx *c, const uint8_t *p) {
122 uint64_t w[80];
123 for (int i = 0; i < 16; i++) {
124 w[i] = 0;
125 for (int j = 0; j < 8; j++) w[i] = (w[i] << 8) | p[i * 8 + j];
126 }
127 for (int i = 16; i < 80; i++) {
128 uint64_t s0 = ror64(w[i - 15], 1) ^ ror64(w[i - 15], 8) ^ (w[i - 15] >> 7);
129 uint64_t s1 = ror64(w[i - 2], 19) ^ ror64(w[i - 2], 61) ^ (w[i - 2] >> 6);
130 w[i] = w[i - 16] + s0 + w[i - 7] + s1;
131 }
132 uint64_t a = c->h[0], b = c->h[1], cc = c->h[2], d = c->h[3], e = c->h[4], f = c->h[5], g = c->h[6], h = c->h[7];
133 for (int i = 0; i < 80; i++) {
134 uint64_t S1 = ror64(e, 14) ^ ror64(e, 18) ^ ror64(e, 41);
135 uint64_t ch = (e & f) ^ (~e & g);
136 uint64_t t1 = h + S1 + ch + K512[i] + w[i];
137 uint64_t S0 = ror64(a, 28) ^ ror64(a, 34) ^ ror64(a, 39);
138 uint64_t mj = (a & b) ^ (a & cc) ^ (b & cc);
139 uint64_t t2 = S0 + mj;
140 h = g; g = f; f = e; e = d + t1; d = cc; cc = b; b = a; a = t1 + t2;
141 }
142 c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h;
143}
144
145static void sha384_init(sha384_ctx *c) {
146 static const uint64_t iv[8] = {
147 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,
148 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL,
149 };
150 memcpy(c->h, iv, sizeof iv);
151 c->total = 0;
152 c->buflen = 0;
153}
154
155static void sha384_update(sha384_ctx *c, const uint8_t *p, size_t n) {
156 c->total += n;
157 while (n) {
158 size_t take = 128 - c->buflen;
159 if (take > n) take = n;
160 memcpy(c->buf + c->buflen, p, take);
161 c->buflen += take; p += take; n -= take;
162 if (c->buflen == 128) { sha384_block(c, c->buf); c->buflen = 0; }
163 }
164}
165
166static void sha384_final(sha384_ctx *c, uint8_t out[HASH384_BYTES]) {
167 uint64_t bits = c->total * 8;
168 uint8_t pad = 0x80;
169 sha384_update(c, &pad, 1);
170 c->total -= 1;
171 uint8_t z = 0;
172 while (c->buflen != 112) { sha384_update(c, &z, 1); c->total -= 1; }
173 uint8_t len[16] = {0};
174 for (int i = 0; i < 8; i++) len[15 - i] = (uint8_t)(bits >> (8 * i));
175 sha384_update(c, len, 16);
176 for (int i = 0; i < 6; i++)
177 for (int j = 0; j < 8; j++) out[i * 8 + j] = (uint8_t)(c->h[i] >> (56 - 8 * j));
178}
179
180static void sha384_hash(const uint8_t *p, size_t n, uint8_t out[HASH384_BYTES]) {
181 sha384_ctx c;
182 sha384_init(&c);
183 sha384_update(&c, p, n);
184 sha384_final(&c, out);
185}
186
187/* ------------------------------------------------------------------------ */
188/* Raw DEFLATE decoder (RFC 1951), our own */
189/* ------------------------------------------------------------------------ */
190typedef struct {
191 const uint8_t *in; size_t inlen, inpos;
192 uint32_t bitbuf; int bitcnt;
193 uint8_t *out; size_t outlen, outpos;
194 const char *err;
195} inf_state;
196
197typedef struct { uint16_t count[16]; uint16_t symbol[288]; } huff;
198
199static int inf_bits(inf_state *s, int need, uint32_t *v) {
200 while (s->bitcnt < need) {
201 if (s->inpos >= s->inlen) { s->err = "inflate: input exhausted"; return -1; }
202 s->bitbuf |= (uint32_t)s->in[s->inpos++] << s->bitcnt;
203 s->bitcnt += 8;
204 }
205 *v = s->bitbuf & ((1u << need) - 1u);
206 s->bitbuf >>= need;
207 s->bitcnt -= need;
208 return 0;
209}
210
211/* Returns the number of unused codes (0 = complete), -1 = over-subscribed. */
212static int huff_construct(huff *h, const uint16_t *length, int n) {
213 int offs[16];
214 for (int i = 0; i < 16; i++) h->count[i] = 0;
215 for (int i = 0; i < n; i++) h->count[length[i]]++;
216 if (h->count[0] == n) return 0;
217 int left = 1;
218 for (int len = 1; len < 16; len++) {
219 left <<= 1;
220 left -= h->count[len];
221 if (left < 0) return -1;
222 }
223 offs[1] = 0;
224 for (int len = 1; len < 15; len++) offs[len + 1] = offs[len] + h->count[len];
225 for (int i = 0; i < n; i++)
226 if (length[i] != 0) h->symbol[offs[length[i]]++] = (uint16_t)i;
227 return left;
228}
229
230static int huff_decode(inf_state *s, const huff *h, int *sym) {
231 int code = 0, first = 0, index = 0;
232 for (int len = 1; len < 16; len++) {
233 uint32_t b;
234 if (inf_bits(s, 1, &b)) return -1;
235 code |= (int)b;
236 int count = h->count[len];
237 if (code - count < first) { *sym = h->symbol[index + (code - first)]; return 0; }
238 index += count;
239 first += count;
240 first <<= 1;
241 code <<= 1;
242 }
243 s->err = "inflate: invalid Huffman code";
244 return -1;
245}
246
247static int inf_codes(inf_state *s, const huff *lencode, const huff *distcode) {
248 static const uint16_t lbase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
249 static const uint16_t lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
250 static const uint16_t dbase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
251 static const uint16_t dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
252 for (;;) {
253 int sym;
254 if (huff_decode(s, lencode, &sym)) return -1;
255 if (sym < 256) {
256 if (s->outpos >= s->outlen) { s->err = "inflate: output longer than declared size"; return -1; }
257 s->out[s->outpos++] = (uint8_t)sym;
258 continue;
259 }
260 if (sym == 256) return 0;
261 sym -= 257;
262 if (sym >= 29) { s->err = "inflate: invalid length symbol"; return -1; }
263 uint32_t e;
264 if (inf_bits(s, lext[sym], &e)) return -1;
265 size_t len = lbase[sym] + e;
266 if (huff_decode(s, distcode, &sym)) return -1;
267 if (sym >= 30) { s->err = "inflate: invalid distance symbol"; return -1; }
268 if (inf_bits(s, dext[sym], &e)) return -1;
269 size_t dist = dbase[sym] + e;
270 if (dist > s->outpos) { s->err = "inflate: distance before start of output"; return -1; }
271 if (s->outpos + len > s->outlen) { s->err = "inflate: output longer than declared size"; return -1; }
272 while (len--) { s->out[s->outpos] = s->out[s->outpos - dist]; s->outpos++; }
273 }
274}
275
276static int inf_stored(inf_state *s) {
277 s->bitbuf = 0; s->bitcnt = 0;
278 if (s->inpos + 4 > s->inlen) { s->err = "inflate: input exhausted"; return -1; }
279 unsigned len = s->in[s->inpos] | (s->in[s->inpos + 1] << 8);
280 unsigned nlen = s->in[s->inpos + 2] | (s->in[s->inpos + 3] << 8);
281 s->inpos += 4;
282 if ((len ^ 0xffffu) != nlen) { s->err = "inflate: stored block length check failed"; return -1; }
283 if (s->inpos + len > s->inlen) { s->err = "inflate: input exhausted"; return -1; }
284 if (s->outpos + len > s->outlen) { s->err = "inflate: output longer than declared size"; return -1; }
285 memcpy(s->out + s->outpos, s->in + s->inpos, len);
286 s->inpos += len; s->outpos += len;
287 return 0;
288}
289
290static int inf_fixed(inf_state *s) {
291 static huff lencode, distcode;
292 static int built = 0;
293 if (!built) {
294 uint16_t lengths[288];
295 int i = 0;
296 for (; i < 144; i++) lengths[i] = 8;
297 for (; i < 256; i++) lengths[i] = 9;
298 for (; i < 280; i++) lengths[i] = 7;
299 for (; i < 288; i++) lengths[i] = 8;
300 huff_construct(&lencode, lengths, 288);
301 for (i = 0; i < 30; i++) lengths[i] = 5;
302 huff_construct(&distcode, lengths, 30);
303 built = 1;
304 }
305 return inf_codes(s, &lencode, &distcode);
306}
307
308static int inf_dynamic(inf_state *s) {
309 static const uint16_t order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
310 uint16_t lengths[320];
311 huff lencode, distcode;
312 uint32_t v;
313 if (inf_bits(s, 5, &v)) return -1;
314 int nlen = (int)v + 257;
315 if (inf_bits(s, 5, &v)) return -1;
316 int ndist = (int)v + 1;
317 if (inf_bits(s, 4, &v)) return -1;
318 int ncode = (int)v + 4;
319 if (nlen > 286 || ndist > 30) { s->err = "inflate: bad code counts"; return -1; }
320 int i;
321 for (i = 0; i < ncode; i++) { if (inf_bits(s, 3, &v)) return -1; lengths[order[i]] = (uint16_t)v; }
322 for (; i < 19; i++) lengths[order[i]] = 0;
323 if (huff_construct(&lencode, lengths, 19) != 0) { s->err = "inflate: bad code-length code"; return -1; }
324 i = 0;
325 while (i < nlen + ndist) {
326 int sym;
327 if (huff_decode(s, &lencode, &sym)) return -1;
328 if (sym < 16) { lengths[i++] = (uint16_t)sym; continue; }
329 uint16_t rep = 0;
330 int count;
331 if (sym == 16) {
332 if (i == 0) { s->err = "inflate: repeat with no previous length"; return -1; }
333 rep = lengths[i - 1];
334 if (inf_bits(s, 2, &v)) return -1;
335 count = 3 + (int)v;
336 } else if (sym == 17) {
337 if (inf_bits(s, 3, &v)) return -1;
338 count = 3 + (int)v;
339 } else {
340 if (inf_bits(s, 7, &v)) return -1;
341 count = 11 + (int)v;
342 }
343 if (i + count > nlen + ndist) { s->err = "inflate: too many lengths"; return -1; }
344 while (count--) lengths[i++] = rep;
345 }
346 if (lengths[256] == 0) { s->err = "inflate: no end-of-block code"; return -1; }
347 int err = huff_construct(&lencode, lengths, nlen);
348 if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) { s->err = "inflate: bad literal/length code"; return -1; }
349 err = huff_construct(&distcode, lengths + nlen, ndist);
350 if (err < 0 || (err > 0 && ndist - distcode.count[0] != 1)) { s->err = "inflate: bad distance code"; return -1; }
351 return inf_codes(s, &lencode, &distcode);
352}
353
354/* Inflate exactly outlen bytes from the raw stream in[0..inlen); the stream
355 * must end with its final block in the last input byte. */
356static int inflate_raw(const uint8_t *in, size_t inlen, uint8_t *out, size_t outlen, const char **why) {
357 inf_state s = {in, inlen, 0, 0, 0, out, outlen, 0, "inflate: ok"};
358 uint32_t last, type;
359 do {
360 if (inf_bits(&s, 1, &last)) { *why = s.err; return -1; }
361 if (inf_bits(&s, 2, &type)) { *why = s.err; return -1; }
362 int rc = type == 0 ? inf_stored(&s) : type == 1 ? inf_fixed(&s) : type == 2 ? inf_dynamic(&s) : -2;
363 if (rc == -2) { *why = "inflate: invalid block type 3"; return -1; }
364 if (rc) { *why = s.err; return -1; }
365 } while (!last);
366 if (s.outpos != s.outlen) { *why = "inflate: output shorter than declared size"; return -1; }
367 if (s.inpos != s.inlen) { *why = "inflate: trailing bytes after the final block"; return -1; }
368 return 0;
369}
370
371static uint32_t crc32_bytes(const uint8_t *p, size_t n) {
372 uint32_t c = 0xffffffffu;
373 for (size_t i = 0; i < n; i++) {
374 c ^= p[i];
375 for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xedb88320u & (0u - (c & 1u)));
376 }
377 return ~c;
378}
379
380static uint32_t get32le(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }
381
382/* A bindata compressed array: deflate body + CRC-32 + ISIZE. */
383static int unpack_gz_body(const uint8_t *in, size_t inlen, uint8_t *out, size_t outlen, const char **why) {
384 if (inlen < 9) { *why = "compressed array shorter than a deflate block plus its 8-byte trailer"; return -1; }
385 if (inflate_raw(in, inlen - 8, out, outlen, why)) return -1;
386 if (get32le(in + inlen - 4) != outlen) { *why = "compressed trailer: ISIZE differs from DATA SIZE"; return -1; }
387 if (get32le(in + inlen - 8) != crc32_bytes(out, outlen)) { *why = "compressed trailer: CRC-32 mismatch"; return -1; }
388 return 0;
389}
390
391/* ------------------------------------------------------------------------ */
392/* bindata file parser */
393/* ------------------------------------------------------------------------ */
394typedef struct {
395 char func[96];
396 char label[64];
397 char fname[160];
398 char ident[192];
399 int compressed;
400 uint32_t data_size, comp_size;
401 uint8_t *bytes; /* as stored in the array */
402 size_t nbytes;
403 uint8_t *plain; /* uncompressed (== bytes when not compressed) */
404 size_t plain_len;
405 int have_header, have_data, have_pvt;
406} bd_block;
407
408typedef struct {
409 bd_block b[MAX_BLOCKS];
410 int n;
411 char func[96];
412 int archive_seen;
413 int entry_num;
414 char reason[256];
415} bd_file;
416
417typedef struct { const char *p, *end; int lineno; } cursor;
418
419static void bd_free(bd_file *f) {
420 for (int i = 0; i < f->n; i++) {
421 free(f->b[i].bytes);
422 if (f->b[i].plain != f->b[i].bytes) free(f->b[i].plain);
423 f->b[i].bytes = f->b[i].plain = NULL;
424 }
425}
426
427static int refuse(bd_file *f, const cursor *c, const char *fmt, const char *a) {
428 int n = snprintf(f->reason, sizeof f->reason, "line %d: ", c ? c->lineno : 0);
429 if (n < 0) n = 0;
430 snprintf(f->reason + n, sizeof f->reason - (size_t)n, fmt, a ? a : "");
431 return -1;
432}
433
434/* Copy the next line (without its newline) into buf; 1 = got a line, 0 = EOF. */
435static int next_line(cursor *c, char *buf, size_t cap, bd_file *f) {
436 if (c->p >= c->end) return 0;
437 const char *nl = memchr(c->p, '\n', (size_t)(c->end - c->p));
438 size_t len = nl ? (size_t)(nl - c->p) : (size_t)(c->end - c->p);
439 c->lineno++;
440 if (len >= cap) { refuse(f, c, "line longer than %s characters", "511"); return -1; }
441 memcpy(buf, c->p, len);
442 buf[len] = 0;
443 if (len && buf[len - 1] == '\r') buf[len - 1] = 0;
444 c->p = nl ? nl + 1 : c->end;
445 return 1;
446}
447
448static const char *after(const char *line, const char *prefix) {
449 size_t n = strlen(prefix);
450 return strncmp(line, prefix, n) == 0 ? line + n : NULL;
451}
452
453static int parse_u32(const char *s, uint32_t *v) {
454 if (*s < '0' || *s > '9') return -1;
455 uint64_t acc = 0;
456 while (*s >= '0' && *s <= '9') { acc = acc * 10 + (uint64_t)(*s - '0'); if (acc > 0xffffffffULL) return -1; s++; }
457 while (*s == ' ' || *s == ',' || *s == '\t') s++;
458 if (*s && strncmp(s, "//", 2) != 0) return -1;
459 *v = (uint32_t)acc;
460 return 0;
461}
462
463static int copy_field(char *dst, size_t cap, const char *src, size_t len) {
464 if (len == 0 || len >= cap) return -1;
465 memcpy(dst, src, len);
466 dst[len] = 0;
467 return 0;
468}
469
470static bd_block *cur_block(bd_file *f) { return f->n ? &f->b[f->n - 1] : NULL; }
471
472static int parse_hex_array(cursor *c, bd_file *f, bd_block *b) {
473 char line[MAX_LINE];
474 size_t want = b->compressed ? b->comp_size : b->data_size;
475 if (want == 0 || want > MAX_ARRAY) return refuse(f, c, "array size out of range for %s", b->label);
476 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line, "{") != 0) return refuse(f, c, "expected '{' after the array declaration of %s", b->label);
477 b->bytes = malloc(want);
478 if (!b->bytes) return refuse(f, c, "out of memory for %s", b->label);
479 b->nbytes = 0;
480 for (;;) {
481 int r = next_line(c, line, sizeof line, f);
482 if (r < 0) return -1;
483 if (r == 0) return refuse(f, c, "file ends inside the array of %s", b->label);
484 if (strcmp(line, "};") == 0) break;
485 const char *p = line;
486 while (*p) {
487 while (*p == ' ' || *p == '\t') p++;
488 if (!*p) break;
489 if (p[0] != '0' || p[1] != 'x') return refuse(f, c, "non-hex token in the array of %s", b->label);
490 unsigned v = 0;
491 for (int k = 2; k < 4; k++) {
492 char ch = p[k];
493 unsigned d = ch >= '0' && ch <= '9' ? (unsigned)(ch - '0') : ch >= 'a' && ch <= 'f' ? (unsigned)(ch - 'a' + 10) : ch >= 'A' && ch <= 'F' ? (unsigned)(ch - 'A' + 10) : 16u;
494 if (d == 16u) return refuse(f, c, "non-hex token in the array of %s", b->label);
495 v = v * 16 + d;
496 }
497 if (p[4] != ',') return refuse(f, c, "byte token without a trailing comma in %s", b->label);
498 if (b->nbytes >= want) return refuse(f, c, "more bytes than the declared size in %s", b->label);
499 b->bytes[b->nbytes++] = (uint8_t)v;
500 p += 5;
501 }
502 }
503 if (b->nbytes != want) return refuse(f, c, "fewer bytes than the declared size in %s", b->label);
504 b->have_data = 1;
505 return 0;
506}
507
508static int parse_pvt(cursor *c, bd_file *f, bd_block *b) {
509 char line[MAX_LINE];
510 uint32_t v;
511 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line, "{") != 0) return refuse(f, c, "expected '{' in the storage record of %s", b->label);
512 if (next_line(c, line, sizeof line, f) != 1 || parse_u32(line + strspn(line, " "), &v)) return refuse(f, c, "storage record: bad uncompressed size for %s", b->label);
513 if (v != b->data_size) return refuse(f, c, "storage record: uncompressed size differs from DATA SIZE for %s", b->label);
514 if (next_line(c, line, sizeof line, f) != 1 || parse_u32(line + strspn(line, " "), &v)) return refuse(f, c, "storage record: bad compressed size for %s", b->label);
515 if (v != (b->compressed ? b->comp_size : b->data_size)) return refuse(f, c, "storage record: compressed size differs from the header for %s", b->label);
516 if (next_line(c, line, sizeof line, f) != 1) return refuse(f, c, "storage record: missing pointer line for %s", b->label);
517 const char *p = line + strspn(line, " ");
518 size_t n = strlen(b->ident);
519 if (strncmp(p, b->ident, n) != 0 || p[n] != ',') return refuse(f, c, "storage record: data pointer is not the array of %s", b->label);
520 if (next_line(c, line, sizeof line, f) != 1) return refuse(f, c, "storage record: missing compressed flag for %s", b->label);
521 p = line + strspn(line, " ");
522 int flag = after(p, "NV_TRUE,") ? 1 : after(p, "NV_FALSE,") ? 0 : -1;
523 if (flag < 0) return refuse(f, c, "storage record: bad compressed flag for %s", b->label);
524 if (flag != b->compressed) return refuse(f, c, "storage record: compressed flag disagrees with COMPRESSION for %s", b->label);
525 b->have_pvt = 1;
526 return 0;
527}
528
529static int parse_archive(cursor *c, bd_file *f, const char *decl) {
530 char line[MAX_LINE];
531 uint32_t v;
532 if (f->archive_seen) return refuse(f, c, "second archive table%s", "");
533 const char *name = after(decl, "static const BINDATA_ARCHIVE __");
534 size_t n = strlen(f->func);
535 if (!name || strncmp(name, f->func, n) != 0 || strcmp(name + n, " =") != 0) return refuse(f, c, "archive table name is not the file's function%s", "");
536 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line, "{") != 0) return refuse(f, c, "expected '{' after the archive declaration%s", "");
537 if (next_line(c, line, sizeof line, f) != 1 || parse_u32(line + strspn(line, " "), &v)) return refuse(f, c, "archive: bad entryNum%s", "");
538 if ((int)v != f->n) return refuse(f, c, "archive: entryNum differs from the number of arrays%s", "");
539 f->entry_num = (int)v;
540 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line + strspn(line, " "), "{") != 0) return refuse(f, c, "archive: expected entries block%s", "");
541 if (next_line(c, line, sizeof line, f) != 1 || !after(line + strspn(line, " "), "// entries[]")) return refuse(f, c, "archive: expected the entries comment%s", "");
542 for (int i = 0; i < f->n; i++) {
543 if (next_line(c, line, sizeof line, f) != 1) return refuse(f, c, "archive: missing entry %s", f->b[i].label);
544 const char *p = line + strspn(line, " ");
545 const char *lab = after(p, "{ BINDATA_LABEL_");
546 if (!lab) return refuse(f, c, "archive: malformed entry for %s", f->b[i].label);
547 size_t ll = strlen(f->b[i].label);
548 if (strncmp(lab, f->b[i].label, ll) != 0 || (lab[ll] != ' ' && lab[ll] != ',')) return refuse(f, c, "archive: entry order or label differs from the arrays at %s", f->b[i].label);
549 const char *idx = strstr(lab, "&g_bindata_pvt[__idx_");
550 if (!idx) return refuse(f, c, "archive: entry without a storage index for %s", f->b[i].label);
551 idx += strlen("&g_bindata_pvt[__idx_");
552 size_t il = strlen(f->b[i].ident) - strlen("_data");
553 if (strncmp(idx, f->b[i].ident, il) != 0 || idx[il] != ']') return refuse(f, c, "archive: storage index is not this array for %s", f->b[i].label);
554 }
555 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line + strspn(line, " "), "}") != 0) return refuse(f, c, "archive: expected end of entries%s", "");
556 if (next_line(c, line, sizeof line, f) != 1 || strcmp(line, "};") != 0) return refuse(f, c, "archive: expected end of table%s", "");
557 f->archive_seen = 1;
558 return 0;
559}
560
561static int parse_file(bd_file *f, const char *text, size_t len) {
562 cursor c = {text, text + len, 0};
563 char line[MAX_LINE];
564 memset(f, 0, sizeof *f);
565 for (;;) {
566 int r = next_line(&c, line, sizeof line, f);
567 if (r < 0) return -1;
568 if (r == 0) break;
569 const char *v;
570 bd_block *b = cur_block(f);
571 if ((v = after(line, "// FUNCTION: "))) {
572 if (b && !(b->have_data && b->have_pvt)) return refuse(f, &c, "array %s has no data or no storage record", b->label);
573 if (f->n >= MAX_BLOCKS) return refuse(f, &c, "more than %s arrays", "16");
574 const char *lp = strchr(v, '(');
575 if (!lp || strncmp(lp, "(\"BINDATA_LABEL_", 16) != 0) return refuse(f, &c, "FUNCTION line without a BINDATA_LABEL%s", "");
576 const char *le = strstr(lp + 16, "\")");
577 if (!le || le[2] != 0) return refuse(f, &c, "FUNCTION line not terminated%s", "");
578 b = &f->b[f->n++];
579 if (copy_field(b->func, sizeof b->func, v, (size_t)(lp - v))) return refuse(f, &c, "bad function name%s", "");
580 if (copy_field(b->label, sizeof b->label, lp + 16, (size_t)(le - lp - 16))) return refuse(f, &c, "bad label%s", "");
581 if (f->n == 1) strcpy(f->func, b->func);
582 else if (strcmp(f->func, b->func) != 0) return refuse(f, &c, "array belongs to a different function: %s", b->func);
583 for (int i = 0; i < f->n - 1; i++)
584 if (strcmp(f->b[i].label, b->label) == 0) return refuse(f, &c, "duplicate label %s", b->label);
585 b->comp_size = 0xffffffffu; b->compressed = -1; b->data_size = 0;
586 const char *stem = after(b->func, "kgspGetBinArchive");
587 if (!stem) return refuse(f, &c, "function is not a kgspGetBinArchive function: %s", b->func);
588 char ident[sizeof b->ident];
589 if (snprintf(ident, sizeof ident, "kgspBinArchive%s_BINDATA_LABEL_%s_data", stem, b->label) >= (int)sizeof ident) return refuse(f, &c, "identifier too long for %s", b->label);
590 memcpy(b->ident, ident, sizeof ident);
591 continue;
592 }
593 if (!b) {
594 if (after(line, "static BINDATA_CONST") || after(line, "static const BINDATA_ARCHIVE")) return refuse(f, &c, "data before the first FUNCTION header%s", "");
595 continue;
596 }
597 if ((v = after(line, "// FILE NAME: "))) { if (copy_field(b->fname, sizeof b->fname, v, strlen(v))) return refuse(f, &c, "bad file name for %s", b->label); continue; }
598 if ((v = after(line, "// FILE TYPE: "))) { if (strcmp(v, "BINARY") != 0) return refuse(f, &c, "FILE TYPE is not BINARY for %s", b->label); continue; }
599 if ((v = after(line, "// COMPRESSION: "))) {
600 if (strcmp(v, "YES") == 0) b->compressed = 1;
601 else if (strcmp(v, "NO") == 0) b->compressed = 0;
602 else return refuse(f, &c, "COMPRESSION is neither YES nor NO for %s", b->label);
603 continue;
604 }
605 if ((v = after(line, "// COMPLEX_STRUCT: "))) { if (strcmp(v, "NO") != 0) return refuse(f, &c, "COMPLEX_STRUCT is not NO for %s", b->label); continue; }
606 if ((v = after(line, "// DATA SIZE (bytes): "))) { if (parse_u32(v, &b->data_size)) return refuse(f, &c, "bad DATA SIZE for %s", b->label); continue; }
607 if ((v = after(line, "// COMPRESSED SIZE (bytes): "))) {
608 if (strcmp(v, "N/A") == 0) b->comp_size = 0;
609 else if (parse_u32(v, &b->comp_size)) return refuse(f, &c, "bad COMPRESSED SIZE for %s", b->label);
610 continue;
611 }
612 if ((v = after(line, "static BINDATA_CONST NvU8 "))) {
613 if (b->have_data) return refuse(f, &c, "second array for %s", b->label);
614 if (b->compressed < 0 || b->data_size == 0 || b->comp_size == 0xffffffffu || !b->fname[0]) return refuse(f, &c, "array header incomplete for %s", b->label);
615 if (b->compressed == 1 && b->comp_size == 0) return refuse(f, &c, "COMPRESSED SIZE missing with COMPRESSION YES for %s", b->label);
616 if (b->compressed == 0 && b->comp_size != 0) return refuse(f, &c, "COMPRESSED SIZE given with COMPRESSION NO for %s", b->label);
617 size_t n = strlen(b->ident);
618 if (strncmp(v, b->ident, n) != 0 || strcmp(v + n, "[] = ") != 0) return refuse(f, &c, "array identifier is not the expected one for %s", b->label);
619 b->have_header = 1;
620 if (parse_hex_array(&c, f, b)) return -1;
621 continue;
622 }
623 if (strcmp(line, "#if defined(BINDATA_INCLUDE_STORAGE_PVT_DEFN)") == 0) {
624 if (!b->have_data) return refuse(f, &c, "storage record before the array of %s", b->label);
625 if (b->have_pvt) return refuse(f, &c, "second storage record for %s", b->label);
626 if (parse_pvt(&c, f, b)) return -1;
627 continue;
628 }
629 if (after(line, "static const BINDATA_ARCHIVE __")) {
630 if (!(b->have_data && b->have_pvt)) return refuse(f, &c, "array %s has no data or no storage record", b->label);
631 if (parse_archive(&c, f, line)) return -1;
632 continue;
633 }
634 }
635 if (f->n == 0) return refuse(f, &c, "no arrays found%s", "");
636 if (!f->archive_seen) return refuse(f, &c, "no archive table%s", "");
637 for (int i = 0; i < f->n; i++) {
638 bd_block *b = &f->b[i];
639 if (!(b->have_data && b->have_pvt)) return refuse(f, &c, "array %s has no data or no storage record", b->label);
640 if (b->compressed) {
641 b->plain = malloc(b->data_size);
642 if (!b->plain) return refuse(f, &c, "out of memory for %s", b->label);
643 const char *why;
644 if (unpack_gz_body(b->bytes, b->nbytes, b->plain, b->data_size, &why)) {
645 char msg[200];
646 snprintf(msg, sizeof msg, "%s (%s)", why, b->label);
647 return refuse(f, NULL, "%s", msg);
648 }
649 b->plain_len = b->data_size;
650 } else {
651 b->plain = b->bytes;
652 b->plain_len = b->nbytes;
653 }
654 }
655 return 0;
656}
657
658/* ------------------------------------------------------------------------ */
659/* Semantic checks */
660/* ------------------------------------------------------------------------ */
661static const bd_block *find_label(const bd_file *f, const char *label) {
662 for (int i = 0; i < f->n; i++)
663 if (strcmp(f->b[i].label, label) == 0) return &f->b[i];
664 return NULL;
665}
666
667typedef struct {
668 uint32_t version, bootloader_off, bootloader_size, bl_param_off, bl_param_size, elf_off, elf_size, app_version;
669 uint32_t manifest_off, manifest_size, mdata_off, mdata_size, mcode_off, mcode_size, monitor_enabled;
670 uint32_t swbrom_code_off, swbrom_code_size, swbrom_data_off, swbrom_data_size, fb_reserved, signed_as_code;
671} riscv_desc;
672
673static void decode_desc(const uint8_t *p, riscv_desc *d) {
674 uint32_t *w = (uint32_t *)d;
675 for (int i = 0; i < 21; i++) w[i] = get32le(p + 4 * i);
676}
677
678static int region_ok(uint32_t off, uint32_t size, size_t image) {
679 return size != 0 && (off % RISCV_BR_ALIGN) == 0 && (uint64_t)off + size <= image;
680}
681
682static int check_semantics(bd_file *f, FILE *out) {
683 for (int i = 0; i < f->n; i++) {
684 bd_block *b = &f->b[i];
685 const char *suffix = after(b->label, "UCODE_DESC");
686 if (suffix) {
687 if (b->plain_len != DESC_BYTES) return refuse(f, NULL, "descriptor is not 84 bytes: %s", b->label);
688 riscv_desc d;
689 decode_desc(b->plain, &d);
690 if (d.version != DESC_VERSION) return refuse(f, NULL, "descriptor version is not 5: %s", b->label);
691 if (d.monitor_enabled != 1) return refuse(f, NULL, "descriptor monitor not enabled: %s", b->label);
692 char img[64];
693 snprintf(img, sizeof img, "UCODE_IMAGE%s", suffix);
694 const bd_block *ib = find_label(f, img);
695 if (!ib) return refuse(f, NULL, "descriptor without a matching image: %s", b->label);
696 if (!region_ok(d.manifest_off, d.manifest_size, ib->plain_len)) return refuse(f, NULL, "descriptor manifest region outside the image or unaligned: %s", b->label);
697 if (!region_ok(d.mdata_off, d.mdata_size, ib->plain_len)) return refuse(f, NULL, "descriptor monitor-data region outside the image or unaligned: %s", b->label);
698 if (!region_ok(d.mcode_off, d.mcode_size, ib->plain_len)) return refuse(f, NULL, "descriptor monitor-code region outside the image or unaligned: %s", b->label);
699 if (out)
700 fprintf(out, "desc %s version=%u manifest=0x%x+0x%x monitor_data=0x%x+0x%x monitor_code=0x%x+0x%x monitor_enabled=%u fb_reserved=0x%x signed_as_code=%u app_version=%u image=%s/%zu\n",
701 b->label, d.version, d.manifest_off, d.manifest_size, d.mdata_off, d.mdata_size, d.mcode_off, d.mcode_size,
702 d.monitor_enabled, d.fb_reserved, d.signed_as_code, d.app_version, img, ib->plain_len);
703 } else if (strcmp(b->label, "UCODE_HASH") == 0) {
704 if (b->plain_len != HASH384_BYTES) return refuse(f, NULL, "hash array is not 48 bytes%s", "");
705 const bd_block *ib = find_label(f, "UCODE_IMAGE");
706 if (!ib) return refuse(f, NULL, "hash array without UCODE_IMAGE%s", "");
707 uint8_t h[HASH384_BYTES];
708 sha384_hash(ib->plain, ib->plain_len, h);
709 if (memcmp(h, b->plain, HASH384_BYTES) != 0) return refuse(f, NULL, "UCODE_HASH is not SHA-384 of UCODE_IMAGE%s", "");
710 if (out) fprintf(out, "hash384 UCODE_HASH equals sha384(UCODE_IMAGE)\n");
711 } else if (strcmp(b->label, "UCODE_SIG") == 0 || strcmp(b->label, "UCODE_PKEY") == 0) {
712 if (b->plain_len != RSA3072_BYTES) return refuse(f, NULL, "%s is not 384 bytes", b->label);
713 } else if (!after(b->label, "UCODE_IMAGE")) {
714 return refuse(f, NULL, "unknown label %s", b->label);
715 }
716 }
717 return 0;
718}
719
720static void hex(const uint8_t *p, size_t n, char *out) {
721 static const char *d = "0123456789abcdef";
722 for (size_t i = 0; i < n; i++) { out[2 * i] = d[p[i] >> 4]; out[2 * i + 1] = d[p[i] & 15]; }
723 out[2 * n] = 0;
724}
725
726static int report(const bd_file *f, FILE *out, const char *outdir) {
727 for (int i = 0; i < f->n; i++) {
728 const bd_block *b = &f->b[i];
729 uint8_t d[32];
730 char hx[65];
731 sha256_hash(b->plain, b->plain_len, d);
732 hex(d, 32, hx);
733 fprintf(out, "array %s %s file=%s stored=%zu compressed=%s size=%zu sha256=%s\n", b->func, b->label, b->fname, b->nbytes, b->compressed ? "yes" : "no", b->plain_len, hx);
734 if (outdir) {
735 char path[512];
736 if (snprintf(path, sizeof path, "%s/%s.%s.bin", outdir, b->func, b->label) >= (int)sizeof path) { fprintf(out, "REFUSED: output path too long\n"); return 2; }
737 FILE *w = fopen(path, "wb");
738 if (!w || fwrite(b->plain, 1, b->plain_len, w) != b->plain_len || fclose(w)) { fprintf(out, "REFUSED: cannot write %s: %s\n", path, strerror(errno)); return 2; }
739 fprintf(out, "wrote %s\n", path);
740 }
741 }
742 return 0;
743}
744
745/* ------------------------------------------------------------------------ */
746/* CLI */
747/* ------------------------------------------------------------------------ */
748static char *read_file(const char *path, size_t *len) {
749 FILE *fp = fopen(path, "rb");
750 if (!fp) return NULL;
751 if (fseek(fp, 0, SEEK_END)) { fclose(fp); return NULL; }
752 long sz = ftell(fp);
753 if (sz < 0 || sz > 64L * 1024 * 1024) { fclose(fp); errno = EFBIG; return NULL; }
754 rewind(fp);
755 char *buf = malloc((size_t)sz + 1);
756 if (!buf) { fclose(fp); return NULL; }
757 if (fread(buf, 1, (size_t)sz, fp) != (size_t)sz) { free(buf); fclose(fp); errno = EIO; return NULL; }
758 fclose(fp);
759 buf[sz] = 0;
760 *len = (size_t)sz;
761 return buf;
762}
763
764static int cmd_extract(int argc, char **argv) {
765 const char *path = NULL, *outdir = NULL;
766 for (int i = 0; i < argc; i++) {
767 if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) outdir = argv[++i];
768 else if (!path) path = argv[i];
769 else { fprintf(stderr, "usage: ck_gsp_bindata_extract extract FILE [--out DIR]\n"); return 1; }
770 }
771 if (!path) { fprintf(stderr, "usage: ck_gsp_bindata_extract extract FILE [--out DIR]\n"); return 1; }
772 size_t len;
773 char *text = read_file(path, &len);
774 if (!text) { printf("REFUSED: cannot read %s: %s\n", path, strerror(errno)); return 2; }
775 bd_file *f = calloc(1, sizeof *f);
776 if (!f) { free(text); printf("REFUSED: out of memory\n"); return 2; }
777 int rc = parse_file(f, text, len);
778 free(text);
779 if (rc == 0) { printf("function %s arrays=%d\n", f->func, f->n); rc = check_semantics(f, stdout); }
780 if (rc) { printf("REFUSED: %s\n", f->reason); bd_free(f); free(f); return 2; }
781 rc = report(f, stdout, outdir);
782 if (rc == 0) printf("RESULT OK arrays=%d\n", f->n);
783 bd_free(f);
784 free(f);
785 return rc;
786}
787
788/* ------------------------------------------------------------------------ */
789/* Self-test */
790/* ------------------------------------------------------------------------ */
791static int failures, checks;
792static void check(int ok, const char *what) {
793 checks++;
794 if (!ok) { failures++; printf("FAIL: %s\n", what); }
795}
796
797static size_t unhex(const char *s, uint8_t *out, size_t cap) {
798 size_t n = 0;
799 for (; s[0] && s[1] && n < cap; s += 2, n++) {
800 unsigned v;
801 if (sscanf(s, "%2x", &v) != 1) return 0;
802 out[n] = (uint8_t)v;
803 }
804 return n;
805}
806
807/* Test vectors. Deflate streams were produced once with a reference
808 * compressor (raw, level 0 / 1 / 9) and are compared against the plaintext
809 * (stored, fixed) or its SHA-256 (dynamic, 760 bytes). */
810static const char STORED_STREAM[] = "011b00e4ff4149454e4f532073746f72656420626c6f636b2000ff7f20656e64";
811static const char STORED_PLAIN[] = "4149454e4f532073746f72656420626c6f636b2000ff7f20656e64";
812static const char FIXED_STREAM[] = "4b4c4a4e240e290200";
813static const char FIXED_PLAIN[] = "61626361626361626361626361626361626361626361626361626361626361626361626361626361626321";
814static const char DYNAMIC_STREAM[] =
815 "75525b12c2200cbc0a67f04614538711689db6eaf11df280a4d22f1ed9ddec068adfe31bdc06e1e6a6e4c3f30329b9c7b6ba3907977d4cd3f2c57d21e41de6e47740889421436e9caed277f51e415ad4b613dd06d58d642faba5b6f6a28c697c84b26c0a8ab73a91a831d2b0755d56ecc363384f67e416f1af030e1864661d2a0b834e5c625ba8829eda042f8c1b361d18a1873b7e026c50d46720fef5971049e6d8c5e6b127f1c0d6fa65ed70f26b42fccdae124c6634aeb352b5fd1116aab01f";
816static const char DYNAMIC_SHA256[] = "384833836853e0d0bbe4d054c4f167ce73bf9c120e749d76da574a55c1b0516a";
817#define DYNAMIC_LEN 760
818/* The GB10B RM_RISCV_UCODE_DESC arrays (DBG and PROD are byte-identical),
819 * 28 bytes of fixed-Huffman deflate, from the pinned driver file. */
820static const char GB10B_DESC_STREAM[] = "636520027041f13220de00c4be4c0c8c78f40100b72bc9c254000000";
821static const uint32_t GB10B_DESC_WORDS[21] = {5, 0, 0, 0, 0, 0, 0, 0, 0, 0xa00, 0xa00, 0xa600, 0xb000, 0x24d00, 1, 0, 0, 0, 0, 0, 0};
822
823/* Synthetic bindata file generator. */
824typedef struct { const char *label, *fname; int compressed; uint32_t data_size; const uint8_t *bytes; size_t n; } fx_array;
825
826static size_t fx_emit(char *buf, size_t cap, const char *func, const fx_array *a, int n) {
827 size_t o = 0;
828 const char *stem = func + strlen("kgspGetBinArchive");
829#define EMIT(...) do { int w_ = snprintf(buf + o, cap - o, __VA_ARGS__); if (w_ < 0 || (size_t)w_ >= cap - o) return 0; o += (size_t)w_; } while (0)
830 EMIT("/* synthetic */\n\n");
831 for (int i = 0; i < n; i++) {
832 EMIT("#if defined(BINDATA_INCLUDE_DATA)\n//\n// FUNCTION: %s(\"BINDATA_LABEL_%s\")\n// FILE NAME: %s\n// FILE TYPE: BINARY\n// VAR NAME: N/A\n// COMPRESSION: %s\n// COMPLEX_STRUCT: NO\n// DATA SIZE (bytes): %u\n// COMPRESSED SIZE (bytes): ",
833 func, a[i].label, a[i].fname, a[i].compressed ? "YES" : "NO", a[i].data_size);
834 if (a[i].compressed) EMIT("%zu\n", a[i].n); else EMIT("N/A\n");
835 EMIT("//\nstatic BINDATA_CONST NvU8 kgspBinArchive%s_BINDATA_LABEL_%s_data[] = \n{\n", stem, a[i].label);
836 for (size_t k = 0; k < a[i].n; k++) {
837 if (k % 16 == 0) EMIT(" ");
838 EMIT("0x%02x,%s", a[i].bytes[k], (k % 16 == 15 || k + 1 == a[i].n) ? "\n" : " ");
839 }
840 EMIT("};\n#endif // defined(BINDATA_INCLUDE_DATA)\n\n#if defined(BINDATA_INCLUDE_STORAGE_PVT_DECL)\nBINDATA_STORAGE_PVT kgspBinArchive%s_BINDATA_LABEL_%s_storage_pvt;\n#endif // defined(BINDATA_INCLUDE_STORAGE_PVT_DECL)\n\n", stem, a[i].label);
841 EMIT("#if defined(BINDATA_INCLUDE_STORAGE_PVT_DEFN)\n{\n %u, // uncompressed data size (bytes)\n %zu, // compressed data size (bytes)\n kgspBinArchive%s_BINDATA_LABEL_%s_data, // compressed data pointer\n %s, // is pData compressed?\n NV_TRUE, // contain information for file overriding?\n NV_FALSE, // is the data referenced during load?\n},\n#endif // defined(BINDATA_INCLUDE_STORAGE_PVT_DEFN)\n\n",
842 a[i].data_size, a[i].n, stem, a[i].label, a[i].compressed ? "NV_TRUE" : "NV_FALSE");
843 }
844 EMIT("#if defined(BINDATA_INCLUDE_ARCHIVE)\n//\n// Bindata Archive structure\n//\nstatic const BINDATA_ARCHIVE __%s =\n{\n %d, // entryNum\n {\n // entries[] : { label, pBinStorage }\n", func, n);
845 for (int i = 0; i < n; i++)
846 EMIT(" { BINDATA_LABEL_%s , (const PBINDATA_STORAGE) &g_bindata_pvt[__idx_kgspBinArchive%s_BINDATA_LABEL_%s] },\n", a[i].label, stem, a[i].label);
847 EMIT(" }\n};\n\n#endif // defined(BINDATA_INCLUDE_ARCHIVE)\n");
848#undef EMIT
849 return o;
850}
851
852static int fx_try(const char *text, size_t len, char *reason, size_t cap) {
853 bd_file *f = calloc(1, sizeof *f);
854 if (!f) return -1;
855 int rc = parse_file(f, text, len);
856 if (rc == 0) rc = check_semantics(f, NULL);
857 snprintf(reason, cap, "%s", f->reason);
858 bd_free(f);
859 free(f);
860 return rc;
861}
862
863static void expect_refused(const char *text, size_t len, const char *want, const char *what) {
864 char reason[256];
865 int rc = fx_try(text, len, reason, sizeof reason);
866 checks++;
867 if (rc == 0 || !strstr(reason, want)) {
868 failures++;
869 printf("FAIL: %s: rc=%d reason='%s' (want '%s')\n", what, rc, reason, want);
870 }
871}
872
873/* Replace the first occurrence of `from` in buf with `to` (same or shorter
874 * length is not required; the buffer is regenerated for each mutation). */
875static size_t mutate(char *buf, size_t len, size_t cap, const char *from, const char *to, int occurrence) {
876 char *p = buf;
877 for (int i = 0; i < occurrence; i++) {
878 p = strstr(p, from);
879 if (!p) return 0;
880 if (i + 1 < occurrence) p += strlen(from);
881 }
882 size_t fl = strlen(from), tl = strlen(to);
883 if (len - fl + tl >= cap) return 0;
884 memmove(p + tl, p + fl, len - (size_t)(p - buf) - fl + 1);
885 memcpy(p, to, tl);
886 return len - fl + tl;
887}
888
889/* gzip body (no header) holding one stored block: 5 + n + 8 bytes. */
890static void stored_block(const uint8_t *src, size_t n, uint8_t *dst) {
891 dst[0] = 1;
892 dst[1] = (uint8_t)n; dst[2] = (uint8_t)(n >> 8);
893 dst[3] = (uint8_t)~dst[1]; dst[4] = (uint8_t)~dst[2];
894 memcpy(dst + 5, src, n);
895 uint32_t crc = crc32_bytes(src, n);
896 for (int i = 0; i < 4; i++) { dst[5 + n + i] = (uint8_t)(crc >> (8 * i)); dst[9 + n + i] = (uint8_t)(n >> (8 * i)); }
897}
898
899static void put_desc(const uint32_t *w, uint8_t *desc) {
900 for (int i = 0; i < 21; i++) { desc[4 * i] = (uint8_t)w[i]; desc[4 * i + 1] = (uint8_t)(w[i] >> 8); desc[4 * i + 2] = (uint8_t)(w[i] >> 16); desc[4 * i + 3] = (uint8_t)(w[i] >> 24); }
901}
902
903static int cmd_selftest(void) {
904 uint8_t buf[1024], out[1024], h[48];
905 char hx[97];
906 const char *why;
907
908 /* SHA-384 known answers (FIPS 180-4 examples). */
909 sha384_hash((const uint8_t *)"", 0, h); hex(h, 48, hx);
910 check(strcmp(hx, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") == 0, "sha384 empty");
911 sha384_hash((const uint8_t *)"abc", 3, h); hex(h, 48, hx);
912 check(strcmp(hx, "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7") == 0, "sha384 abc");
913 {
914 uint8_t *big = malloc(1000000);
915 check(big != NULL, "alloc 1e6");
916 if (big) {
917 memset(big, 'a', 1000000);
918 sha384_ctx c; sha384_init(&c);
919 for (size_t o = 0; o < 1000000; o += 777) sha384_update(&c, big + o, o + 777 <= 1000000 ? 777 : 1000000 - o);
920 sha384_final(&c, h); hex(h, 48, hx);
921 check(strncmp(hx, "9d0e1809716474cb086e834e310a4a1c", 32) == 0, "sha384 a*1e6 streamed");
922 free(big);
923 }
924 }
925
926 /* Inflater known answers. */
927 size_t n = unhex(STORED_STREAM, buf, sizeof buf), pn = unhex(STORED_PLAIN, out + 512, 512);
928 check(inflate_raw(buf, n, out, pn, &why) == 0 && memcmp(out, out + 512, pn) == 0, "inflate stored block");
929 n = unhex(FIXED_STREAM, buf, sizeof buf); pn = unhex(FIXED_PLAIN, out + 512, 512);
930 check(inflate_raw(buf, n, out, pn, &why) == 0 && memcmp(out, out + 512, pn) == 0, "inflate fixed block");
931 n = unhex(DYNAMIC_STREAM, buf, sizeof buf);
932 {
933 uint8_t d[32]; char dh[65];
934 check(inflate_raw(buf, n, out, DYNAMIC_LEN, &why) == 0, "inflate dynamic block");
935 sha256_hash(out, DYNAMIC_LEN, d); hex(d, 32, dh);
936 check(strcmp(dh, DYNAMIC_SHA256) == 0, "inflate dynamic block content");
937 check(inflate_raw(buf, n - 1, out, DYNAMIC_LEN, &why) != 0 && strstr(why, "exhausted"), "inflate truncated dynamic refused");
938 check(inflate_raw(buf, n, out, DYNAMIC_LEN - 1, &why) != 0 && strstr(why, "longer than declared"), "inflate short declared size refused");
939 check(inflate_raw(buf, n, out, DYNAMIC_LEN + 1, &why) != 0 && strstr(why, "shorter than declared"), "inflate long declared size refused");
940 uint8_t t[sizeof buf + 1]; memcpy(t, buf, n); t[n] = 0;
941 check(inflate_raw(t, n + 1, out, DYNAMIC_LEN, &why) != 0 && strstr(why, "trailing"), "inflate trailing byte refused");
942 }
943 check(crc32_bytes((const uint8_t *)"123456789", 9) == 0xcbf43926u, "crc32 check value");
944 n = unhex(GB10B_DESC_STREAM, buf, sizeof buf);
945 check(n == 28 && unpack_gz_body(buf, n, out, DESC_BYTES, &why) == 0, "unpack GB10B descriptor array (deflate + CRC-32 + ISIZE)");
946 check(get32le(buf + 24) == 84 && get32le(buf + 20) == crc32_bytes(out, 84), "GB10B descriptor trailer fields");
947 { uint8_t t[28]; memcpy(t, buf, 28); t[21] ^= 1; check(unpack_gz_body(t, 28, out, DESC_BYTES, &why) != 0 && strstr(why, "CRC-32"), "GB10B descriptor CRC flip refused");
948 memcpy(t, buf, 28); t[24] = 83; check(unpack_gz_body(t, 28, out, DESC_BYTES, &why) != 0 && strstr(why, "ISIZE"), "GB10B descriptor ISIZE flip refused");
949 check(unpack_gz_body(t, 8, out, DESC_BYTES, &why) != 0 && strstr(why, "shorter than"), "short compressed array refused"); }
950 {
951 riscv_desc d; decode_desc(out, &d);
952 int same = 1;
953 for (int i = 0; i < 21; i++) if (get32le(out + 4 * i) != GB10B_DESC_WORDS[i]) same = 0;
954 check(same, "GB10B descriptor words");
955 check(d.version == 5 && d.manifest_off == 0 && d.manifest_size == 0xa00 && d.mdata_off == 0xa00 && d.mdata_size == 0xa600 && d.mcode_off == 0xb000 && d.mcode_size == 0x24d00 && d.monitor_enabled == 1, "GB10B descriptor fields");
956 check(d.mcode_off + d.mcode_size <= 196608u, "GB10B descriptor fits the 196608-byte image");
957 }
958 {
959 uint8_t bad[1] = {0x07}; /* BFINAL=1, BTYPE=3 */
960 check(inflate_raw(bad, 1, out, 1, &why) != 0 && strstr(why, "block type 3"), "inflate block type 3 refused");
961 uint8_t st[8] = {1, 2, 0, 0xfd, 0xfe, 'a', 'b', 0}; /* NLEN wrong */
962 check(inflate_raw(st, 7, out, 2, &why) != 0 && strstr(why, "length check"), "inflate stored NLEN refused");
963 }
964
965 /* Synthetic bindata files. File A mirrors the FMC archive (image, hash,
966 * sig, pkey); file B mirrors the boot archive (image + compressed desc). */
967 static uint8_t image[4096], sig[384], pkey[384], desc[84], desc_st[5 + 84 + 8], image2[0x3000];
968 for (size_t i = 0; i < sizeof image; i++) image[i] = (uint8_t)(i * 7 + 3);
969 for (size_t i = 0; i < 384; i++) { sig[i] = (uint8_t)(255 - i); pkey[i] = (uint8_t)(i ^ 0x5a); }
970 sha384_hash(image, sizeof image, h);
971 const uint32_t dw[21] = {5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0};
972 put_desc(dw, desc);
973 stored_block(desc, 84, desc_st);
974 for (size_t i = 0; i < sizeof image2; i++) image2[i] = (uint8_t)(i * 13 + 1);
975 const fx_array fa[4] = {
976 {"UCODE_IMAGE", "kernel/inc/gspcc/bin/test_gfw_image.bin", 0, sizeof image, image, sizeof image},
977 {"UCODE_HASH", "kernel/inc/gspcc/bin/test_gfw_hash.bin", 0, 48, h, 48},
978 {"UCODE_SIG", "kernel/inc/gspcc/bin/test_gfw_sig.bin", 0, 384, sig, 384},
979 {"UCODE_PKEY", "kernel/inc/gspcc/bin/test_gfw_pub_key.bin", 0, 384, pkey, 384},
980 };
981 const fx_array fb[4] = {
982 {"UCODE_IMAGE_DBG", "kernel/inc/gspcc/bin/test_dbg_image.bin", 0, sizeof image2, image2, sizeof image2},
983 {"UCODE_DESC_DBG", "kernel/inc/gspcc/bin/test_dbg_desc.bin", 1, 84, desc_st, sizeof desc_st},
984 {"UCODE_IMAGE_PROD", "kernel/inc/gspcc/bin/test_prd_image.bin", 0, sizeof image2, image2, sizeof image2},
985 {"UCODE_DESC_PROD", "kernel/inc/gspcc/bin/test_prd_desc.bin", 1, 84, desc_st, sizeof desc_st},
986 };
987 size_t cap = 256 * 1024;
988 char *ta = malloc(cap), *tb = malloc(cap), *m = malloc(cap);
989 check(ta && tb && m, "alloc fixtures");
990 if (!(ta && tb && m)) return 1;
991 size_t la = fx_emit(ta, cap, "kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST", fa, 4);
992 size_t lb = fx_emit(tb, cap, "kgspGetBinArchiveGspRmBoot_TEST", fb, 4);
993 check(la > 0 && lb > 0, "emit fixtures");
994 {
995 char reason[256];
996 check(fx_try(ta, la, reason, sizeof reason) == 0, "fixture A extracts");
997 check(fx_try(tb, lb, reason, sizeof reason) == 0, "fixture B extracts");
998 bd_file *f = calloc(1, sizeof *f);
999 if (f && parse_file(f, tb, lb) == 0) {
1000 check(f->n == 4 && f->b[1].compressed == 1 && f->b[1].plain_len == 84 && memcmp(f->b[1].plain, desc, 84) == 0, "fixture B descriptor inflated");
1001 check(f->b[0].plain_len == sizeof image2 && memcmp(f->b[0].plain, image2, sizeof image2) == 0, "fixture B image bytes");
1002 } else check(0, "fixture B reparse");
1003 if (f) { bd_free(f); free(f); }
1004 }
1005
1006 /* Mutations of file A (uncompressed arrays). */
1007 struct { const char *from, *to; int occ; const char *want; const char *what; } ma[] = {
1008 {"// DATA SIZE (bytes): 4096", "// DATA SIZE (bytes): 4095", 1, "more bytes than the declared size", "data size one short"},
1009 {"// DATA SIZE (bytes): 4096", "// DATA SIZE (bytes): 4097", 1, "fewer bytes than the declared size", "data size one long"},
1010 {" 4096, // uncompressed", " 4095, // uncompressed", 1, "uncompressed size differs from DATA SIZE", "pvt uncompressed size"},
1011 {" 4096, // compressed data size", " 4000, // compressed data size", 1, "compressed size differs from the header", "pvt compressed size"},
1012 {" NV_FALSE, // is pData compressed?", " NV_TRUE, // is pData compressed?", 1, "compressed flag disagrees", "pvt compressed flag"},
1013 {"// COMPRESSION: NO", "// COMPRESSION: YES", 1, "COMPRESSED SIZE missing", "compression yes without size"},
1014 {"// COMPRESSED SIZE (bytes): N/A", "// COMPRESSED SIZE (bytes): 100", 1, "COMPRESSED SIZE given with COMPRESSION NO", "compressed size with no"},
1015 {"// FILE TYPE: BINARY", "// FILE TYPE: TEXT", 1, "FILE TYPE is not BINARY", "file type"},
1016 {"// COMPLEX_STRUCT: NO", "// COMPLEX_STRUCT: YES", 1, "COMPLEX_STRUCT is not NO", "complex struct"},
1017 {"0x03,", "0y03,", 1, "non-hex token", "non-hex token"},
1018 {"0x03,", "0x03 ", 1, "without a trailing comma", "missing comma"},
1019 {"};\n#endif // defined(BINDATA_INCLUDE_DATA)", "\n#endif // defined(BINDATA_INCLUDE_DATA)", 1, "non-hex token", "array end removed"},
1020 {"(\"BINDATA_LABEL_UCODE_PKEY\")", "(\"BINDATA_LABEL_UCODE_SIG\")", 1, "duplicate label", "duplicate label"},
1021 {"(\"BINDATA_LABEL_UCODE_SIG\")", "(\"BINDATA_LABEL_UCODE_FOO\")", 1, "array identifier is not the expected one", "label vs identifier"},
1022 {"kgspBinArchiveGspRmFmcGfwProdSigned_TEST_BINDATA_LABEL_UCODE_SIG_data, // compressed data pointer", "kgspBinArchiveGspRmFmcGfwProdSigned_TEST_BINDATA_LABEL_UCODE_PKEY_data, // compressed data pointer", 1, "data pointer is not the array", "pvt pointer"},
1023 {" 4, // entryNum", " 3, // entryNum", 1, "entryNum differs", "archive entry count"},
1024 {"{ BINDATA_LABEL_UCODE_SIG ,", "{ BINDATA_LABEL_UCODE_PKEY ,", 1, "entry order or label differs", "archive label order"},
1025 {"&g_bindata_pvt[__idx_kgspBinArchiveGspRmFmcGfwProdSigned_TEST_BINDATA_LABEL_UCODE_SIG]", "&g_bindata_pvt[__idx_kgspBinArchiveGspRmFmcGfwProdSigned_TEST_BINDATA_LABEL_UCODE_PKEY]", 1, "storage index is not this array", "archive storage index"},
1026 {"static const BINDATA_ARCHIVE __kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST =", "static const BINDATA_ARCHIVE __kgspGetBinArchiveOther_TEST =", 1, "archive table name is not the file's function", "archive name"},
1027 {"// FUNCTION: kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST(\"BINDATA_LABEL_UCODE_PKEY\")", "// FUNCTION: kgspGetBinArchiveGspRmBoot_TEST(\"BINDATA_LABEL_UCODE_PKEY\")", 1, "different function", "mixed functions"},
1028 {"// DATA SIZE (bytes): 48", "// DATA SIZE (bytes): 47", 1, "more bytes than the declared size", "hash size via array"},
1029 {"// COMPRESSION: NO", "// COMPRESSION: MAYBE", 1, "neither YES nor NO", "compression keyword"},
1030 };
1031 for (size_t i = 0; i < sizeof ma / sizeof ma[0]; i++) {
1032 memcpy(m, ta, la + 1);
1033 size_t lm = mutate(m, la, cap, ma[i].from, ma[i].to, ma[i].occ);
1034 check(lm > 0, ma[i].what);
1035 if (lm) expect_refused(m, lm, ma[i].want, ma[i].what);
1036 }
1037 /* Hash that does not match the image: flip one byte of the hash array. */
1038 {
1039 memcpy(m, ta, la + 1);
1040 char from[8], to[8];
1041 snprintf(from, sizeof from, "0x%02x,", h[0]);
1042 snprintf(to, sizeof to, "0x%02x,", h[0] ^ 1);
1043 /* the hash array is the second array; its first byte follows the IMAGE array */
1044 char *p = strstr(m, "UCODE_HASH_data[] = \n{\n ");
1045 check(p != NULL, "locate hash array");
1046 if (p) { p += strlen("UCODE_HASH_data[] = \n{\n "); check(strncmp(p, from, 5) == 0, "hash first byte"); memcpy(p, to, 5); expect_refused(m, la, "not SHA-384 of UCODE_IMAGE", "hash mismatch"); }
1047 }
1048 /* Image byte flipped: also a hash mismatch. */
1049 {
1050 memcpy(m, ta, la + 1);
1051 char *p = strstr(m, "UCODE_IMAGE_data[] = \n{\n 0x03,");
1052 check(p != NULL, "locate image array");
1053 if (p) { p += strlen("UCODE_IMAGE_data[] = \n{\n "); memcpy(p, "0x04,", 5); expect_refused(m, la, "not SHA-384 of UCODE_IMAGE", "image byte flipped"); }
1054 }
1055 /* Truncated file (ends inside the archive). */
1056 {
1057 memcpy(m, ta, la + 1);
1058 char *p = strstr(m, " { BINDATA_LABEL_UCODE_PKEY");
1059 check(p != NULL, "locate last archive entry");
1060 if (p) { *p = 0; expect_refused(m, (size_t)(p - m), "archive: missing entry", "truncated archive"); }
1061 memcpy(m, ta, la + 1);
1062 p = strstr(m, "#if defined(BINDATA_INCLUDE_ARCHIVE)");
1063 if (p) { *p = 0; expect_refused(m, (size_t)(p - m), "no archive table", "no archive table"); }
1064 }
1065 /* File ends inside an array. */
1066 {
1067 memcpy(m, ta, la + 1);
1068 char *p = strstr(m, "};\n#endif // defined(BINDATA_INCLUDE_DATA)");
1069 check(p != NULL, "locate first array end");
1070 if (p) { *p = 0; expect_refused(m, (size_t)(p - m), "file ends inside the array", "file ends inside array"); }
1071 }
1072 /* Empty and foreign files. */
1073 expect_refused("", 0, "no arrays found", "empty file");
1074 expect_refused("int x;\nstatic BINDATA_CONST NvU8 foo[] = \n{\n};\n", 44, "data before the first FUNCTION", "array before header");
1075
1076 /* Mutations of file B: regenerate the fixture with a changed descriptor
1077 * or a damaged compressed array, then expect the refusal. */
1078 struct { uint32_t words[21]; int nlen_flip, crc_flip, isize_flip, cut; uint32_t data_size; const char *want, *what; } mbs[] = {
1079 {{4, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "descriptor version is not 5", "desc version 4"},
1080 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 0, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "monitor not enabled", "desc monitor disabled"},
1081 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2a01, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "monitor-code region outside the image", "desc code past image"},
1082 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x610, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "monitor-code region outside the image or unaligned", "desc code unaligned"},
1083 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "monitor-code region", "desc code size zero"},
1084 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x3000, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "monitor-data region outside the image", "desc data past image"},
1085 {{5, 0, 0, 0, 0, 0, 0, 0, 0x100, 0x2f80, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 84, "manifest region outside the image", "desc manifest past image"},
1086 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 1, 0, 0, 0, 84, "stored block length check failed", "desc stored NLEN"},
1087 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 1, 0, 0, 84, "CRC-32 mismatch", "desc CRC flipped"},
1088 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 1, 0, 84, "ISIZE differs", "desc ISIZE flipped"},
1089 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 83, "output longer than declared size", "desc declared 83"},
1090 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 0, 85, "output shorter than declared size", "desc declared 85"},
1091 {{5, 0, 0, 0, 0, 0, 0, 0, 0, 0x200, 0x200, 0x400, 0x600, 0x2400, 1, 0, 0, 0, 0, 0x8000, 0}, 0, 0, 0, 5, 84, "inflate: input exhausted", "desc stream cut"},
1092 };
1093 for (size_t i = 0; i < sizeof mbs / sizeof mbs[0]; i++) {
1094 uint8_t d2[84], st[5 + 84 + 8];
1095 put_desc(mbs[i].words, d2);
1096 stored_block(d2, 84, st);
1097 if (mbs[i].nlen_flip) st[4] ^= 1;
1098 if (mbs[i].crc_flip) st[5 + 84] ^= 1;
1099 if (mbs[i].isize_flip) st[5 + 84 + 4] ^= 1;
1100 fx_array fm[2] = {fb[0], fb[1]};
1101 fm[1].bytes = st; fm[1].n = sizeof st - (size_t)mbs[i].cut; fm[1].data_size = mbs[i].data_size;
1102 size_t lm = fx_emit(m, cap, "kgspGetBinArchiveGspRmBoot_TEST", fm, 2);
1103 check(lm > 0, mbs[i].what);
1104 if (lm) expect_refused(m, lm, mbs[i].want, mbs[i].what);
1105 }
1106 /* Text mutations of file B. */
1107 struct { const char *from, *to; const char *want, *what; } mbt[] = {
1108 {"(\"BINDATA_LABEL_UCODE_IMAGE_PROD\")", "(\"BINDATA_LABEL_UCODE_IMAGE_PRD\")", "array identifier is not the expected one", "renamed image (identifier catches)"},
1109 {"(\"BINDATA_LABEL_UCODE_DESC_PROD\")", "(\"BINDATA_LABEL_UCODE_DESC_XYZ\")", "array identifier is not the expected one", "renamed desc (identifier catches)"},
1110 {" 97, // compressed data size", " 98, // compressed data size", "compressed size differs from the header", "pvt compressed size (B)"},
1111 };
1112 for (size_t i = 0; i < sizeof mbt / sizeof mbt[0]; i++) {
1113 memcpy(m, tb, lb + 1);
1114 size_t lm = mutate(m, lb, cap, mbt[i].from, mbt[i].to, 1);
1115 check(lm > 0, mbt[i].what);
1116 if (lm) expect_refused(m, lm, mbt[i].want, mbt[i].what);
1117 }
1118 /* Semantic refusals that need a consistent archive: rebuild fixtures. */
1119 {
1120 fx_array fc[2] = {fb[0], fb[1]};
1121 fc[1].label = "UCODE_DESC_PROD";
1122 size_t lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmBoot_TEST", fc, 2);
1123 check(lc > 0, "emit fixture C");
1124 if (lc) expect_refused(m, lc, "descriptor without a matching image", "desc without image");
1125 fx_array fd[1] = {fb[0]};
1126 fd[0].label = "UCODE_OTHER";
1127 lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmBoot_TEST", fd, 1);
1128 if (lc) expect_refused(m, lc, "unknown label", "unknown label");
1129 fx_array fe[2] = {fa[0], fa[2]};
1130 fe[1].label = "UCODE_HASH";
1131 lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST", fe, 2);
1132 if (lc) expect_refused(m, lc, "hash array is not 48 bytes", "hash size");
1133 fx_array ff[1] = {fa[2]};
1134 ff[0].data_size = 383; ff[0].n = 383;
1135 lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST", ff, 1);
1136 if (lc) expect_refused(m, lc, "UCODE_SIG is not 384 bytes", "sig size");
1137 fx_array fg[1] = {fa[1]};
1138 lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmFmcGfwProdSigned_TEST", fg, 1);
1139 if (lc) expect_refused(m, lc, "hash array without UCODE_IMAGE", "hash without image");
1140 fx_array fi[2] = {fb[0], fb[1]};
1141 fi[1].compressed = 1; fi[1].n = 0;
1142 lc = fx_emit(m, cap, "kgspGetBinArchiveGspRmBoot_TEST", fi, 2);
1143 if (lc) expect_refused(m, lc, "COMPRESSED SIZE missing", "compressed size zero");
1144 }
1145 free(ta); free(tb); free(m);
1146 printf("CK_GSP_BINDATA_EXTRACT_SELFTEST: %s (%d checks, %d failures)\n", failures ? "FAIL" : "PASS", checks, failures);
1147 return failures ? 1 : 0;
1148}
1149
1150int main(int argc, char **argv) {
1151 if (argc >= 2 && strcmp(argv[1], "extract") == 0) return cmd_extract(argc - 2, argv + 2);
1152 if (argc == 2 && strcmp(argv[1], "selftest") == 0) return cmd_selftest();
1153 fprintf(stderr, "usage: ck_gsp_bindata_extract extract FILE [--out DIR]\n ck_gsp_bindata_extract selftest\n");
1154 return 1;
1155}