tinyc-web 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -249,6 +249,19 @@ const worker = new TinycWorker({ shimModules: ['./my-shims.mjs'] });
249
249
  // my-shims.mjs: export default { host_log: (ctx, ptr) => { ... } };
250
250
  ```
251
251
 
252
+ ## SIMD intrinsics
253
+
254
+ Each target's sysroot carries that target's SIMD headers in its
255
+ default include set. The native targets carry the same headers
256
+ as the other packages (`arm_neon.h` for AArch64, the
257
+ `immintrin.h` set for x86-64, `riscv_vector.h` for riscv64).
258
+ The `wasm32-wasi` target carries `#include <wasm_simd128.h>` —
259
+ the WebAssembly SIMD128 intrinsic set — plus wasm forms of
260
+ `arm_neon.h`, `xmmintrin.h` and `emmintrin.h`: subsets of the
261
+ NEON and SSE/SSE2 surfaces mapped onto v128 operations. See the
262
+ root README's "SIMD intrinsics" section for the per-header
263
+ breakdown.
264
+
252
265
  ## Tests
253
266
 
254
267
  ```
package/README.zh-CN.md CHANGED
@@ -249,6 +249,17 @@ const worker = new TinycWorker({ shimModules: ['./my-shims.mjs'] });
249
249
  // my-shims.mjs: export default { host_log: (ctx, ptr) => { ... } };
250
250
  ```
251
251
 
252
+ ## SIMD 内建函数
253
+
254
+ 每个目标的 sysroot 在其默认头文件集里带该目标的 SIMD 头。
255
+ 原生目标带与其它包相同的头(AArch64 用 `arm_neon.h`、x86-64
256
+ 用 `immintrin.h` 一组、riscv64 用 `riscv_vector.h`)。
257
+ `wasm32-wasi` 目标带 `#include <wasm_simd128.h>`——
258
+ WebAssembly SIMD128 内建集——另带 wasm 形态的 `arm_neon.h`、
259
+ `xmmintrin.h`、`emmintrin.h`:NEON 与 SSE/SSE2 表面中映射到
260
+ v128 操作的子集。逐个头的覆盖明细见根 README 的「SIMD 内建
261
+ 函数」一节。
262
+
252
263
  ## 测试
253
264
 
254
265
  ```
package/package.json CHANGED
@@ -1 +1 @@
1
- {"browser":"./index.mjs","description":"TinyC (TCC) in the browser: the compiler built to WebAssembly, one module per code generation target (wasm32-wasi by default), with a JS glue layer, a virtual filesystem and a Web Worker interface.","exports":{".":"./index.mjs","./package.json":"./package.json","./sysroot-manifest":"./sysroot-manifest.json","./sysroot-manifests/*":"./sysroot-manifests/*","./worker":"./worker.mjs"},"files":["README.md","README.zh-CN.md","index.mjs","vfs-store.mjs","tinyc-web.js","worker.mjs","sysroot-manifest.json","sysroot-manifests","tcc-*.mjs","tcc-*.wasm"],"keywords":["tcc","tinycc","compiler","wasm","webassembly","browser","cross-compiler"],"license":"LGPL-2.1-or-later","main":"./index.mjs","module":"./index.mjs","name":"tinyc-web","scripts":{"build":"./build.sh","build:web":"node build-web-bundle.mjs","test":"node --test test.mjs","test:web":"node --test test-web-bundle.mjs"},"type":"module","version":"0.1.3"}
1
+ {"browser":"./index.mjs","description":"TinyC (TCC) in the browser: the compiler built to WebAssembly, one module per code generation target (wasm32-wasi by default), with a JS glue layer, a virtual filesystem and a Web Worker interface.","exports":{".":"./index.mjs","./package.json":"./package.json","./sysroot-manifest":"./sysroot-manifest.json","./sysroot-manifests/*":"./sysroot-manifests/*","./worker":"./worker.mjs"},"files":["README.md","README.zh-CN.md","index.mjs","runtime-shims.mjs","vfs-store.mjs","tinyc-web.js","worker.mjs","sysroot-manifest.json","sysroot-manifests","tcc-*.mjs","tcc-*.wasm"],"keywords":["tcc","tinycc","compiler","wasm","webassembly","browser","cross-compiler"],"license":"LGPL-2.1-or-later","main":"./index.mjs","module":"./index.mjs","name":"tinyc-web","scripts":{"build":"./build.sh","build:web":"node build-web-bundle.mjs","test":"node --test test.mjs","test:web":"node --test test-web-bundle.mjs"},"type":"module","version":"0.3.0"}
@@ -0,0 +1,1004 @@
1
+ // runtime-shims.mjs: default "env" imports for running wasm32
2
+ // products compiled from C in the browser.
3
+ //
4
+ // A C program compiled to wasm32 imports the libc functions it uses.
5
+ // There is no libc .a to link in this package, so runWasmModule
6
+ // supplies this JS implementation of a common libc subset by
7
+ // default (module name "env"). Every function operates on the
8
+ // running instance's linear memory.
9
+ //
10
+ // Timing: the import functions are created before the instance
11
+ // exists. They never capture the memory directly — they read it
12
+ // through `holder` on every call. The glue (index.mjs) fills
13
+ // holder.memory and holder.instance right after instantiation,
14
+ // before any entry point (_start) is invoked, so by the time a shim
15
+ // can be called the memory is there.
16
+ //
17
+ // Priority: these are the lowest-priority layer. Per-run shims,
18
+ // instance-registered shims, package-global shims and raw
19
+ // options.imports entries all override individual entries (see
20
+ // index.mjs, buildWasmImports).
21
+
22
+ const textEncoder = new TextEncoder();
23
+ const textDecoder = new TextDecoder();
24
+
25
+ /** Thrown by the libc exit/abort shims. The runner in index.mjs
26
+ * catches it and reports { exitCode }, exactly like WASI
27
+ * proc_exit — exiting a guest program never terminates the host. */
28
+ export class ShimExit extends Error {
29
+ constructor(code) {
30
+ super(`tinyc: libc exit(${code})`);
31
+ this.name = 'ShimExit';
32
+ this.exitCode = code;
33
+ }
34
+ }
35
+
36
+ const ALLOC_USED = 0xa110ce11;
37
+
38
+ /**
39
+ * Build the default shim imports.
40
+ *
41
+ * options:
42
+ * io byte IO: { out(Uint8Array), err(Uint8Array),
43
+ * in() -> Uint8Array|string|null } — stdio output goes
44
+ * to out/err as bytes; stdin is pulled from `stdin`
45
+ * first, then from io.in() chunks.
46
+ * holder { memory, instance } — filled by the glue after
47
+ * instantiation (see the timing note above).
48
+ * stdin Uint8Array|string served to fread/fgetc before io.in.
49
+ * heapBase start address of the shim allocator's heap region in
50
+ * linear memory (default 65536). The allocator grows
51
+ * the memory when it runs out.
52
+ * args/env accepted for symmetry with the WASI shim options;
53
+ * libc shims do not consume argv, and getenv returns
54
+ * null by design, so neither is read.
55
+ *
56
+ * Returns { env: { ... } }, ready to merge into an importObject.
57
+ *
58
+ * Allocator rule: malloc/calloc/realloc/free are served by a simple
59
+ * free-list allocator inside the module's linear memory — unless
60
+ * the module exports its own malloc, in which case the shim
61
+ * forwards allocation calls to the module's own allocator and the
62
+ * internal one never touches the heap. (If the module exports no
63
+ * malloc, nothing else can allocate, so there is no conflict; if it
64
+ * does export one, forwarding keeps exactly one allocator in play.)
65
+ */
66
+ export function createDefaultShims(options = {}) {
67
+ const { holder } = options;
68
+ const io = options.io ?? {};
69
+ const emitOut = typeof io.out === 'function' ? io.out : () => {};
70
+ const emitErr = typeof io.err === 'function' ? io.err : () => {};
71
+ const heapBase = options.heapBase ?? 65536;
72
+
73
+ // -- linear memory access (always through the holder) --
74
+ const memory = () => holder?.memory ?? null;
75
+ const u8 = () => new Uint8Array(memory().buffer);
76
+ const dv = () => new DataView(memory().buffer);
77
+ const readU32 = (ptr) => dv().getUint32(ptr, true);
78
+ const writeU32 = (ptr, v) => dv().setUint32(ptr, v >>> 0, true);
79
+ const readBytes = (ptr, len) => u8().slice(ptr, ptr + len);
80
+ const writeBytes = (ptr, data) => { u8().set(data, ptr); };
81
+ const readCString = (ptr, max = 1 << 20) => {
82
+ if (!ptr) return '';
83
+ const m = u8();
84
+ let end = ptr;
85
+ while (end < m.length && end - ptr < max && m[end] !== 0) end++;
86
+ return textDecoder.decode(m.subarray(ptr, end));
87
+ };
88
+ const writeCStringBytes = (ptr, bytes) => {
89
+ writeBytes(ptr, bytes);
90
+ u8()[ptr + bytes.length] = 0;
91
+ return bytes.length;
92
+ };
93
+
94
+ // ---------------------------------------------------------------
95
+ // Allocator: first-fit free list over [heapBase, memory end).
96
+ // Block layout: [payloadSize u32][nextOrUsed u32][payload...];
97
+ // the payload pointer handed out is header + 8.
98
+ // ---------------------------------------------------------------
99
+ let heapTop = 0;
100
+ let freeHead = 0;
101
+
102
+ const moduleAllocator = () => {
103
+ const ex = holder?.instance?.exports;
104
+ return ex && typeof ex.malloc === 'function' ? ex : null;
105
+ };
106
+
107
+ function ensureCapacity(end) {
108
+ const mem = memory();
109
+ if (!mem) return false;
110
+ if (mem.buffer.byteLength >= end) return true;
111
+ const pages = Math.ceil((end - mem.buffer.byteLength) / 65536);
112
+ try {
113
+ mem.grow(pages);
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ function rawMalloc(size) {
121
+ size = Math.max(8, (size + 7) & ~7);
122
+ let prev = 0;
123
+ let cur = freeHead;
124
+ while (cur) {
125
+ const csize = readU32(cur);
126
+ const cnext = readU32(cur + 4);
127
+ if (csize >= size) {
128
+ if (csize - size >= 16) {
129
+ // split: tail stays on the free list
130
+ const rem = cur + 8 + size;
131
+ writeU32(rem, csize - size - 8);
132
+ writeU32(rem + 4, cnext);
133
+ writeU32(cur, size);
134
+ if (prev) writeU32(prev + 4, rem); else freeHead = rem;
135
+ } else {
136
+ if (prev) writeU32(prev + 4, cnext); else freeHead = cnext;
137
+ }
138
+ writeU32(cur + 4, ALLOC_USED);
139
+ return cur + 8;
140
+ }
141
+ prev = cur;
142
+ cur = cnext;
143
+ }
144
+ if (!heapTop) heapTop = heapBase;
145
+ const header = heapTop;
146
+ const end = header + 8 + size;
147
+ if (!ensureCapacity(end)) return 0;
148
+ writeU32(header, size);
149
+ writeU32(header + 4, ALLOC_USED);
150
+ heapTop = end;
151
+ return header + 8;
152
+ }
153
+
154
+ function rawFree(ptr) {
155
+ if (!ptr) return;
156
+ const header = ptr - 8;
157
+ if (readU32(header + 4) !== ALLOC_USED) return; // foreign/double free
158
+ writeU32(header + 4, freeHead);
159
+ freeHead = header;
160
+ }
161
+
162
+ function malloc(size) {
163
+ const own = moduleAllocator();
164
+ return own ? own.malloc(size) : rawMalloc(size);
165
+ }
166
+
167
+ function free(ptr) {
168
+ const own = moduleAllocator();
169
+ if (own && typeof own.free === 'function') {
170
+ own.free(ptr);
171
+ return;
172
+ }
173
+ rawFree(ptr);
174
+ }
175
+
176
+ function calloc(n, size) {
177
+ const own = moduleAllocator();
178
+ if (own && typeof own.calloc === 'function') return own.calloc(n, size);
179
+ const total = n * size;
180
+ const ptr = malloc(total);
181
+ if (ptr) writeBytes(ptr, new Uint8Array(total));
182
+ return ptr;
183
+ }
184
+
185
+ function realloc(ptr, size) {
186
+ if (!ptr) return malloc(size);
187
+ if (size === 0) {
188
+ free(ptr);
189
+ return 0;
190
+ }
191
+ const own = moduleAllocator();
192
+ if (own) {
193
+ if (typeof own.realloc === 'function') return own.realloc(ptr, size);
194
+ const np = own.malloc(size);
195
+ if (!np) return 0;
196
+ // The preserved prefix is what matters; bytes past the old
197
+ // block's end land in the new block's uninitialized tail.
198
+ writeBytes(np, readBytes(ptr, size));
199
+ if (typeof own.free === 'function') own.free(ptr);
200
+ return np;
201
+ }
202
+ const oldSize = readU32(ptr - 8);
203
+ if (size <= oldSize) return ptr;
204
+ const np = rawMalloc(size);
205
+ if (!np) return 0;
206
+ writeBytes(np, readBytes(ptr, oldSize));
207
+ rawFree(ptr);
208
+ return np;
209
+ }
210
+
211
+ // ---------------------------------------------------------------
212
+ // Memory and string functions
213
+ // ---------------------------------------------------------------
214
+ function memcpy(dest, src, n) {
215
+ writeBytes(dest, readBytes(src, n)); // readBytes copies: overlap-safe
216
+ return dest;
217
+ }
218
+ function memmove(dest, src, n) {
219
+ writeBytes(dest, readBytes(src, n));
220
+ return dest;
221
+ }
222
+ function memset(ptr, value, n) {
223
+ u8().fill(value & 0xff, ptr, ptr + n);
224
+ return ptr;
225
+ }
226
+ function memcmp(a, b, n) {
227
+ const ma = u8();
228
+ for (let i = 0; i < n; i++) {
229
+ const d = ma[a + i] - ma[b + i];
230
+ if (d !== 0) return d;
231
+ }
232
+ return 0;
233
+ }
234
+ function strlen(ptr) {
235
+ const m = u8();
236
+ let n = 0;
237
+ while (m[ptr + n] !== 0) n++;
238
+ return n;
239
+ }
240
+ function strcpy(dest, src) {
241
+ writeBytes(dest, readBytes(src, strlen(src) + 1));
242
+ return dest;
243
+ }
244
+ function strncpy(dest, src, n) {
245
+ const m = u8();
246
+ let i = 0;
247
+ while (i < n && m[src + i] !== 0) {
248
+ m[dest + i] = m[src + i];
249
+ i++;
250
+ }
251
+ while (i < n) m[dest + i++] = 0;
252
+ return dest;
253
+ }
254
+ function strcat(dest, src) {
255
+ writeBytes(dest + strlen(dest), readBytes(src, strlen(src) + 1));
256
+ return dest;
257
+ }
258
+ function strncat(dest, src, n) {
259
+ const m = u8();
260
+ const at = dest + strlen(dest);
261
+ let i = 0;
262
+ while (i < n && m[src + i] !== 0) {
263
+ m[at + i] = m[src + i];
264
+ i++;
265
+ }
266
+ m[at + i] = 0;
267
+ return dest;
268
+ }
269
+ function strcmp(a, b) {
270
+ const m = u8();
271
+ let i = 0;
272
+ for (;;) {
273
+ const d = m[a + i] - m[b + i];
274
+ if (d !== 0 || m[a + i] === 0) return d;
275
+ i++;
276
+ }
277
+ }
278
+ function strncmp(a, b, n) {
279
+ const m = u8();
280
+ for (let i = 0; i < n; i++) {
281
+ const d = m[a + i] - m[b + i];
282
+ if (d !== 0 || m[a + i] === 0) return d;
283
+ }
284
+ return 0;
285
+ }
286
+ function strchr(ptr, c) {
287
+ const m = u8();
288
+ const want = c & 0xff;
289
+ let i = 0;
290
+ for (;;) {
291
+ if (m[ptr + i] === want) return ptr + i;
292
+ if (m[ptr + i] === 0) return 0;
293
+ i++;
294
+ }
295
+ }
296
+ function strrchr(ptr, c) {
297
+ const m = u8();
298
+ const want = c & 0xff;
299
+ let found = 0;
300
+ let i = 0;
301
+ for (;;) {
302
+ if (m[ptr + i] === want) found = ptr + i;
303
+ if (m[ptr + i] === 0) return found;
304
+ i++;
305
+ }
306
+ }
307
+ function strstr(haystack, needle) {
308
+ const h = readCString(haystack);
309
+ const ndl = readCString(needle);
310
+ if (ndl === '') return haystack;
311
+ const idx = h.indexOf(ndl);
312
+ return idx < 0 ? 0 : haystack + textEncoder.encode(h.slice(0, idx)).length;
313
+ }
314
+ function strdup(ptr) {
315
+ const copy = readBytes(ptr, strlen(ptr) + 1);
316
+ const dest = malloc(copy.length);
317
+ if (dest) writeBytes(dest, copy);
318
+ return dest;
319
+ }
320
+
321
+ // ---------------------------------------------------------------
322
+ // ctype: table-driven. Flags per byte: upper/lower/digit/space/
323
+ // punct/cntrl/xdigit/blank.
324
+ // ---------------------------------------------------------------
325
+ const CT = (() => {
326
+ const t = new Uint8Array(256);
327
+ const U = 1, L = 2, D = 4, S = 8, P = 16, C = 32, X = 64, B = 128;
328
+ for (let c = 0x00; c < 0x20; c++) t[c] |= C;
329
+ t[0x7f] |= C;
330
+ for (let c = 0x30; c <= 0x39; c++) t[c] |= D | X;
331
+ for (let c = 0x41; c <= 0x46; c++) t[c] |= X;
332
+ for (let c = 0x61; c <= 0x66; c++) t[c] |= X;
333
+ for (let c = 0x41; c <= 0x5a; c++) t[c] |= U;
334
+ for (let c = 0x61; c <= 0x7a; c++) t[c] |= L;
335
+ for (const c of [0x20, 0x09, 0x0a, 0x0b, 0x0c, 0x0d]) t[c] |= S;
336
+ t[0x20] |= B;
337
+ t[0x09] |= B;
338
+ for (let c = 0x21; c <= 0x7e; c++) {
339
+ if (!(t[c] & (U | L | D))) t[c] |= P;
340
+ }
341
+ return { t, U, L, D, S, P, C, X, B };
342
+ })();
343
+ const ctFlag = (bit) => (c) =>
344
+ c >= 0 && c <= 255 ? (CT.t[c] & bit ? 1 : 0) : 0;
345
+ const isupper = ctFlag(CT.U);
346
+ const islower = ctFlag(CT.L);
347
+ const isdigit = ctFlag(CT.D);
348
+ const isspace = ctFlag(CT.S);
349
+ const ispunct = ctFlag(CT.P);
350
+ const iscntrl = ctFlag(CT.C);
351
+ const isxdigit = ctFlag(CT.X);
352
+ const isblank = ctFlag(CT.B);
353
+ const isalpha = (c) => (isupper(c) || islower(c) ? 1 : 0);
354
+ const isalnum = (c) => (isalpha(c) || isdigit(c) ? 1 : 0);
355
+ const isprint = (c) => (c >= 0x20 && c <= 0x7e ? 1 : 0);
356
+ const isgraph = (c) => (c >= 0x21 && c <= 0x7e ? 1 : 0);
357
+ const tolower = (c) => (isupper(c) ? c + 32 : c);
358
+ const toupper = (c) => (islower(c) ? c - 32 : c);
359
+
360
+ // ---------------------------------------------------------------
361
+ // stdlib conversions
362
+ // ---------------------------------------------------------------
363
+ function scanInt(ptr, base) {
364
+ const s = readCString(ptr);
365
+ let i = 0;
366
+ while (i < s.length && ' \t\n\v\f\r'.includes(s[i])) i++;
367
+ let sign = 1n;
368
+ if (s[i] === '+' || s[i] === '-') {
369
+ if (s[i] === '-') sign = -1n;
370
+ i++;
371
+ }
372
+ let b = base;
373
+ if (b === 0) {
374
+ if (s[i] === '0' && (s[i + 1] === 'x' || s[i + 1] === 'X')) b = 16;
375
+ else if (s[i] === '0') b = 8;
376
+ else b = 10;
377
+ }
378
+ if (b === 16 && s[i] === '0' && (s[i + 1] === 'x' || s[i + 1] === 'X')) i += 2;
379
+ const digits = '0123456789abcdefghijklmnopqrstuvwxyz';
380
+ let value = 0n;
381
+ let any = false;
382
+ while (i < s.length) {
383
+ const d = digits.indexOf(s[i].toLowerCase());
384
+ if (d < 0 || d >= b) break;
385
+ value = value * BigInt(b) + BigInt(d);
386
+ i++;
387
+ any = true;
388
+ }
389
+ return { value: sign * value, consumed: any ? i : 0, any };
390
+ }
391
+ function finishEndptr(endptr, ptr, consumed) {
392
+ if (endptr) writeU32(endptr, ptr + consumed);
393
+ }
394
+ const I32_MIN = -2147483648n;
395
+ const I32_MAX = 2147483647n;
396
+ const U32_MAX = 4294967295n;
397
+ function clampBig(v, lo, hi) {
398
+ return v < lo ? lo : v > hi ? hi : v;
399
+ }
400
+ function strtol(ptr, endptr, base) {
401
+ const r = scanInt(ptr, base | 0);
402
+ finishEndptr(endptr, ptr, r.consumed);
403
+ return Number(clampBig(r.value, I32_MIN, I32_MAX));
404
+ }
405
+ function strtoul(ptr, endptr, base) {
406
+ const r = scanInt(ptr, base | 0);
407
+ finishEndptr(endptr, ptr, r.consumed);
408
+ return Number(clampBig(r.value, 0n, U32_MAX)) >>> 0;
409
+ }
410
+ function strtoll(ptr, endptr, base) {
411
+ const r = scanInt(ptr, base | 0);
412
+ finishEndptr(endptr, ptr, r.consumed);
413
+ return r.value;
414
+ }
415
+ function strtoull(ptr, endptr, base) {
416
+ const r = scanInt(ptr, base | 0);
417
+ finishEndptr(endptr, ptr, r.consumed);
418
+ return r.value < 0n ? 0n : r.value;
419
+ }
420
+ function scanFloat(ptr) {
421
+ const s = readCString(ptr);
422
+ const m = /^[\s]*[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(s) ??
423
+ /^[\s]*[+-]?(inf(inity)?|nan)/i.exec(s);
424
+ if (!m) return { value: 0, consumed: 0 };
425
+ return { value: parseFloat(m[0]), consumed: m[0].length };
426
+ }
427
+ function strtod(ptr, endptr) {
428
+ const r = scanFloat(ptr);
429
+ finishEndptr(endptr, ptr, r.consumed);
430
+ return r.value;
431
+ }
432
+ function strtof(ptr, endptr) {
433
+ return Math.fround(strtod(ptr, endptr));
434
+ }
435
+ function atoi(ptr) {
436
+ return Number(clampBig(scanInt(ptr, 10).value, I32_MIN, I32_MAX));
437
+ }
438
+ function atol(ptr) {
439
+ return atoi(ptr);
440
+ }
441
+ function atoll(ptr) {
442
+ return scanInt(ptr, 10).value;
443
+ }
444
+ function atof(ptr) {
445
+ return scanFloat(ptr).value;
446
+ }
447
+ const abs = (v) => Math.abs(v | 0);
448
+ const labs = (v) => Math.abs(v | 0);
449
+ const llabs = (v) => (v < 0n ? -v : v);
450
+
451
+ let randState = 1;
452
+ function srand(seed) {
453
+ randState = seed >>> 0 || 1;
454
+ }
455
+ function rand() {
456
+ randState = (Math.imul(randState, 1103515245) + 12345) & 0x7fffffff;
457
+ return (randState >> 16) & 0x7fff;
458
+ }
459
+
460
+ // ---------------------------------------------------------------
461
+ // exit / atexit (minimal semantics): handlers are C function
462
+ // pointers — wasm table indices. They can only be invoked if the
463
+ // module exports its indirect function table; when it does not,
464
+ // handlers are skipped and exit still unwinds via ShimExit.
465
+ // ---------------------------------------------------------------
466
+ const atexitHandlers = [];
467
+ function atexit(fnPtr) {
468
+ atexitHandlers.push(fnPtr);
469
+ return 0;
470
+ }
471
+ function exit(code) {
472
+ const table = holder?.instance?.exports?.__indirect_function_table;
473
+ if (table && typeof table.get === 'function') {
474
+ for (let i = atexitHandlers.length - 1; i >= 0; i--) {
475
+ try {
476
+ const fn = table.get(atexitHandlers[i]);
477
+ if (typeof fn === 'function') fn();
478
+ } catch {
479
+ // A failing handler must not mask the exit itself.
480
+ }
481
+ }
482
+ }
483
+ throw new ShimExit(code | 0);
484
+ }
485
+ function abort() {
486
+ throw new ShimExit(134);
487
+ }
488
+
489
+ // ---------------------------------------------------------------
490
+ // stdin: `options.stdin` bytes first, then io.in() chunks.
491
+ // ---------------------------------------------------------------
492
+ let stdinBuf = null;
493
+ let stdinPos = 0;
494
+ const pushback = [];
495
+ if (options.stdin != null) {
496
+ stdinBuf =
497
+ typeof options.stdin === 'string'
498
+ ? textEncoder.encode(options.stdin)
499
+ : options.stdin;
500
+ }
501
+ function stdinPull() {
502
+ if (stdinBuf && stdinPos < stdinBuf.length) return true;
503
+ if (typeof io.in === 'function') {
504
+ const chunk = io.in();
505
+ if (chunk == null) return false;
506
+ const b = typeof chunk === 'string' ? textEncoder.encode(chunk) : chunk;
507
+ if (!b || b.length === 0) return false;
508
+ stdinBuf = b;
509
+ stdinPos = 0;
510
+ return true;
511
+ }
512
+ return false;
513
+ }
514
+ function stdinRead(n) {
515
+ const parts = [];
516
+ let got = 0;
517
+ while (got < n) {
518
+ if (pushback.length) {
519
+ parts.push(Uint8Array.of(pushback.pop()));
520
+ got++;
521
+ continue;
522
+ }
523
+ if (!stdinPull()) break;
524
+ const take = Math.min(n - got, stdinBuf.length - stdinPos);
525
+ parts.push(stdinBuf.slice(stdinPos, stdinPos + take));
526
+ stdinPos += take;
527
+ got += take;
528
+ }
529
+ const result = new Uint8Array(got);
530
+ let at = 0;
531
+ for (const p of parts) {
532
+ result.set(p, at);
533
+ at += p.length;
534
+ }
535
+ return result;
536
+ }
537
+
538
+ // ---------------------------------------------------------------
539
+ // stdio. Variadic functions receive a va_list pointer: TCC's
540
+ // wasm32 va_list is a pointer into a memory region where the
541
+ // variadic arguments are laid out in order, each at its natural
542
+ // alignment — i32/pointers in 4-byte slots, i64 and f64 in
543
+ // 8-byte slots aligned to 8. printf's format parsing happens
544
+ // here in JS, reading the format string from linear memory.
545
+ //
546
+ // FILE* routing: stream values are opaque in this shim. Output
547
+ // goes to io.out, except stream value 2 (stderr's conventional
548
+ // value), which goes to io.err. fread/fgetc read stdin.
549
+ // ---------------------------------------------------------------
550
+ function makeVa(vaPtr) {
551
+ let cur = vaPtr;
552
+ const alignTo = (n) => {
553
+ cur = (cur + n - 1) & ~(n - 1);
554
+ };
555
+ return {
556
+ i32() {
557
+ alignTo(4);
558
+ const v = dv().getInt32(cur, true);
559
+ cur += 4;
560
+ return v;
561
+ },
562
+ u32() {
563
+ alignTo(4);
564
+ const v = dv().getUint32(cur, true);
565
+ cur += 4;
566
+ return v;
567
+ },
568
+ i64() {
569
+ alignTo(8);
570
+ const v = dv().getBigInt64(cur, true);
571
+ cur += 8;
572
+ return v;
573
+ },
574
+ u64() {
575
+ alignTo(8);
576
+ const v = dv().getBigUint64(cur, true);
577
+ cur += 8;
578
+ return v;
579
+ },
580
+ f64() {
581
+ alignTo(8);
582
+ const v = dv().getFloat64(cur, true);
583
+ cur += 8;
584
+ return v;
585
+ },
586
+ };
587
+ }
588
+
589
+ function padSpaces(s, width, left) {
590
+ if (s.length >= width) return s;
591
+ const p = ' '.repeat(width - s.length);
592
+ return left ? s + p : p + s;
593
+ }
594
+
595
+ function fmtInteger(digits, sign, prefix, flags, width, precision) {
596
+ let body = digits;
597
+ if (precision >= 0) body = body.padStart(precision, '0');
598
+ const head = sign + prefix;
599
+ if (flags.includes('0') && !flags.includes('-') && precision < 0) {
600
+ const total = head.length + body.length;
601
+ if (total < width) body = '0'.repeat(width - total) + body;
602
+ return head + body;
603
+ }
604
+ return padSpaces(head + body, width, flags.includes('-'));
605
+ }
606
+
607
+ function fmtFloatNumber(body, flags, width) {
608
+ let sign = '';
609
+ let rest = body;
610
+ if (rest.startsWith('-')) {
611
+ sign = '-';
612
+ rest = rest.slice(1);
613
+ } else if (flags.includes('+')) {
614
+ sign = '+';
615
+ } else if (flags.includes(' ')) {
616
+ sign = ' ';
617
+ }
618
+ const special = /^(inf|nan)/i.test(rest);
619
+ if (flags.includes('0') && !flags.includes('-') && !special) {
620
+ const total = sign.length + rest.length;
621
+ if (total < width) rest = '0'.repeat(width - total) + rest;
622
+ return sign + rest;
623
+ }
624
+ return padSpaces(sign + rest, width, flags.includes('-'));
625
+ }
626
+
627
+ function expParts(s) {
628
+ const [mant, exp] = s.split('e');
629
+ const e = parseInt(exp, 10);
630
+ return [mant, (e < 0 ? '-' : '+') + String(Math.abs(e)).padStart(2, '0')];
631
+ }
632
+ function fmtE(v, precision, upper) {
633
+ if (Number.isNaN(v)) return upper ? 'NAN' : 'nan';
634
+ if (!Number.isFinite(v)) return (v > 0 ? '' : '-') + (upper ? 'INF' : 'inf');
635
+ const [mant, e] = expParts(v.toExponential(precision));
636
+ return mant + (upper ? 'E' : 'e') + e;
637
+ }
638
+ function fmtF(v, precision, upper) {
639
+ if (Number.isNaN(v)) return upper ? 'NAN' : 'nan';
640
+ if (!Number.isFinite(v)) return (v > 0 ? '' : '-') + (upper ? 'INF' : 'inf');
641
+ return v.toFixed(precision);
642
+ }
643
+ function fmtG(v, precision, upper, alt) {
644
+ if (Number.isNaN(v) || !Number.isFinite(v)) return fmtF(v, 0, upper);
645
+ const p = precision <= 0 ? 1 : precision;
646
+ let s = v.toPrecision(p);
647
+ if (!alt) {
648
+ const strip = (m) =>
649
+ m.includes('.') ? m.replace(/0+$/, '').replace(/\.$/, '') : m;
650
+ if (s.includes('e')) {
651
+ const [m, e] = s.split('e');
652
+ s = strip(m) + 'e' + e;
653
+ } else {
654
+ s = strip(s);
655
+ }
656
+ s = s.replace(/e([+-])(\d)$/, 'e$10$2');
657
+ }
658
+ return upper ? s.toUpperCase() : s;
659
+ }
660
+
661
+ function convert(conv, { flags, width, precision, length, va }, outLen) {
662
+ switch (conv) {
663
+ case 'd':
664
+ case 'i': {
665
+ let sign = '';
666
+ let digits;
667
+ if (length === 'll') {
668
+ const v = va.i64();
669
+ if (v < 0n) {
670
+ sign = '-';
671
+ digits = (-v).toString(10);
672
+ } else digits = v.toString(10);
673
+ if (v === 0n && precision === 0) digits = '';
674
+ } else {
675
+ let v = va.i32();
676
+ if (length === 'hh') v = (v << 24) >> 24;
677
+ else if (length === 'h') v = (v << 16) >> 16;
678
+ if (v < 0) {
679
+ sign = '-';
680
+ digits = String(-v);
681
+ } else digits = String(v);
682
+ if (v === 0 && precision === 0) digits = '';
683
+ }
684
+ if (!sign && flags.includes('+')) sign = '+';
685
+ else if (!sign && flags.includes(' ')) sign = ' ';
686
+ return fmtInteger(digits, sign, '', flags, width, precision);
687
+ }
688
+ case 'u':
689
+ case 'x':
690
+ case 'X':
691
+ case 'o': {
692
+ const radix = conv === 'u' ? 10 : conv === 'o' ? 8 : 16;
693
+ let digits;
694
+ let isZero;
695
+ if (length === 'll') {
696
+ const v = va.u64();
697
+ isZero = v === 0n;
698
+ digits = v.toString(radix);
699
+ if (isZero && precision === 0) digits = '';
700
+ } else {
701
+ let v = va.u32();
702
+ if (length === 'hh') v &= 0xff;
703
+ else if (length === 'h') v &= 0xffff;
704
+ isZero = v === 0;
705
+ digits = v.toString(radix);
706
+ if (isZero && precision === 0) digits = '';
707
+ }
708
+ if (conv === 'X') digits = digits.toUpperCase();
709
+ let prefix = '';
710
+ if (flags.includes('#') && conv !== 'u') {
711
+ if (conv === 'o') {
712
+ if (!digits.startsWith('0')) prefix = '0';
713
+ } else if (!isZero) {
714
+ prefix = conv === 'X' ? '0X' : '0x';
715
+ }
716
+ }
717
+ return fmtInteger(digits, '', prefix, flags, width, precision);
718
+ }
719
+ case 'c': {
720
+ const ch = String.fromCharCode(va.i32() & 0xff);
721
+ return padSpaces(ch, width, flags.includes('-'));
722
+ }
723
+ case 's': {
724
+ const ptr = va.u32();
725
+ let s = ptr ? readCString(ptr) : '(null)';
726
+ if (precision >= 0) s = s.slice(0, precision);
727
+ return padSpaces(s, width, flags.includes('-'));
728
+ }
729
+ case 'p': {
730
+ const ptr = va.u32();
731
+ return padSpaces('0x' + ptr.toString(16), width, flags.includes('-'));
732
+ }
733
+ case 'f':
734
+ case 'F':
735
+ return fmtFloatNumber(
736
+ fmtF(va.f64(), precision < 0 ? 6 : precision, conv === 'F'),
737
+ flags,
738
+ width,
739
+ );
740
+ case 'e':
741
+ case 'E':
742
+ return fmtFloatNumber(
743
+ fmtE(va.f64(), precision < 0 ? 6 : precision, conv === 'E'),
744
+ flags,
745
+ width,
746
+ );
747
+ case 'g':
748
+ case 'G':
749
+ return fmtFloatNumber(
750
+ fmtG(va.f64(), precision < 0 ? 6 : precision, conv === 'G', flags.includes('#')),
751
+ flags,
752
+ width,
753
+ );
754
+ case 'a':
755
+ case 'A': {
756
+ const v = va.f64();
757
+ return fmtFloatNumber(String(v), flags, width);
758
+ }
759
+ case 'n': {
760
+ const ptr = va.u32();
761
+ if (ptr) {
762
+ if (length === 'll') dv().setBigInt64(ptr, BigInt(outLen), true);
763
+ else dv().setInt32(ptr, outLen, true);
764
+ }
765
+ return '';
766
+ }
767
+ default:
768
+ return '%' + conv;
769
+ }
770
+ }
771
+
772
+ function formatString(fmtPtr, vaPtr) {
773
+ const fmt = readCString(fmtPtr);
774
+ const va = makeVa(vaPtr);
775
+ let out = '';
776
+ let i = 0;
777
+ while (i < fmt.length) {
778
+ if (fmt[i] !== '%') {
779
+ out += fmt[i++];
780
+ continue;
781
+ }
782
+ i++;
783
+ if (fmt[i] === '%') {
784
+ out += '%';
785
+ i++;
786
+ continue;
787
+ }
788
+ let flags = '';
789
+ while (i < fmt.length && '-+ #0'.includes(fmt[i])) flags += fmt[i++];
790
+ let width = 0;
791
+ if (fmt[i] === '*') {
792
+ width = va.i32();
793
+ i++;
794
+ if (width < 0) {
795
+ flags += '-';
796
+ width = -width;
797
+ }
798
+ } else {
799
+ while (i < fmt.length && fmt[i] >= '0' && fmt[i] <= '9') {
800
+ width = width * 10 + (fmt.charCodeAt(i++) - 48);
801
+ }
802
+ }
803
+ let precision = -1;
804
+ if (fmt[i] === '.') {
805
+ i++;
806
+ if (fmt[i] === '*') {
807
+ precision = va.i32();
808
+ i++;
809
+ } else {
810
+ precision = 0;
811
+ while (i < fmt.length && fmt[i] >= '0' && fmt[i] <= '9') {
812
+ precision = precision * 10 + (fmt.charCodeAt(i++) - 48);
813
+ }
814
+ }
815
+ if (precision < 0) precision = -1;
816
+ }
817
+ let length = '';
818
+ if (fmt.startsWith('hh', i)) {
819
+ length = 'hh';
820
+ i += 2;
821
+ } else if (fmt.startsWith('ll', i)) {
822
+ length = 'll';
823
+ i += 2;
824
+ } else if (i < fmt.length && 'hlzjtL'.includes(fmt[i])) {
825
+ length = fmt[i++];
826
+ }
827
+ const conv = fmt[i++] ?? '';
828
+ out += convert(conv, { flags, width, precision, length, va }, out.length);
829
+ }
830
+ return out;
831
+ }
832
+
833
+ function emitText(text, toErr) {
834
+ const bytes = textEncoder.encode(text);
835
+ (toErr ? emitErr : emitOut)(bytes);
836
+ return bytes.length;
837
+ }
838
+
839
+ function printf(fmt, va) {
840
+ return emitText(formatString(fmt, va), false);
841
+ }
842
+ function fprintf(stream, fmt, va) {
843
+ return emitText(formatString(fmt, va), stream === 2);
844
+ }
845
+ function sprintf(dest, fmt, va) {
846
+ const bytes = textEncoder.encode(formatString(fmt, va));
847
+ return writeCStringBytes(dest, bytes);
848
+ }
849
+ function snprintf(dest, size, fmt, va) {
850
+ const bytes = textEncoder.encode(formatString(fmt, va));
851
+ if (size > 0) {
852
+ const n = Math.min(bytes.length, size - 1);
853
+ writeBytes(dest, bytes.subarray(0, n));
854
+ u8()[dest + n] = 0;
855
+ }
856
+ return bytes.length;
857
+ }
858
+ function puts(ptr) {
859
+ return emitText(readCString(ptr) + '\n', false) >= 0 ? 0 : -1;
860
+ }
861
+ function putchar(c) {
862
+ emitOut(Uint8Array.of(c & 0xff));
863
+ return c;
864
+ }
865
+ function fputs(ptr, stream) {
866
+ emitText(readCString(ptr), stream === 2);
867
+ return 0;
868
+ }
869
+ function putc(c, stream) {
870
+ (stream === 2 ? emitErr : emitOut)(Uint8Array.of(c & 0xff));
871
+ return c;
872
+ }
873
+ function fwrite(ptr, size, nmemb, stream) {
874
+ const total = size * nmemb;
875
+ if (total === 0) return 0;
876
+ (stream === 2 ? emitErr : emitOut)(readBytes(ptr, total));
877
+ return nmemb;
878
+ }
879
+ function fread(ptr, size, nmemb, _stream) {
880
+ if (size === 0 || nmemb === 0) return 0;
881
+ const data = stdinRead(size * nmemb);
882
+ if (data.length) writeBytes(ptr, data);
883
+ return Math.floor(data.length / size);
884
+ }
885
+ function fgetc(_stream) {
886
+ const data = stdinRead(1);
887
+ return data.length ? data[0] : -1;
888
+ }
889
+ function ungetc(c, _stream) {
890
+ if (c >= 0) pushback.push(c & 0xff);
891
+ return c;
892
+ }
893
+
894
+ // ---------------------------------------------------------------
895
+ // math / time
896
+ // ---------------------------------------------------------------
897
+ const env = {
898
+ // memory / string
899
+ memcpy,
900
+ memmove,
901
+ memset,
902
+ memcmp,
903
+ strlen,
904
+ strcpy,
905
+ strncpy,
906
+ strcat,
907
+ strncat,
908
+ strcmp,
909
+ strncmp,
910
+ strchr,
911
+ strrchr,
912
+ strstr,
913
+ strdup,
914
+ // allocation
915
+ malloc,
916
+ calloc,
917
+ realloc,
918
+ free,
919
+ // stdio
920
+ printf,
921
+ fprintf,
922
+ vprintf: printf,
923
+ vfprintf: fprintf,
924
+ sprintf,
925
+ vsprintf: sprintf,
926
+ snprintf,
927
+ vsnprintf: snprintf,
928
+ puts,
929
+ putchar,
930
+ fputs,
931
+ putc,
932
+ fputc: putc,
933
+ fwrite,
934
+ fread,
935
+ fgetc,
936
+ getchar: () => fgetc(0),
937
+ ungetc,
938
+ // stdlib
939
+ exit,
940
+ abort,
941
+ atexit,
942
+ atoi,
943
+ atol,
944
+ atoll,
945
+ atof,
946
+ strtol,
947
+ strtoul,
948
+ strtoll,
949
+ strtoull,
950
+ strtod,
951
+ strtof,
952
+ abs,
953
+ labs,
954
+ llabs,
955
+ rand,
956
+ srand,
957
+ getenv: (_name) => 0,
958
+ system: (cmd) => (cmd === 0 ? 0 : -1),
959
+ // ctype
960
+ isalpha,
961
+ isdigit,
962
+ isspace,
963
+ isalnum,
964
+ isupper,
965
+ islower,
966
+ ispunct,
967
+ iscntrl,
968
+ isxdigit,
969
+ isblank,
970
+ isprint,
971
+ isgraph,
972
+ tolower,
973
+ toupper,
974
+ // math
975
+ sin: Math.sin,
976
+ cos: Math.cos,
977
+ tan: Math.tan,
978
+ asin: Math.asin,
979
+ acos: Math.acos,
980
+ atan: Math.atan,
981
+ atan2: Math.atan2,
982
+ exp: Math.exp,
983
+ log: Math.log,
984
+ log10: Math.log10,
985
+ pow: Math.pow,
986
+ sqrt: Math.sqrt,
987
+ floor: Math.floor,
988
+ ceil: Math.ceil,
989
+ fabs: Math.abs,
990
+ round: Math.round,
991
+ trunc: Math.trunc,
992
+ fmod: (a, b) => a % b,
993
+ // time
994
+ time: (tloc) => {
995
+ const sec = Math.floor(Date.now() / 1000);
996
+ if (tloc) writeU32(tloc, sec);
997
+ return sec;
998
+ },
999
+ clock: () => Math.floor(performance.now() * 1000),
1000
+ difftime: (a, b) => a - b,
1001
+ };
1002
+
1003
+ return { env };
1004
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file