tinyc-web 0.0.0-stage → 0.1.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/index.mjs ADDED
@@ -0,0 +1,2219 @@
1
+ // tinyc-web: TinyC (TCC) WebAssembly glue layer.
2
+ //
3
+ // A TCC build has exactly one code generation target, so the native
4
+ // side is one WASM module per target (see build.sh), named
5
+ // tcc-<target>.wasm with glue tcc-<target>.mjs. loadTinyc() picks the
6
+ // module for the requested target from a registry and loads it
7
+ // lazily; instances of different targets coexist. This file provides,
8
+ // in plain JS:
9
+ // - loadTinyc() instantiate the WASM module (or an injected one)
10
+ // - instance.callMain() command-line mode through the exported main
11
+ // - TinycState fine-grained libtcc API (tcc_* exports)
12
+ // - runWasmModule() execute a compiled wasm32 product: a WASM
13
+ // module cannot instantiate another module
14
+ // from inside itself, so running is the
15
+ // host's (this glue layer's) job — it takes
16
+ // the product bytes, instantiates them with
17
+ // the WebAssembly API plus a minimal WASI
18
+ // shim, and calls _start or a named export.
19
+ // Products also get default JS libc shims
20
+ // (runtime-shims.mjs, module "env"); users
21
+ // can register their own shims at package,
22
+ // instance and per-run level, and imports
23
+ // no layer satisfies are reported by name
24
+ // (TinycMissingImportError) up front
25
+ // - VirtualFS in-page filesystem; user files enter from
26
+ // content strings, File/Blob objects or URLs
27
+ // - IO JS callbacks directly, no trampoline needed:
28
+ // this package's host language is JavaScript.
29
+ //
30
+ // Native module resolution order in loadTinyc(), per target:
31
+ // options.module an already-created Emscripten module object
32
+ // options.createModule an Emscripten MODULARIZE factory
33
+ // options.wasmExports raw WebAssembly exports, or a plain mock object
34
+ // implementing the same tcc_* names (test double)
35
+ // options.loadModule async loader called with (target, files);
36
+ // its result is cached per target
37
+ // (default) the per-target glue tcc-<target>.mjs built
38
+ // by build.sh, with the wasm at options.wasmUrl
39
+ // or tcc-<target>.wasm alongside the glue
40
+
41
+ import manifestWasm32Wasi from './sysroot-manifests/wasm32-wasi.json' with { type: 'json' };
42
+ import manifestX86_64LinuxGnu from './sysroot-manifests/x86_64-linux-gnu.json' with { type: 'json' };
43
+ import manifestAarch64LinuxGnu from './sysroot-manifests/aarch64-linux-gnu.json' with { type: 'json' };
44
+ import manifestRiscv64LinuxGnu from './sysroot-manifests/riscv64-linux-gnu.json' with { type: 'json' };
45
+ import manifestX86_64Windows from './sysroot-manifests/x86_64-windows.json' with { type: 'json' };
46
+ import manifestAarch64LinuxAndroid from './sysroot-manifests/aarch64-linux-android.json' with { type: 'json' };
47
+ import manifestX86_64LinuxAndroid from './sysroot-manifests/x86_64-linux-android.json' with { type: 'json' };
48
+ import manifestArm64AppleDarwin from './sysroot-manifests/arm64-apple-darwin.json' with { type: 'json' };
49
+ import manifestX86_64AppleDarwin from './sysroot-manifests/x86_64-apple-darwin.json' with { type: 'json' };
50
+ import { createDefaultShims, ShimExit } from './runtime-shims.mjs';
51
+ import { MemoryFsStore, openFsStore } from './vfs-store.mjs';
52
+
53
+ export { MemoryFsStore, IndexedDbFsStore, createFsStore } from './vfs-store.mjs';
54
+
55
+ /** The default target's sysroot manifest (sysroot-manifests/wasm32-wasi.json). */
56
+ export const sysrootManifest = manifestWasm32Wasi;
57
+
58
+ // Every target's sysroot manifest, statically imported so the data is
59
+ // part of the module graph: the classic-script bundle (tinyc-web.js)
60
+ // inlines all of them, and loadSysrootManifest never fetches JSON at
61
+ // runtime.
62
+ const SYSROOT_MANIFESTS = Object.freeze({
63
+ 'wasm32-wasi': manifestWasm32Wasi,
64
+ 'x86_64-linux-gnu': manifestX86_64LinuxGnu,
65
+ 'aarch64-linux-gnu': manifestAarch64LinuxGnu,
66
+ 'riscv64-linux-gnu': manifestRiscv64LinuxGnu,
67
+ 'x86_64-windows': manifestX86_64Windows,
68
+ 'aarch64-linux-android': manifestAarch64LinuxAndroid,
69
+ 'x86_64-linux-android': manifestX86_64LinuxAndroid,
70
+ 'arm64-apple-darwin': manifestArm64AppleDarwin,
71
+ 'x86_64-apple-darwin': manifestX86_64AppleDarwin,
72
+ });
73
+
74
+ // ---------------------------------------------------------------------
75
+ // Asset base URL
76
+ //
77
+ // The per-target glue/wasm files and the sysroot files resolve
78
+ // against a base captured for the environment this code runs in:
79
+ // - ES module: this module's own URL (import.meta.url), so assets
80
+ // sitting next to index.mjs are found;
81
+ // - classic-script bundle (tinyc-web.js): the directory of the
82
+ // <script> element that loaded the bundle, captured below from
83
+ // document.currentScript while the bundle executes, so assets
84
+ // sitting next to tinyc-web.js are found; when no script URL is
85
+ // available, the page's own directory (location.href) is used.
86
+ // loadTinyc's baseUrl option overrides the base per call; its
87
+ // wasmUrl / glueUrl options override individual files.
88
+ // ---------------------------------------------------------------------
89
+
90
+ const SCRIPT_DIR_HREF = (() => {
91
+ try {
92
+ const script = typeof document !== 'undefined' ? document.currentScript : null;
93
+ if (script && script.src) return new URL('.', script.src).href;
94
+ } catch { /* no usable script URL */ }
95
+ return null;
96
+ })();
97
+
98
+ const MODULE_URL = (() => {
99
+ try {
100
+ return import.meta.url || null;
101
+ } catch {
102
+ return null;
103
+ }
104
+ })();
105
+
106
+ const PAGE_DIR_HREF = (() => {
107
+ try {
108
+ if (typeof location !== 'undefined' && location.href) {
109
+ return new URL('.', location.href).href;
110
+ }
111
+ } catch { /* no page URL */ }
112
+ return null;
113
+ })();
114
+
115
+ /** baseUrl values are directory URLs: a missing trailing slash is
116
+ * added, so "https://host/libs" names the directory, not a file. */
117
+ function dirHref(url) {
118
+ return url.endsWith('/') ? url : url + '/';
119
+ }
120
+
121
+ /** Absolute URL of an asset file: resolved against baseUrl when
122
+ * given, else against the captured environment base. */
123
+ function assetUrl(name, baseUrl) {
124
+ const base = baseUrl
125
+ ? dirHref(baseUrl)
126
+ : SCRIPT_DIR_HREF ?? MODULE_URL ?? PAGE_DIR_HREF;
127
+ return base ? new URL(name, base).href : name;
128
+ }
129
+
130
+ /** Virtual path placed in argv[0] when calling the exported main. TCC
131
+ * derives its library path from argv[0]; the sysroot is mounted at
132
+ * /sysroot in the virtual filesystem, so argv[0] points inside it. */
133
+ export const VIRTUAL_BIN_PATH = sysrootManifest.binPath;
134
+
135
+ export class TinycError extends Error {
136
+ constructor(message, code) {
137
+ super(message);
138
+ this.name = 'TinycError';
139
+ if (code !== undefined) this.code = code;
140
+ }
141
+ }
142
+
143
+ /** Thrown when a required tcc_* / main export is not present in the
144
+ * loaded native module. The message always names the missing export. */
145
+ export class TinycMissingExportError extends TinycError {
146
+ constructor(exportName) {
147
+ super(
148
+ `tinyc: native module does not export "${exportName}". ` +
149
+ `The WASM build must list it in EXPORTED_FUNCTIONS (see build.sh).`
150
+ );
151
+ this.name = 'TinycMissingExportError';
152
+ this.exportName = exportName;
153
+ }
154
+ }
155
+
156
+ // ---------------------------------------------------------------------
157
+ // Targets
158
+ //
159
+ // A TCC binary has exactly one code generation target, fixed when it
160
+ // is built; upstream ships parallel cross-compiler variants instead
161
+ // of one multi-target binary. This package does the same: one WASM
162
+ // module per target, named tcc-<target>.wasm (glue tcc-<target>.mjs),
163
+ // chosen through the registry below and loaded lazily — only the
164
+ // requested target's module is ever fetched. Instances of different
165
+ // targets coexist in one page; each has its own virtual FS and its
166
+ // own sysroot manifest (sysroot-manifests/<target>.json).
167
+ //
168
+ // Compiling and running are different things here. The compiler's
169
+ // host platform in a browser is WebAssembly itself, so only the
170
+ // wasm32 target's output can run in the browser (the produced module
171
+ // is instantiated and executed). Every other target compiles to
172
+ // files only; the glue layer rejects run requests for them up front
173
+ // (TinycRunNotSupportedError) instead of passing them to the native
174
+ // module to fail there.
175
+ // ---------------------------------------------------------------------
176
+
177
+ export const DEFAULT_TARGET = 'wasm32-wasi';
178
+
179
+ export const TARGETS = Object.freeze({
180
+ 'wasm32-wasi': { runnable: true, description: 'WebAssembly (WASI); output runs in the browser' },
181
+ 'x86_64-linux-gnu': { runnable: false, description: 'Linux x86-64 ELF' },
182
+ 'aarch64-linux-gnu': { runnable: false, description: 'Linux AArch64 ELF' },
183
+ 'riscv64-linux-gnu': { runnable: false, description: 'Linux RISC-V 64 ELF' },
184
+ 'x86_64-windows': { runnable: false, description: 'Windows x86-64 PE' },
185
+ 'aarch64-linux-android': { runnable: false, description: 'Android AArch64 ELF (bionic)' },
186
+ 'x86_64-linux-android': { runnable: false, description: 'Android x86-64 ELF (bionic)' },
187
+ 'arm64-apple-darwin': { runnable: false, description: 'macOS arm64 Mach-O' },
188
+ 'x86_64-apple-darwin': { runnable: false, description: 'macOS x86-64 Mach-O' },
189
+ });
190
+
191
+ export const SUPPORTED_TARGETS = Object.freeze(Object.keys(TARGETS));
192
+
193
+ export function isRunnableTarget(target) {
194
+ return Boolean(TARGETS[target]?.runnable);
195
+ }
196
+
197
+ export function targetModuleFiles(target) {
198
+ return { wasmFile: `tcc-${target}.wasm`, glueFile: `tcc-${target}.mjs` };
199
+ }
200
+
201
+ function assertKnownTarget(target) {
202
+ if (!Object.hasOwn(TARGETS, target)) {
203
+ throw new TinycError(
204
+ `tinyc: unknown target "${target}". Supported targets: ${SUPPORTED_TARGETS.join(', ')}`
205
+ );
206
+ }
207
+ }
208
+
209
+ /** Thrown by the glue layer — before anything reaches the native
210
+ * module — when code tries to run the output of a target that
211
+ * cannot execute in the browser. */
212
+ export class TinycRunNotSupportedError extends TinycError {
213
+ constructor(target) {
214
+ super(
215
+ `tinyc: target "${target}" cannot be run in the browser: in the browser it ` +
216
+ `can only be compiled to a file. Running compiled output is only possible ` +
217
+ `for the "${DEFAULT_TARGET}" target, whose output is WebAssembly and is ` +
218
+ `instantiated and executed by the browser itself.`
219
+ );
220
+ this.name = 'TinycRunNotSupportedError';
221
+ this.target = target;
222
+ }
223
+ }
224
+
225
+ // ---------------------------------------------------------------------
226
+ // IO
227
+ //
228
+ // An IO object is { out, err, in }:
229
+ // out(text) / err(text) receive decoded text chunks written by TCC
230
+ // in() returns the next stdin chunk (string) or
231
+ // null at EOF; may also return a Promise
232
+ // Defaults: out/err are line-buffered writers onto console.log /
233
+ // console.error, in returns null (immediate EOF). No fd juggling and
234
+ // no host stdio is ever touched: this is the TCCIO interface of the
235
+ // native core with JS functions plugged straight in.
236
+ // ---------------------------------------------------------------------
237
+
238
+ function lineBuffered(sink) {
239
+ let pending = '';
240
+ const write = (text) => {
241
+ pending += text;
242
+ let idx;
243
+ while ((idx = pending.indexOf('\n')) >= 0) {
244
+ sink(pending.slice(0, idx));
245
+ pending = pending.slice(idx + 1);
246
+ }
247
+ };
248
+ write.flush = () => {
249
+ if (pending.length > 0) {
250
+ sink(pending);
251
+ pending = '';
252
+ }
253
+ };
254
+ return write;
255
+ }
256
+
257
+ export function createDefaultIO() {
258
+ return {
259
+ out: lineBuffered((line) => console.log(line)),
260
+ err: lineBuffered((line) => console.error(line)),
261
+ in: () => null,
262
+ };
263
+ }
264
+
265
+ export function normalizeIO(partial, base) {
266
+ const io = { ...(base ?? createDefaultIO()) };
267
+ if (partial) {
268
+ for (const key of ['out', 'err', 'in']) {
269
+ if (partial[key] !== undefined) {
270
+ if (typeof partial[key] !== 'function') {
271
+ throw new TinycError(`tinyc: io.${key} must be a function`);
272
+ }
273
+ io[key] = partial[key];
274
+ }
275
+ }
276
+ }
277
+ return io;
278
+ }
279
+
280
+ export function flushIO(io) {
281
+ for (const key of ['out', 'err']) {
282
+ if (typeof io[key]?.flush === 'function') io[key].flush();
283
+ }
284
+ }
285
+
286
+ // ---------------------------------------------------------------------
287
+ // Virtual filesystem
288
+ //
289
+ // File contents are persisted in a store (vfs-store.mjs): one
290
+ // IndexedDB database per target where IndexedDB exists, an in-memory
291
+ // backend where it does not. What stays in memory here is only the
292
+ // path index (path -> { size, mtime }) plus a small LRU content
293
+ // cache; the bytes themselves live in the store. Paths are
294
+ // POSIX-style and normalized to absolute form ("/src/main.c"). This
295
+ // is where the "dynamically add local files" rule of the native
296
+ // packages lands in a browser, where there is no real filesystem to
297
+ // point TCC at: a local file enters as its content, as a File/Blob
298
+ // from an <input> or drag-and-drop, or fetched from a URL.
299
+ //
300
+ // Synchronous reads (readFile / readTextFile) are served from the
301
+ // content cache — everything written or read during this session is
302
+ // cached — and throw for a persisted file that is not cached,
303
+ // naming readFileAsync / readTextFileAsync as the alternative.
304
+ // addFile awaits its store write; addFileSync stays synchronous and
305
+ // queues the write instead — await whenIdle() (on the FS or the
306
+ // instance) to know queued writes and deletes have landed.
307
+ //
308
+ // === Emscripten FS adaptation point ===
309
+ // When the native module is an Emscripten build, mountTo() copies
310
+ // every virtual file into the module's FS (FS.mkdirTree + FS.writeFile)
311
+ // and syncFile() keeps single files in sync after each write. The
312
+ // compile working set has to live in that FS while TCC runs, so it
313
+ // is mirrored there in full — under the bridge's moduleFsPrefix
314
+ // ("/opfs", the WasmFS OPFS backend loadTinyc mounts before
315
+ // mirroring, when that mount succeeds; the module FS root
316
+ // otherwise). Emscripten-FS knowledge in this package is confined
317
+ // to those two methods, to removeFile's unlink, and to the OPFS
318
+ // mount attempt itself (tryMountOpfsBackend).
319
+ // ---------------------------------------------------------------------
320
+
321
+ /** Content cache bounds for the virtual FS: at most this many
322
+ * files, and at most this many bytes in total, are held in memory
323
+ * for synchronous reads. A single file larger than the byte bound
324
+ * is still cached (the bound is soft for one entry). */
325
+ export const VFS_CACHE_MAX_ENTRIES = 32;
326
+ export const VFS_CACHE_MAX_BYTES = 16 * 1024 * 1024;
327
+
328
+ const textEncoder = new TextEncoder();
329
+ const textDecoder = new TextDecoder();
330
+
331
+ export function normalizeVfsPath(path) {
332
+ if (typeof path !== 'string' || path.length === 0) {
333
+ throw new TinycError('tinyc: vfs path must be a non-empty string');
334
+ }
335
+ const parts = [];
336
+ for (const seg of path.split('/')) {
337
+ if (seg === '' || seg === '.') continue;
338
+ if (seg === '..') parts.pop();
339
+ else parts.push(seg);
340
+ }
341
+ return '/' + parts.join('/');
342
+ }
343
+
344
+ /** Bytes for the content kinds whose bytes are at hand synchronously
345
+ * (string, Uint8Array, ArrayBuffer); null for Blob/File content,
346
+ * whose bytes only an asynchronous read can produce. Any other
347
+ * content is rejected with the addFile content error. */
348
+ function contentToBytesSync(content) {
349
+ if (typeof content === 'string') return textEncoder.encode(content);
350
+ if (content instanceof Uint8Array) return new Uint8Array(content);
351
+ if (content instanceof ArrayBuffer) return new Uint8Array(content);
352
+ if (typeof Blob !== 'undefined' && content instanceof Blob) return null;
353
+ throw new TinycError(
354
+ 'tinyc: addFile content must be a string, Uint8Array, ArrayBuffer, File or Blob'
355
+ );
356
+ }
357
+
358
+ async function contentToBytes(content) {
359
+ const syncBytes = contentToBytesSync(content);
360
+ if (syncBytes) return syncBytes;
361
+ // File is a Blob subclass; both are read the same way.
362
+ return new Uint8Array(await content.arrayBuffer());
363
+ }
364
+
365
+ export class VirtualFS {
366
+ /** `store` is an opened FsStore (see vfs-store.mjs); its persisted
367
+ * index becomes this filesystem's initial file set. With no store
368
+ * argument, a volatile in-memory store is used. loadTinyc opens
369
+ * the per-target store (IndexedDB by default) before building
370
+ * the instance's VirtualFS. */
371
+ constructor(store = null) {
372
+ this._store = store ?? new MemoryFsStore();
373
+ this.index = new Map(this._store.index ?? []);
374
+ this.includeDirs = [];
375
+ this._emscriptenFS = null;
376
+ this._moduleFsPrefix = '';
377
+ this._cache = new Map();
378
+ this._cacheBytes = 0;
379
+ this._pending = new Set();
380
+ this._idleError = null;
381
+ }
382
+
383
+ /** The kind of the backing store: 'indexeddb' or 'memory'. */
384
+ get storeKind() {
385
+ return this._store.kind;
386
+ }
387
+
388
+ _cacheGet(path) {
389
+ const bytes = this._cache.get(path);
390
+ if (bytes) {
391
+ // Refresh recency: re-insert at the newest end.
392
+ this._cache.delete(path);
393
+ this._cache.set(path, bytes);
394
+ }
395
+ return bytes;
396
+ }
397
+
398
+ _cachePut(path, bytes) {
399
+ const prev = this._cache.get(path);
400
+ if (prev) {
401
+ this._cache.delete(path);
402
+ this._cacheBytes -= prev.byteLength;
403
+ }
404
+ this._cache.set(path, bytes);
405
+ this._cacheBytes += bytes.byteLength;
406
+ while (
407
+ this._cache.size > 1 &&
408
+ (this._cache.size > VFS_CACHE_MAX_ENTRIES ||
409
+ this._cacheBytes > VFS_CACHE_MAX_BYTES)
410
+ ) {
411
+ const oldest = this._cache.keys().next().value;
412
+ this._cacheBytes -= this._cache.get(oldest).byteLength;
413
+ this._cache.delete(oldest);
414
+ }
415
+ }
416
+
417
+ _cacheDelete(path) {
418
+ const prev = this._cache.get(path);
419
+ if (prev) {
420
+ this._cache.delete(path);
421
+ this._cacheBytes -= prev.byteLength;
422
+ }
423
+ }
424
+
425
+ /** Queue a store operation kicked off by a synchronous method
426
+ * (addFileSync / removeFile / clear). Tracked so whenIdle() can
427
+ * await the queue; the first failure is remembered and rethrown
428
+ * by whenIdle() instead of surfacing as an unhandled rejection. */
429
+ _queueStoreOp(op) {
430
+ let base;
431
+ try {
432
+ base = Promise.resolve(op());
433
+ } catch (err) {
434
+ base = Promise.reject(err);
435
+ }
436
+ const tracked = base.then(
437
+ () => { this._pending.delete(tracked); },
438
+ (err) => {
439
+ this._pending.delete(tracked);
440
+ if (this._idleError == null) this._idleError = err;
441
+ }
442
+ );
443
+ this._pending.add(tracked);
444
+ }
445
+
446
+ /** Resolve once every queued store write/delete has landed.
447
+ * Rethrows the first queued operation's failure, if any. */
448
+ async whenIdle() {
449
+ while (this._pending.size > 0) {
450
+ await Promise.all([...this._pending]);
451
+ }
452
+ if (this._idleError != null) {
453
+ const err = this._idleError;
454
+ this._idleError = null;
455
+ throw err;
456
+ }
457
+ }
458
+
459
+ /** Synchronous half of a write: index, content cache and the
460
+ * Emscripten FS mirror. Returns the normalized path and the
461
+ * record to persist. */
462
+ _stage(path, bytes) {
463
+ const p = normalizeVfsPath(path);
464
+ const buf = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
465
+ const meta = { size: buf.byteLength, mtime: Date.now() };
466
+ this.index.set(p, meta);
467
+ this._cachePut(p, buf);
468
+ this.syncFile(p);
469
+ return { p, record: { bytes: buf, size: meta.size, mtime: meta.mtime } };
470
+ }
471
+
472
+ /** Add or replace a file. `content` may be a string, Uint8Array,
473
+ * ArrayBuffer, File or Blob. For the content kinds whose bytes
474
+ * are at hand (string, Uint8Array, ArrayBuffer) the file is
475
+ * staged — index, content cache and the Emscripten FS mirror —
476
+ * synchronously, before this call returns its promise, so a
477
+ * compile or read issued immediately afterwards, without
478
+ * awaiting, already sees the file; Blob and File content stages
479
+ * once its bytes have been read. The returned promise resolves
480
+ * once the content is persisted in the store. */
481
+ async addFile(path, content) {
482
+ const bytes = contentToBytesSync(content) ?? (await contentToBytes(content));
483
+ const { p, record } = this._stage(path, bytes);
484
+ await this._store.put(p, record);
485
+ }
486
+
487
+ /** Synchronous write: index, cache and the Emscripten mirror are
488
+ * updated immediately (so the file can be compiled and read back
489
+ * synchronously); the store write is queued behind any other
490
+ * queued operations — await whenIdle() for it to land. */
491
+ addFileSync(path, content) {
492
+ const bytes =
493
+ typeof content === 'string' ? textEncoder.encode(content) : content;
494
+ const { p, record } = this._stage(path, bytes);
495
+ this._queueStoreOp(() => this._store.put(p, record));
496
+ return p;
497
+ }
498
+
499
+ /** Fetch a file from a URL into the virtual filesystem.
500
+ * `fetchImpl` is injectable for tests and non-window contexts. */
501
+ async addFileFromUrl(path, url, { fetchImpl = globalThis.fetch } = {}) {
502
+ if (typeof fetchImpl !== 'function') {
503
+ throw new TinycError('tinyc: addFileFromUrl needs a fetch implementation');
504
+ }
505
+ const res = await fetchImpl(url);
506
+ if (res && res.ok === false) {
507
+ throw new TinycError(`tinyc: fetching ${url} failed with status ${res.status}`);
508
+ }
509
+ const buf = await res.arrayBuffer();
510
+ const bytes = new Uint8Array(buf);
511
+ const { p, record } = this._stage(path, bytes);
512
+ await this._store.put(p, record);
513
+ return p;
514
+ }
515
+
516
+ /** Register a directory as a header search directory. Every state
517
+ * created afterwards gets it via tcc_add_include_path, in
518
+ * registration order, ahead of the sysroot. */
519
+ registerIncludeDir(path) {
520
+ const p = normalizeVfsPath(path);
521
+ if (!this.includeDirs.includes(p)) this.includeDirs.push(p);
522
+ return p;
523
+ }
524
+
525
+ getIncludeDirs() {
526
+ return [...this.includeDirs];
527
+ }
528
+
529
+ hasFile(path) {
530
+ return this.index.has(normalizeVfsPath(path));
531
+ }
532
+
533
+ /** Synchronous read, served from the content cache: files written
534
+ * or read during this session are cached, so this covers the
535
+ * compile/read-back paths. A persisted file that is not cached
536
+ * throws, naming the async alternative — use readFileAsync. */
537
+ readFile(path) {
538
+ const p = normalizeVfsPath(path);
539
+ if (!this.index.has(p)) {
540
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
541
+ }
542
+ const bytes = this._cacheGet(p);
543
+ if (!bytes) {
544
+ throw new TinycError(
545
+ `tinyc: ${p} is persisted in the virtual FS store but is not in ` +
546
+ `the in-memory cache; read it with readFileAsync() instead`
547
+ );
548
+ }
549
+ return bytes;
550
+ }
551
+
552
+ readTextFile(path) {
553
+ return textDecoder.decode(this.readFile(path));
554
+ }
555
+
556
+ /** Read a file's content from the store, warming the content
557
+ * cache, so later synchronous reads of the same file succeed. */
558
+ async readFileAsync(path) {
559
+ const p = normalizeVfsPath(path);
560
+ if (!this.index.has(p)) {
561
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
562
+ }
563
+ const hit = this._cacheGet(p);
564
+ if (hit) return hit;
565
+ const rec = await this._store.get(p);
566
+ if (!rec) {
567
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
568
+ }
569
+ this._cachePut(p, rec.bytes);
570
+ return rec.bytes;
571
+ }
572
+
573
+ async readTextFileAsync(path) {
574
+ return textDecoder.decode(await this.readFileAsync(path));
575
+ }
576
+
577
+ /** Delete one file. Every copy goes: the index entry and cached
578
+ * content, the persisted record (queued — see whenIdle), and,
579
+ * when an Emscripten FS is mounted, the mirrored file inside the
580
+ * native module (an unlink is attempted even for a path missing
581
+ * from the index, e.g. a file the compiler created natively).
582
+ * Returns true when the index or the native copy existed. */
583
+ removeFile(path) {
584
+ const p = normalizeVfsPath(path);
585
+ const had = this.index.delete(p);
586
+ this._cacheDelete(p);
587
+ this._queueStoreOp(() => this._store.delete(p));
588
+ let unlinked = false;
589
+ const FS = this._emscriptenFS;
590
+ if (FS && typeof FS.unlink === 'function') {
591
+ try { FS.unlink(this._nativePath(p)); unlinked = true; } catch { /* not present natively */ }
592
+ }
593
+ return had || unlinked;
594
+ }
595
+
596
+ /** Delete every file tracked by this virtual FS except the
597
+ * mounted sysroot (paths under /sysroot/), which stays so the
598
+ * instance can keep compiling. Store records are deleted (queued)
599
+ * and mirrors in the native module FS are unlinked as well.
600
+ * Returns the number of files removed. */
601
+ clear() {
602
+ let removed = 0;
603
+ for (const p of [...this.index.keys()]) {
604
+ if (p.startsWith('/sysroot/')) continue;
605
+ if (this.removeFile(p)) removed += 1;
606
+ }
607
+ return removed;
608
+ }
609
+
610
+ listFiles(prefix = '/') {
611
+ const p = normalizeVfsPath(prefix);
612
+ return [...this.index.keys()].filter((f) => f.startsWith(p)).sort();
613
+ }
614
+
615
+ // === Emscripten FS adaptation point (see header note) ===
616
+ /** Mirror the whole virtual FS into the native module's FS. The
617
+ * mounted FS is registered synchronously; copying the persisted
618
+ * files is asynchronous (their bytes may have to come out of the
619
+ * store), so this returns a promise loadTinyc awaits before the
620
+ * instance is handed out. Callers that mount an empty or
621
+ * cache-resident FS can ignore the promise.
622
+ * `moduleFsPrefix` is the directory inside the module FS the
623
+ * mirror lands under — the bridge's moduleFsPrefix ("/opfs" when
624
+ * the WasmFS OPFS backend is mounted there, "" for the memory
625
+ * root). It is remembered here so syncFile() and removeFile()
626
+ * hit the same locations; the virtual FS's own paths, index and
627
+ * store are unaffected by it. */
628
+ async mountTo(emscriptenFS, moduleFsPrefix = '') {
629
+ this._emscriptenFS = emscriptenFS ?? null;
630
+ this._moduleFsPrefix = moduleFsPrefix ?? '';
631
+ if (!this._emscriptenFS) return;
632
+ for (const path of [...this.index.keys()]) {
633
+ let bytes = this._cacheGet(path);
634
+ if (!bytes) {
635
+ const rec = await this._store.get(path);
636
+ if (rec) {
637
+ bytes = rec.bytes;
638
+ this._cachePut(path, bytes);
639
+ }
640
+ }
641
+ if (bytes) this._writeNative(path, bytes);
642
+ }
643
+ }
644
+
645
+ /** Mirror one file into the native FS from the content cache.
646
+ * Files written through this FS are synced as they are written;
647
+ * a file whose content is neither cached nor already mirrored
648
+ * cannot be synced synchronously and is left to mountTo. */
649
+ syncFile(path) {
650
+ const FS = this._emscriptenFS;
651
+ if (!FS) return;
652
+ const bytes = this._cacheGet(path);
653
+ if (!bytes) return;
654
+ this._writeNative(path, bytes);
655
+ }
656
+
657
+ /** The location of a (normalized) virtual path inside the
658
+ * native module's filesystem: under the mount prefix when one
659
+ * was given to mountTo, at the module FS root otherwise. */
660
+ _nativePath(path) {
661
+ return this._moduleFsPrefix ? this._moduleFsPrefix + path : path;
662
+ }
663
+
664
+ _writeNative(path, bytes) {
665
+ const FS = this._emscriptenFS;
666
+ const nativePath = this._nativePath(path);
667
+ const dir = nativePath.slice(0, nativePath.lastIndexOf('/')) || '/';
668
+ if (typeof FS.mkdirTree === 'function') FS.mkdirTree(dir);
669
+ FS.writeFile(nativePath, bytes);
670
+ }
671
+ }
672
+
673
+ // ---------------------------------------------------------------------
674
+ // Native bridge
675
+ //
676
+ // Normalizes the three native shapes onto one call interface whose
677
+ // function names are exactly the libtcc export names (tcc_new,
678
+ // tcc_compile_string, ..., plus main / tinyc_main):
679
+ // 'emscripten' module object with ccall (build.sh output)
680
+ // 'raw' WebAssembly.Instance exports with a memory
681
+ // 'mock' plain object of JS functions with the same names;
682
+ // strings and handles pass through as JS values.
683
+ // This is the injection point used by the tests and
684
+ // by anyone prototyping without a WASM build.
685
+ // ---------------------------------------------------------------------
686
+
687
+ class NativeBridge {
688
+ constructor(native, io) {
689
+ this.native = native;
690
+ this.io = io;
691
+ /** Directory inside the native module's filesystem under which
692
+ * the virtual FS is mirrored and native-side paths are rooted:
693
+ * "/opfs" when loadTinyc mounted the WasmFS OPFS backend there,
694
+ * "" (the module FS root, the memory backend) otherwise. Set by
695
+ * loadTinyc once the mount attempt has decided; every path that
696
+ * crosses into the native module — mirrored files, tcc_add_file
697
+ * and path registrations, callMain argv, product read-back —
698
+ * goes through modulePath() so the two stay consistent. */
699
+ this.moduleFsPrefix = '';
700
+ if (native && typeof native.ccall === 'function') this.mode = 'emscripten';
701
+ else if (native && native.memory instanceof WebAssembly.Memory) this.mode = 'raw';
702
+ else if (native && typeof native === 'object') this.mode = 'mock';
703
+ else {
704
+ throw new TinycError(
705
+ 'tinyc: unsupported native module shape; pass an Emscripten module, ' +
706
+ 'WebAssembly exports, or a mock object implementing the tcc_* functions'
707
+ );
708
+ }
709
+ }
710
+
711
+ /** Translate a virtual FS path to the path the native module
712
+ * knows it by: the normalized path under moduleFsPrefix. With no
713
+ * prefix (memory backend) the argument passes through exactly as
714
+ * given, so native calls are unchanged in that mode. */
715
+ modulePath(path) {
716
+ if (!this.moduleFsPrefix) return path;
717
+ return this.moduleFsPrefix + normalizeVfsPath(path);
718
+ }
719
+
720
+ has(name) {
721
+ const n = this.native;
722
+ switch (this.mode) {
723
+ case 'emscripten':
724
+ return typeof n['_' + name] === 'function' || typeof n[name] === 'function';
725
+ case 'raw':
726
+ return typeof n[name] === 'function' || typeof n['_' + name] === 'function';
727
+ default:
728
+ return typeof n[name] === 'function';
729
+ }
730
+ }
731
+
732
+ requireExport(name) {
733
+ if (!this.has(name)) throw new TinycMissingExportError(name);
734
+ }
735
+
736
+ _rawFn(name) {
737
+ return this.native[name] ?? this.native['_' + name];
738
+ }
739
+
740
+ /** Call a tcc_* style export. argTypes entries: 'number' | 'string'.
741
+ * In mock mode arguments pass through as JS values untouched. */
742
+ call(name, returnType, argTypes, args) {
743
+ this.requireExport(name);
744
+ if (this.mode === 'mock') return this.native[name](...args);
745
+ if (this.mode === 'emscripten') {
746
+ return this.native.ccall(name, returnType, argTypes, args);
747
+ }
748
+ return this._callRaw(name, argTypes, args);
749
+ }
750
+
751
+ _mem() {
752
+ return new Uint8Array(this.native.memory.buffer);
753
+ }
754
+
755
+ _alloc(bytes) {
756
+ const malloc = this._rawFn('malloc');
757
+ if (typeof malloc !== 'function') {
758
+ throw new TinycMissingExportError('malloc (needed to pass strings to the raw WASM module)');
759
+ }
760
+ const ptr = malloc(bytes);
761
+ if (!ptr) throw new TinycError('tinyc: WASM malloc returned null');
762
+ return ptr;
763
+ }
764
+
765
+ _free(ptr) {
766
+ const free = this._rawFn('free');
767
+ if (typeof free === 'function' && ptr) free(ptr);
768
+ }
769
+
770
+ _allocCString(str) {
771
+ const bytes = textEncoder.encode(str + '\0');
772
+ const ptr = this._alloc(bytes.length);
773
+ this._mem().set(bytes, ptr);
774
+ return ptr;
775
+ }
776
+
777
+ _callRaw(name, argTypes, args) {
778
+ const fn = this._rawFn(name);
779
+ const ptrs = [];
780
+ try {
781
+ const conv = args.map((arg, i) => {
782
+ if (argTypes[i] === 'string') {
783
+ const p = this._allocCString(arg);
784
+ ptrs.push(p);
785
+ return p;
786
+ }
787
+ return arg;
788
+ });
789
+ return fn(...conv);
790
+ } finally {
791
+ for (const p of ptrs) this._free(p);
792
+ }
793
+ }
794
+
795
+ /** Call the exported main / tinyc_main with a fully assembled argv.
796
+ * argvStrings[0] is the program name slot, already filled by the
797
+ * caller. tinyc_main is preferred when both are exported. */
798
+ callMain(argvStrings) {
799
+ const entry = this.has('tinyc_main') ? 'tinyc_main' : 'main';
800
+ this.requireExport(entry);
801
+ const argc = argvStrings.length;
802
+ if (this.mode === 'mock') return this.native[entry](argc, [...argvStrings]);
803
+ if (this.mode === 'emscripten') return this._callMainEmscripten(entry, argvStrings);
804
+ return this._callMainRaw(entry, argvStrings);
805
+ }
806
+
807
+ _callMainRaw(entry, argvStrings) {
808
+ const fn = this._rawFn(entry);
809
+ const strPtrs = argvStrings.map((s) => this._allocCString(s));
810
+ const argvPtr = this._alloc((argvStrings.length + 1) * 4);
811
+ try {
812
+ const view = new DataView(this.native.memory.buffer);
813
+ strPtrs.forEach((p, i) => view.setUint32(argvPtr + i * 4, p, true));
814
+ view.setUint32(argvPtr + argvStrings.length * 4, 0, true);
815
+ return fn(argvStrings.length, argvPtr);
816
+ } finally {
817
+ for (const p of strPtrs) this._free(p);
818
+ this._free(argvPtr);
819
+ }
820
+ }
821
+
822
+ _callMainEmscripten(entry, argvStrings) {
823
+ const n = this.native;
824
+ if (typeof n._malloc !== 'function' || !n.HEAPU8) {
825
+ throw new TinycError(
826
+ 'tinyc: Emscripten module must export _malloc and HEAPU8 to assemble argv'
827
+ );
828
+ }
829
+ const strPtrs = argvStrings.map((s) => {
830
+ const bytes = textEncoder.encode(s + '\0');
831
+ const p = n._malloc(bytes.length);
832
+ n.HEAPU8.set(bytes, p);
833
+ return p;
834
+ });
835
+ const argvPtr = n._malloc((argvStrings.length + 1) * 4);
836
+ try {
837
+ const view = new DataView(n.HEAPU8.buffer);
838
+ strPtrs.forEach((p, i) => view.setUint32(argvPtr + i * 4, p, true));
839
+ view.setUint32(argvPtr + argvStrings.length * 4, 0, true);
840
+ const fn = n['_' + entry];
841
+ return fn(argvStrings.length, argvPtr);
842
+ } finally {
843
+ for (const p of strPtrs) n._free(p);
844
+ n._free(argvPtr);
845
+ }
846
+ }
847
+ }
848
+
849
+ // ---------------------------------------------------------------------
850
+ // Running compiled wasm32 products
851
+ //
852
+ // A WebAssembly module cannot instantiate another WebAssembly module
853
+ // from inside itself — instantiation is a host capability. So for
854
+ // the wasm32 target, "run" does not go through the compiler module
855
+ // at all (native TCC provides no tcc_run for the wasm target): this
856
+ // glue layer takes the compiled product's bytes, instantiates them
857
+ // with the WebAssembly API, and calls the entry point. The instance
858
+ // gets a minimal WASI shim (wasi_snapshot_preview1) assembled here;
859
+ // proc_exit is turned into a WasiExit exception that the runner
860
+ // catches and reports as an exit code — it never terminates the host.
861
+ //
862
+ // runWasmModule(bytes, options) is async (WebAssembly.compile);
863
+ // runWasmModuleSync(bytes, options) uses WebAssembly.Module /
864
+ // Instance directly and is the variant used inside Workers and by
865
+ // the synchronous Tinyc / TinycState run paths below.
866
+ //
867
+ // options:
868
+ // args program arguments. For _start modules this is the WASI
869
+ // argv (args[0] is the program name slot); for a named
870
+ // entry it is the default argument list (see callArgs).
871
+ // callArgs arguments for a named entry, overriding args.
872
+ // entry export name to call instead of _start. Its return
873
+ // value is returned as-is (function style).
874
+ // env object of environment variables for environ_get.
875
+ // imports extra import objects, merged as-is over the WASI shim
876
+ // (a same-named entry replaces the shim's).
877
+ // io { out, err } receiving Uint8Array chunks from fd_write
878
+ // on fd 1 / 2. Defaults decode to console.log/error.
879
+ // stdin Uint8Array (or string) served by fd_read on fd 0.
880
+ // shims per-run custom shims: { name: fn } (module "env") or
881
+ // { "module.name": fn } for any other import module.
882
+ // heapBase heap start for the default shims' allocator.
883
+ // Without options.entry: if the module exports _start it is called
884
+ // (command style) and the result is { exitCode }; a normal return
885
+ // from _start means exit code 0.
886
+ //
887
+ // Imports are assembled in layers; for the same module.name, a later
888
+ // layer replaces an earlier one:
889
+ // 1. built-in WASI shim (wasi_snapshot_preview1)
890
+ // 2. default libc shims (runtime-shims.mjs, module "env")
891
+ // 3. package-global shims (registerGlobalShim / registerGlobalShims)
892
+ // 4. instance shims (Tinyc.registerShim; only for runs made
893
+ // through an instance)
894
+ // 5. per-run options.shims
895
+ // 6. options.imports, merged as-is (raw escape hatch)
896
+ // A registered shim is called as fn(ctx, ...cArgs). ctx exposes the
897
+ // running instance: { memory(), u8(), readCString(ptr),
898
+ // writeCString(ptr, str), readBytes(ptr, len),
899
+ // writeBytes(ptr, bytes), io }, where io is
900
+ // the run's byte IO. C arguments arrive in their wasm types (i32 /
901
+ // f32 / f64 as numbers, i64 as BigInt) and the return value goes
902
+ // back the same way — an i64 result must be returned as a BigInt.
903
+ // The JS function declares no signature: the engine coerces the
904
+ // arguments and the return value to the import type the module
905
+ // itself declares.
906
+ //
907
+ // Before instantiation, the module's required imports
908
+ // (WebAssembly.Module.imports) are diffed against the assembled
909
+ // importObject. Anything missing throws TinycMissingImportError
910
+ // listing every missing module.name, instead of surfacing the
911
+ // engine's raw LinkError.
912
+ // ---------------------------------------------------------------------
913
+
914
+ export class WasiExit extends Error {
915
+ constructor(code) {
916
+ super(`tinyc: wasi proc_exit(${code})`);
917
+ this.name = 'WasiExit';
918
+ this.exitCode = code;
919
+ }
920
+ }
921
+
922
+ const WASI_ERRNO = {
923
+ SUCCESS: 0, BADF: 8, FAULT: 21, INVAL: 28, NOSYS: 52, SPIPE: 70,
924
+ };
925
+ const WASI_RIGHTS_FD_READ = 1n << 1n;
926
+ const WASI_RIGHTS_FD_WRITE = 1n << 6n;
927
+
928
+ function createDefaultByteIO() {
929
+ const outDec = new TextDecoder();
930
+ const errDec = new TextDecoder();
931
+ return {
932
+ out: (bytes) => console.log(outDec.decode(bytes, { stream: true })),
933
+ err: (bytes) => console.error(errDec.decode(bytes, { stream: true })),
934
+ };
935
+ }
936
+
937
+ function createWasiShim(options, holder, io) {
938
+ const argv = (options.args ?? []).map(String);
939
+ const envPairs = Object.entries(options.env ?? {}).map(([k, v]) => `${k}=${v}`);
940
+ let stdin = options.stdin ?? new Uint8Array(0);
941
+ if (typeof stdin === 'string') stdin = textEncoder.encode(stdin);
942
+ let stdinPos = 0;
943
+
944
+ const mem = () => holder.memory;
945
+ const view = () => new DataView(mem().buffer);
946
+ const bytes = () => new Uint8Array(mem().buffer);
947
+
948
+ // Write a (char**) array at ptrAddr plus the NUL-terminated strings
949
+ // themselves at bufAddr; returns total string bytes written.
950
+ function writeStringTable(ptrAddr, bufAddr, strings) {
951
+ const v = view();
952
+ const m = bytes();
953
+ let offset = 0;
954
+ strings.forEach((s, i) => {
955
+ const encoded = textEncoder.encode(s + '\0');
956
+ v.setUint32(ptrAddr + i * 4, bufAddr + offset, true);
957
+ m.set(encoded, bufAddr + offset);
958
+ offset += encoded.length;
959
+ });
960
+ return offset;
961
+ }
962
+ const stringTableSize = (strings) =>
963
+ strings.reduce((n, s) => n + textEncoder.encode(s).length + 1, 0);
964
+
965
+ return {
966
+ fd_write(fd, iovs, iovsLen, nwrittenPtr) {
967
+ if (fd !== 1 && fd !== 2) return WASI_ERRNO.BADF;
968
+ if (!mem()) return WASI_ERRNO.FAULT;
969
+ const v = view();
970
+ const m = bytes();
971
+ const chunks = [];
972
+ let total = 0;
973
+ for (let i = 0; i < iovsLen; i++) {
974
+ const ptr = v.getUint32(iovs + i * 8, true);
975
+ const len = v.getUint32(iovs + i * 8 + 4, true);
976
+ chunks.push(m.slice(ptr, ptr + len)); // copy: memory may move
977
+ total += len;
978
+ }
979
+ const merged = new Uint8Array(total);
980
+ let at = 0;
981
+ for (const c of chunks) { merged.set(c, at); at += c.length; }
982
+ (fd === 1 ? io.out : io.err)(merged);
983
+ v.setUint32(nwrittenPtr, total, true);
984
+ return WASI_ERRNO.SUCCESS;
985
+ },
986
+
987
+ fd_read(fd, iovs, iovsLen, nreadPtr) {
988
+ if (fd !== 0) return WASI_ERRNO.BADF;
989
+ if (!mem()) return WASI_ERRNO.FAULT;
990
+ const v = view();
991
+ const m = bytes();
992
+ let total = 0;
993
+ for (let i = 0; i < iovsLen && stdinPos < stdin.length; i++) {
994
+ const ptr = v.getUint32(iovs + i * 8, true);
995
+ const len = v.getUint32(iovs + i * 8 + 4, true);
996
+ const n = Math.min(len, stdin.length - stdinPos);
997
+ m.set(stdin.subarray(stdinPos, stdinPos + n), ptr);
998
+ stdinPos += n;
999
+ total += n;
1000
+ }
1001
+ v.setUint32(nreadPtr, total, true);
1002
+ return WASI_ERRNO.SUCCESS;
1003
+ },
1004
+
1005
+ fd_close(fd) {
1006
+ return fd >= 0 && fd <= 2 ? WASI_ERRNO.SUCCESS : WASI_ERRNO.BADF;
1007
+ },
1008
+
1009
+ fd_seek(fd, _offset, _whence, newoffsetPtr) {
1010
+ if (fd < 0 || fd > 2) return WASI_ERRNO.BADF;
1011
+ if (!mem()) return WASI_ERRNO.FAULT;
1012
+ view().setBigUint64(newoffsetPtr, 0n, true);
1013
+ return WASI_ERRNO.SPIPE; // stdio descriptors are not seekable
1014
+ },
1015
+
1016
+ fd_fdstat_get(fd, ptr) {
1017
+ if (fd < 0 || fd > 2) return WASI_ERRNO.BADF;
1018
+ if (!mem()) return WASI_ERRNO.FAULT;
1019
+ const m = bytes();
1020
+ m.fill(0, ptr, ptr + 24);
1021
+ const v = view();
1022
+ m[ptr] = 2; // fs_filetype: character device
1023
+ v.setBigUint64(ptr + 8, fd === 0 ? WASI_RIGHTS_FD_READ : WASI_RIGHTS_FD_WRITE, true);
1024
+ v.setBigUint64(ptr + 16, 0n, true);
1025
+ return WASI_ERRNO.SUCCESS;
1026
+ },
1027
+
1028
+ proc_exit(code) {
1029
+ throw new WasiExit(code);
1030
+ },
1031
+
1032
+ args_sizes_get(argcPtr, argvBufSizePtr) {
1033
+ if (!mem()) return WASI_ERRNO.FAULT;
1034
+ const v = view();
1035
+ v.setUint32(argcPtr, argv.length, true);
1036
+ v.setUint32(argvBufSizePtr, stringTableSize(argv), true);
1037
+ return WASI_ERRNO.SUCCESS;
1038
+ },
1039
+
1040
+ args_get(argvPtr, bufPtr) {
1041
+ if (!mem()) return WASI_ERRNO.FAULT;
1042
+ writeStringTable(argvPtr, bufPtr, argv);
1043
+ return WASI_ERRNO.SUCCESS;
1044
+ },
1045
+
1046
+ environ_sizes_get(countPtr, sizePtr) {
1047
+ if (!mem()) return WASI_ERRNO.FAULT;
1048
+ const v = view();
1049
+ v.setUint32(countPtr, envPairs.length, true);
1050
+ v.setUint32(sizePtr, stringTableSize(envPairs), true);
1051
+ return WASI_ERRNO.SUCCESS;
1052
+ },
1053
+
1054
+ environ_get(envPtr, bufPtr) {
1055
+ if (!mem()) return WASI_ERRNO.FAULT;
1056
+ writeStringTable(envPtr, bufPtr, envPairs);
1057
+ return WASI_ERRNO.SUCCESS;
1058
+ },
1059
+
1060
+ clock_time_get(id, _precision, resultPtr) {
1061
+ if (!mem()) return WASI_ERRNO.FAULT;
1062
+ const nowNs = id === 0
1063
+ ? BigInt(Date.now()) * 1_000_000n
1064
+ : BigInt(Math.round(performance.now() * 1_000_000));
1065
+ view().setBigUint64(resultPtr, nowNs, true);
1066
+ return WASI_ERRNO.SUCCESS;
1067
+ },
1068
+
1069
+ random_get(bufPtr, len) {
1070
+ if (!mem()) return WASI_ERRNO.FAULT;
1071
+ const m = bytes();
1072
+ const chunk = new Uint8Array(len);
1073
+ if (typeof globalThis.crypto?.getRandomValues === 'function') {
1074
+ for (let at = 0; at < len; at += 65536) {
1075
+ globalThis.crypto.getRandomValues(
1076
+ chunk.subarray(at, Math.min(at + 65536, len)));
1077
+ }
1078
+ } else {
1079
+ for (let i = 0; i < len; i++) chunk[i] = Math.floor(Math.random() * 256);
1080
+ }
1081
+ m.set(chunk, bufPtr);
1082
+ return WASI_ERRNO.SUCCESS;
1083
+ },
1084
+
1085
+ sched_yield() {
1086
+ return WASI_ERRNO.SUCCESS;
1087
+ },
1088
+ };
1089
+ }
1090
+
1091
+ // ---------------------------------------------------------------------
1092
+ // Custom shim registration
1093
+ //
1094
+ // A shim key is a bare name ("printf", served from the "env"
1095
+ // module) or "module.name" for any other import module — including
1096
+ // wasi_snapshot_preview1, whose built-in entries can be overridden
1097
+ // the same way. Registrations live in Maps keyed by the canonical
1098
+ // "module.name" form; registering the same key again replaces the
1099
+ // previous function.
1100
+ // ---------------------------------------------------------------------
1101
+
1102
+ const globalShimRegistry = new Map();
1103
+
1104
+ function splitShimKey(key) {
1105
+ const dot = key.indexOf('.');
1106
+ if (dot < 0) return { module: 'env', name: key };
1107
+ return { module: key.slice(0, dot), name: key.slice(dot + 1) };
1108
+ }
1109
+
1110
+ function canonicalShimKey(key) {
1111
+ const { module, name } = splitShimKey(key);
1112
+ return `${module}.${name}`;
1113
+ }
1114
+
1115
+ function setShimEntry(map, name, fn) {
1116
+ if (typeof name !== 'string' || name.length === 0) {
1117
+ throw new TinycError('tinyc: shim name must be a non-empty string');
1118
+ }
1119
+ if (typeof fn !== 'function') {
1120
+ throw new TinycError(`tinyc: shim "${name}" must be a function`);
1121
+ }
1122
+ map.set(canonicalShimKey(name), fn);
1123
+ }
1124
+
1125
+ function shimEntriesOf(layer) {
1126
+ if (!layer) return [];
1127
+ if (layer instanceof Map) return [...layer.entries()];
1128
+ return Object.entries(layer);
1129
+ }
1130
+
1131
+ /** Register a package-global shim: it applies to every later
1132
+ * runWasmModule call and every instance run, until unregistered.
1133
+ * Only the default shims sit below this layer. */
1134
+ export function registerGlobalShim(name, fn) {
1135
+ setShimEntry(globalShimRegistry, name, fn);
1136
+ }
1137
+
1138
+ /** Bulk form of registerGlobalShim: { name: fn, ... }. */
1139
+ export function registerGlobalShims(shims) {
1140
+ for (const [name, fn] of shimEntriesOf(shims)) {
1141
+ setShimEntry(globalShimRegistry, name, fn);
1142
+ }
1143
+ }
1144
+
1145
+ export function unregisterGlobalShim(name) {
1146
+ globalShimRegistry.delete(canonicalShimKey(name));
1147
+ }
1148
+
1149
+ /** The ctx handed to every registered shim as its first argument.
1150
+ * Memory access goes through the holder, which the runner fills
1151
+ * after instantiation and before the entry point runs — so a shim
1152
+ * can only ever be called with the memory in place. */
1153
+ function createShimContext(holder, byteIO) {
1154
+ return {
1155
+ memory: () => holder.memory,
1156
+ u8: () => new Uint8Array(holder.memory.buffer),
1157
+ readCString(ptr, maxLength = 1 << 16) {
1158
+ const m = new Uint8Array(holder.memory.buffer);
1159
+ let end = ptr;
1160
+ while (end < m.length && end - ptr < maxLength && m[end] !== 0) end++;
1161
+ return textDecoder.decode(m.subarray(ptr, end));
1162
+ },
1163
+ writeCString(ptr, str) {
1164
+ const bytes = textEncoder.encode(str);
1165
+ const m = new Uint8Array(holder.memory.buffer);
1166
+ m.set(bytes, ptr);
1167
+ m[ptr + bytes.length] = 0;
1168
+ return bytes.length + 1;
1169
+ },
1170
+ readBytes(ptr, length) {
1171
+ return new Uint8Array(holder.memory.buffer).slice(ptr, ptr + length);
1172
+ },
1173
+ writeBytes(ptr, data) {
1174
+ new Uint8Array(holder.memory.buffer).set(data, ptr);
1175
+ },
1176
+ io: byteIO,
1177
+ };
1178
+ }
1179
+
1180
+ function buildWasmImports(options, holder) {
1181
+ const defaults = createDefaultByteIO();
1182
+ const byteIO = {
1183
+ out: options.io?.out ?? defaults.out,
1184
+ err: options.io?.err ?? defaults.err,
1185
+ in: options.io?.in,
1186
+ };
1187
+ const imports = {};
1188
+ const put = (moduleName, name, value) => {
1189
+ (imports[moduleName] ??= {})[name] = value;
1190
+ };
1191
+ // Layer 1: built-in WASI shim.
1192
+ const wasi = createWasiShim(options, holder, byteIO);
1193
+ for (const [name, fn] of Object.entries(wasi)) {
1194
+ put('wasi_snapshot_preview1', name, fn);
1195
+ }
1196
+ // Layer 2: default libc shims (module "env").
1197
+ const defaultShims = createDefaultShims({
1198
+ io: byteIO,
1199
+ holder,
1200
+ args: options.args,
1201
+ env: options.env,
1202
+ stdin: options.stdin,
1203
+ heapBase: options.heapBase,
1204
+ });
1205
+ for (const [moduleName, fns] of Object.entries(defaultShims)) {
1206
+ for (const [name, fn] of Object.entries(fns)) put(moduleName, name, fn);
1207
+ }
1208
+ // Layers 3-5: registered shims — package-global, then instance,
1209
+ // then per-run. Each is wrapped so it is called as fn(ctx, ...).
1210
+ const ctx = createShimContext(holder, byteIO);
1211
+ for (const layer of [globalShimRegistry, options._instanceShims, options.shims]) {
1212
+ for (const [key, fn] of shimEntriesOf(layer)) {
1213
+ const { module: moduleName, name } = splitShimKey(key);
1214
+ put(moduleName, name, (...cArgs) => fn(ctx, ...cArgs));
1215
+ }
1216
+ }
1217
+ // Layer 6: raw imports, as-is.
1218
+ for (const [moduleName, fns] of Object.entries(options.imports ?? {})) {
1219
+ for (const [name, value] of Object.entries(fns)) put(moduleName, name, value);
1220
+ }
1221
+ return imports;
1222
+ }
1223
+
1224
+ /** Thrown before instantiation when a wasm product imports symbols
1225
+ * that no import layer provides. `missing` is the full list of
1226
+ * "module.name" strings; the message names the registration routes
1227
+ * that can supply them. */
1228
+ export class TinycMissingImportError extends TinycError {
1229
+ constructor(missing) {
1230
+ const list = missing.map((m) => `${m.module}.${m.name}`);
1231
+ super(
1232
+ `tinyc: wasm module imports are not satisfied: ${list.join(', ')}. ` +
1233
+ `Provide them as shims: runWasmModule(bytes, { shims: { name: fn } }), ` +
1234
+ `instance.registerShim(name, fn) / instance.registerShims({ ... }), or ` +
1235
+ `registerGlobalShim(name, fn); use a "module.name" key for imports ` +
1236
+ `outside the default "env" module.`
1237
+ );
1238
+ this.name = 'TinycMissingImportError';
1239
+ this.missing = list;
1240
+ }
1241
+ }
1242
+
1243
+ function assertAllImportsSatisfied(module, imports) {
1244
+ const missing = [];
1245
+ for (const imp of WebAssembly.Module.imports(module)) {
1246
+ const provided = imports[imp.module]?.[imp.name];
1247
+ const ok =
1248
+ imp.kind === 'function'
1249
+ ? typeof provided === 'function'
1250
+ : provided !== undefined;
1251
+ if (!ok) missing.push(imp);
1252
+ }
1253
+ if (missing.length > 0) throw new TinycMissingImportError(missing);
1254
+ }
1255
+
1256
+ function runWasmInstance(instance, options, holder) {
1257
+ holder.memory = instance.exports.memory ?? null;
1258
+ holder.instance = instance;
1259
+ const exports = instance.exports;
1260
+ try {
1261
+ if (options.entry !== undefined) {
1262
+ const fn = exports[options.entry];
1263
+ if (typeof fn !== 'function') {
1264
+ throw new TinycError(`tinyc: wasm module does not export "${options.entry}"`);
1265
+ }
1266
+ return fn(...(options.callArgs ?? options.args ?? []));
1267
+ }
1268
+ if (typeof exports._start === 'function') {
1269
+ exports._start();
1270
+ return { exitCode: 0 };
1271
+ }
1272
+ throw new TinycError(
1273
+ 'tinyc: wasm module exports no _start; pass options.entry to call an exported function'
1274
+ );
1275
+ } catch (err) {
1276
+ if (err instanceof WasiExit) return { exitCode: err.exitCode };
1277
+ if (err instanceof ShimExit) return { exitCode: err.exitCode };
1278
+ throw err;
1279
+ }
1280
+ }
1281
+
1282
+ /** Instantiate and run a compiled wasm32 product (async variant,
1283
+ * built on WebAssembly.compile). See the section header above for
1284
+ * the options and the entry conventions. */
1285
+ export async function runWasmModule(bytes, options = {}) {
1286
+ const holder = { memory: null, instance: null };
1287
+ const imports = buildWasmImports(options, holder);
1288
+ const module = bytes instanceof WebAssembly.Module
1289
+ ? bytes
1290
+ : await WebAssembly.compile(bytes);
1291
+ assertAllImportsSatisfied(module, imports);
1292
+ const instance = await WebAssembly.instantiate(module, imports);
1293
+ return runWasmInstance(instance, options, holder);
1294
+ }
1295
+
1296
+ /** Synchronous variant of runWasmModule (WebAssembly.Module +
1297
+ * WebAssembly.Instance). This is the variant used inside Workers
1298
+ * and by TinycState.run / Tinyc.callMain below. */
1299
+ export function runWasmModuleSync(bytes, options = {}) {
1300
+ const holder = { memory: null, instance: null };
1301
+ const imports = buildWasmImports(options, holder);
1302
+ const module = bytes instanceof WebAssembly.Module
1303
+ ? bytes
1304
+ : new WebAssembly.Module(bytes);
1305
+ assertAllImportsSatisfied(module, imports);
1306
+ const instance = new WebAssembly.Instance(module, imports);
1307
+ return runWasmInstance(instance, options, holder);
1308
+ }
1309
+
1310
+ /** Where run paths put the compiled product in the virtual FS when
1311
+ * no output path is given: TCC's own default output name, at the
1312
+ * virtual FS root. */
1313
+ export const DEFAULT_RUN_OUTPUT = '/a.out';
1314
+
1315
+ // Adapt an instance text IO ({ out, err } receiving strings) to the
1316
+ // byte IO runWasmModule expects, decoding each fd_write chunk.
1317
+ function textIOToByteIO(io) {
1318
+ const outDec = new TextDecoder();
1319
+ const errDec = new TextDecoder();
1320
+ return {
1321
+ out: (chunk) => io.out(outDec.decode(chunk, { stream: true })),
1322
+ err: (chunk) => io.err(errDec.decode(chunk, { stream: true })),
1323
+ };
1324
+ }
1325
+
1326
+ // ---------------------------------------------------------------------
1327
+ // Module memory helpers
1328
+ //
1329
+ // Passing strings/bytes into a module instance: if the module
1330
+ // exports malloc (and free), writeModuleData allocates through it
1331
+ // and the returned free() releases the block. Otherwise the caller
1332
+ // supplies the write address with options.offset — a number, or a
1333
+ // function (byteLength) => address for bump-allocator style layouts.
1334
+ // ---------------------------------------------------------------------
1335
+
1336
+ export function writeModuleData(instance, data, options = {}) {
1337
+ const memory = instance.exports.memory;
1338
+ if (!memory) throw new TinycError('tinyc: writeModuleData: module exports no memory');
1339
+ const chunk = typeof data === 'string' ? textEncoder.encode(data) : data;
1340
+ const malloc = instance.exports.malloc ?? instance.exports._malloc;
1341
+ let ptr;
1342
+ let free = null;
1343
+ if (typeof malloc === 'function' && options.offset === undefined) {
1344
+ ptr = malloc(chunk.length);
1345
+ if (!ptr && chunk.length > 0) throw new TinycError('tinyc: writeModuleData: malloc returned null');
1346
+ const freeFn = instance.exports.free ?? instance.exports._free;
1347
+ if (typeof freeFn === 'function') free = () => freeFn(ptr);
1348
+ } else if (options.offset !== undefined) {
1349
+ ptr = typeof options.offset === 'function' ? options.offset(chunk.length) : options.offset;
1350
+ } else {
1351
+ throw new TinycError(
1352
+ 'tinyc: writeModuleData needs an exported malloc or options.offset'
1353
+ );
1354
+ }
1355
+ new Uint8Array(memory.buffer).set(chunk, ptr);
1356
+ return { ptr, length: chunk.length, free };
1357
+ }
1358
+
1359
+ export function readModuleData(instance, ptr, length) {
1360
+ const memory = instance.exports.memory;
1361
+ if (!memory) throw new TinycError('tinyc: readModuleData: module exports no memory');
1362
+ return new Uint8Array(memory.buffer).slice(ptr, ptr + length);
1363
+ }
1364
+
1365
+ export function readModuleCString(instance, ptr, maxLength = 1 << 16) {
1366
+ const memory = instance.exports.memory;
1367
+ if (!memory) throw new TinycError('tinyc: readModuleCString: module exports no memory');
1368
+ const m = new Uint8Array(memory.buffer);
1369
+ let end = ptr;
1370
+ while (end < m.length && end - ptr < maxLength && m[end] !== 0) end++;
1371
+ return textDecoder.decode(m.subarray(ptr, end));
1372
+ }
1373
+
1374
+ // ---------------------------------------------------------------------
1375
+ // Fine-grained API: one TCCState wrapped as a JS object.
1376
+ // Method names mirror the libtcc functions they call. A method whose
1377
+ // export is absent from the native module throws
1378
+ // TinycMissingExportError naming that export.
1379
+ // ---------------------------------------------------------------------
1380
+
1381
+ export const TCC_OUTPUT = {
1382
+ MEMORY: 1,
1383
+ EXE: 2,
1384
+ OBJ: 3,
1385
+ DLL: 4,
1386
+ PREPROCESS: 5,
1387
+ };
1388
+
1389
+ export class TinycState {
1390
+ constructor(instance, handle) {
1391
+ this._instance = instance;
1392
+ this._bridge = instance._bridge;
1393
+ this.handle = handle;
1394
+ this._io = null;
1395
+ this._deleted = false;
1396
+ }
1397
+
1398
+ _call(name, returnType, argTypes, args) {
1399
+ if (this._deleted) throw new TinycError('tinyc: state already deleted');
1400
+ return this._bridge.call(name, returnType, argTypes, [this.handle, ...args]);
1401
+ }
1402
+
1403
+ _checkRc(name, rc) {
1404
+ if (typeof rc === 'number' && rc < 0) {
1405
+ throw new TinycError(`tinyc: ${name} failed with code ${rc}`, rc);
1406
+ }
1407
+ return rc;
1408
+ }
1409
+
1410
+ /** Per-state IO. The error channel takes effect immediately through
1411
+ * tcc_set_error_func; out/in are kept for JS-side helpers because
1412
+ * native stdout routing is per-module (see Tinyc.setIO). */
1413
+ setIO(partial) {
1414
+ this._io = normalizeIO(partial, this._io ?? this._instance.io);
1415
+ this._installErrorFunc();
1416
+ return this;
1417
+ }
1418
+
1419
+ get io() {
1420
+ return this._io ?? this._instance.io;
1421
+ }
1422
+
1423
+ _installErrorFunc() {
1424
+ if (!this._bridge.has('tcc_set_error_func')) return;
1425
+ const io = this.io;
1426
+ const errorFunc = (opaque, msg) => {
1427
+ io.err(String(msg) + '\n');
1428
+ };
1429
+ this._errorFunc = errorFunc; // pinned: must outlive the state
1430
+ if (this._bridge.mode === 'mock') {
1431
+ this._bridge.native.tcc_set_error_func(this.handle, null, errorFunc);
1432
+ } else if (this._bridge.mode === 'emscripten') {
1433
+ const n = this._bridge.native;
1434
+ if (typeof n.addFunction === 'function') {
1435
+ const ptr = n.addFunction((opaque, msgPtr) => {
1436
+ errorFunc(opaque, n.UTF8ToString(msgPtr));
1437
+ }, 'vii');
1438
+ this._errorFuncPtr = ptr;
1439
+ n.ccall('tcc_set_error_func', null, ['number', 'number', 'number'],
1440
+ [this.handle, 0, ptr]);
1441
+ }
1442
+ }
1443
+ // raw mode: function-pointer upcalls need a wasm table slot; the
1444
+ // native default error writer already routes through module IO.
1445
+ }
1446
+
1447
+ setLibPath(path) {
1448
+ this._call('tcc_set_lib_path', null, ['string'], [this._bridge.modulePath(path)]);
1449
+ return this;
1450
+ }
1451
+
1452
+ setOptions(str) {
1453
+ return this._checkRc('tcc_set_options',
1454
+ this._call('tcc_set_options', 'number', ['string'], [str]));
1455
+ }
1456
+
1457
+ addIncludePath(path) {
1458
+ return this._checkRc('tcc_add_include_path',
1459
+ this._call('tcc_add_include_path', 'number', ['string'], [this._bridge.modulePath(path)]));
1460
+ }
1461
+
1462
+ addSysincludePath(path) {
1463
+ return this._checkRc('tcc_add_sysinclude_path',
1464
+ this._call('tcc_add_sysinclude_path', 'number', ['string'], [this._bridge.modulePath(path)]));
1465
+ }
1466
+
1467
+ addLibraryPath(path) {
1468
+ return this._checkRc('tcc_add_library_path',
1469
+ this._call('tcc_add_library_path', 'number', ['string'], [this._bridge.modulePath(path)]));
1470
+ }
1471
+
1472
+ addLibrary(name) {
1473
+ return this._checkRc('tcc_add_library',
1474
+ this._call('tcc_add_library', 'number', ['string'], [name]));
1475
+ }
1476
+
1477
+ defineSymbol(sym, value = '1') {
1478
+ this._call('tcc_define_symbol', null, ['string', 'string'], [sym, value]);
1479
+ return this;
1480
+ }
1481
+
1482
+ undefineSymbol(sym) {
1483
+ this._call('tcc_undefine_symbol', null, ['string'], [sym]);
1484
+ return this;
1485
+ }
1486
+
1487
+ setOutputType(type) {
1488
+ return this._checkRc('tcc_set_output_type',
1489
+ this._call('tcc_set_output_type', 'number', ['number'], [type]));
1490
+ }
1491
+
1492
+ /** Add a file (source, object or archive) by virtual path. The file
1493
+ * must exist in the instance's virtual FS; it is synced to the
1494
+ * native filesystem first when an adapter is mounted. The path
1495
+ * handed to tcc_add_file is the file's location inside the
1496
+ * module FS (bridge.modulePath), which differs from the virtual
1497
+ * path when the OPFS backend is mounted. */
1498
+ addFile(path) {
1499
+ const p = normalizeVfsPath(path);
1500
+ if (this._bridge.mode !== 'mock' && !this._instance.fs.hasFile(p)) {
1501
+ throw new TinycError(`tinyc: addFile: ${p} is not in the virtual FS`);
1502
+ }
1503
+ this._instance.fs.syncFile(p);
1504
+ return this._checkRc('tcc_add_file',
1505
+ this._call('tcc_add_file', 'number', ['string'], [this._bridge.modulePath(p)]));
1506
+ }
1507
+
1508
+ compileString(source) {
1509
+ return this._checkRc('tcc_compile_string',
1510
+ this._call('tcc_compile_string', 'number', ['string'], [source]));
1511
+ }
1512
+
1513
+ /** Compile a file from the virtual FS: its content is fed through
1514
+ * tcc_compile_string with a #line marker carrying the path, so no
1515
+ * native filesystem access is needed for plain sources. The
1516
+ * marker carries the virtual path exactly as given — it is what
1517
+ * diagnostics show the user — never the file's location inside
1518
+ * the module FS. */
1519
+ compileFile(path) {
1520
+ const p = normalizeVfsPath(path);
1521
+ const src = this._instance.fs.readTextFile(p);
1522
+ const marked = `#line 1 "${p}"\n${src}`;
1523
+ return this._checkRc('tcc_compile_string',
1524
+ this._call('tcc_compile_string', 'number', ['string'], [marked]));
1525
+ }
1526
+
1527
+ /** Write the compiled product to a virtual path. TCC writes it
1528
+ * inside the module FS (at bridge.modulePath(path)); exportFile
1529
+ * reads it back from there into the virtual FS. */
1530
+ outputFile(path) {
1531
+ return this._checkRc('tcc_output_file',
1532
+ this._call('tcc_output_file', 'number', ['string'],
1533
+ [this._bridge.modulePath(normalizeVfsPath(path))]));
1534
+ }
1535
+
1536
+ relocate() {
1537
+ return this._checkRc('tcc_relocate',
1538
+ this._call('tcc_relocate', 'number', [], []));
1539
+ }
1540
+
1541
+ getSymbol(name) {
1542
+ return this._call('tcc_get_symbol', 'number', ['string'], [name]);
1543
+ }
1544
+
1545
+ /** Run the compiled program. Only on the wasm32 target, and not
1546
+ * through the native module: a WASM module cannot instantiate
1547
+ * another module from inside itself, and native TCC provides no
1548
+ * tcc_run for the wasm target. Instead the glue layer writes the
1549
+ * product to a file in the virtual FS (options.outputPath,
1550
+ * default DEFAULT_RUN_OUTPUT), reads its bytes back, and
1551
+ * instantiates it in the host with runWasmModuleSync — the WASI
1552
+ * argv is [outputPath, ...args]. Returns the program's exit code
1553
+ * for a _start module, or the named entry's return value when
1554
+ * options.entry is given. This switches the state to EXE output
1555
+ * type. On every other target the glue layer throws
1556
+ * TinycRunNotSupportedError before anything is passed to the
1557
+ * native module — those targets compile to files only.
1558
+ * options: { outputPath, entry, callArgs, env, imports, shims,
1559
+ * stdin, heapBase, io } — entry/callArgs/env/imports/shims/stdin/
1560
+ * heapBase forward to runWasmModuleSync, and the instance's
1561
+ * registered shims apply automatically; io is a text IO partial
1562
+ * (default: this state's IO) whose out/err receive the program's
1563
+ * fd_write output, decoded. */
1564
+ run(args = [], options = {}) {
1565
+ if (!isRunnableTarget(this._instance.target)) {
1566
+ throw new TinycRunNotSupportedError(this._instance.target);
1567
+ }
1568
+ const outputPath = options.outputPath ?? DEFAULT_RUN_OUTPUT;
1569
+ this.setOutputType(TCC_OUTPUT.EXE);
1570
+ this.outputFile(outputPath);
1571
+ const bytes = this._instance.exportFile(outputPath);
1572
+ const io = normalizeIO(options.io, this.io);
1573
+ const result = runWasmModuleSync(bytes, {
1574
+ args: [outputPath, ...args.map(String)],
1575
+ entry: options.entry,
1576
+ callArgs: options.callArgs,
1577
+ env: options.env,
1578
+ imports: options.imports,
1579
+ shims: options.shims,
1580
+ stdin: options.stdin,
1581
+ heapBase: options.heapBase,
1582
+ _instanceShims: this._instance._shims,
1583
+ io: textIOToByteIO(io),
1584
+ });
1585
+ flushIO(io);
1586
+ if (result && typeof result === 'object' && 'exitCode' in result) {
1587
+ return result.exitCode;
1588
+ }
1589
+ return result;
1590
+ }
1591
+
1592
+ delete() {
1593
+ if (this._deleted) return;
1594
+ this._deleted = true;
1595
+ if (this._bridge.has('tcc_delete')) {
1596
+ this._bridge.call('tcc_delete', null, [], [this.handle]);
1597
+ }
1598
+ if (this._errorFuncPtr && typeof this._bridge.native.removeFunction === 'function') {
1599
+ this._bridge.native.removeFunction(this._errorFuncPtr);
1600
+ this._errorFuncPtr = null;
1601
+ }
1602
+ this._instance._forgetState(this);
1603
+ }
1604
+
1605
+ [Symbol.dispose]() {
1606
+ this.delete();
1607
+ }
1608
+ }
1609
+
1610
+ // Compiler options whose value is a filesystem path, in the
1611
+ // separate form ("-o file") and in the joined form ("-I/dir").
1612
+ // Used only by Tinyc._moduleArgv to relocate path arguments into
1613
+ // the module FS when the OPFS backend is mounted; option values
1614
+ // that are not paths (-l names, -D macros, -x languages) are never
1615
+ // in these tables and pass through untouched.
1616
+ const PATH_VALUE_OPTIONS = new Set([
1617
+ '-o', '-I', '-L', '-B', '-MF',
1618
+ '-include', '-isystem', '-idirafter', '-iquote',
1619
+ '-iprefix', '-iwithprefix', '-iwithprefixbefore',
1620
+ ]);
1621
+ const PATH_JOINED_OPTIONS = [
1622
+ '-iwithprefixbefore', '-iwithprefix', '-idirafter', '-isystem',
1623
+ '-iprefix', '-iquote', '-include', '-I', '-L', '-B', '-MF', '-o',
1624
+ ];
1625
+
1626
+ // ---------------------------------------------------------------------
1627
+ // Instance
1628
+ // ---------------------------------------------------------------------
1629
+
1630
+ export class Tinyc {
1631
+ constructor(bridge, { fs, io, target = DEFAULT_TARGET }) {
1632
+ this._bridge = bridge;
1633
+ this.fs = fs;
1634
+ this._io = io;
1635
+ this.target = target;
1636
+ this._states = new Set();
1637
+ this._mainRunning = false;
1638
+ this._shims = new Map();
1639
+ this._fsBackend = 'memory';
1640
+ }
1641
+
1642
+ get io() {
1643
+ return this._io;
1644
+ }
1645
+
1646
+ /** True only for the wasm32 target: its compiled output is
1647
+ * WebAssembly, which the browser itself instantiates and runs.
1648
+ * All other targets compile to files only. */
1649
+ get canRun() {
1650
+ return isRunnableTarget(this.target);
1651
+ }
1652
+
1653
+ get nativeMode() {
1654
+ return this._bridge.mode;
1655
+ }
1656
+
1657
+ /** The backend mounted at "/opfs" in the native module's
1658
+ * filesystem: 'opfs' when loadTinyc mounted the WasmFS OPFS
1659
+ * backend there, 'memory' when it did not — the browser main
1660
+ * thread, a browser without OPFS, and every non-Emscripten
1661
+ * module land on 'memory'. Decided once per module by loadTinyc
1662
+ * (see tryMountOpfsBackend). The module filesystem's root is the
1663
+ * WasmFS memory backend in both cases; with 'opfs', the mirrored
1664
+ * compile working set and every path handed to the native module
1665
+ * are rooted at "/opfs" (bridge.moduleFsPrefix), so the working
1666
+ * set lives on disk. */
1667
+ get fsBackend() {
1668
+ return this._fsBackend;
1669
+ }
1670
+
1671
+ /** Replace the instance IO. out/err are module-level on the native
1672
+ * side (Emscripten print/printErr were bound at load time to the
1673
+ * functions this object delegates to), so swapping the delegates
1674
+ * here reroutes native output for everything created afterwards
1675
+ * and for callMain. */
1676
+ setIO(partial) {
1677
+ this._io = normalizeIO(partial, this._io);
1678
+ return this;
1679
+ }
1680
+
1681
+ /** Register a custom shim on this instance: a JS function served
1682
+ * as a wasm import for every later run made through this
1683
+ * instance (state.run, callMain "-run"). `name` is a bare
1684
+ * function name (module "env") or "module.name" for any other
1685
+ * import module — including wasi_snapshot_preview1 entries. The
1686
+ * function is called as fn(ctx, ...cArgs); see the runWasmModule
1687
+ * section for the ctx convention and the layer priority.
1688
+ * Registering the same name again replaces the previous shim. */
1689
+ registerShim(name, fn) {
1690
+ setShimEntry(this._shims, name, fn);
1691
+ return this;
1692
+ }
1693
+
1694
+ /** Bulk form of registerShim: { name: fn, ... }. */
1695
+ registerShims(shims) {
1696
+ for (const [name, fn] of shimEntriesOf(shims)) {
1697
+ setShimEntry(this._shims, name, fn);
1698
+ }
1699
+ return this;
1700
+ }
1701
+
1702
+ /** Remove an instance shim previously added with registerShim. */
1703
+ unregisterShim(name) {
1704
+ this._shims.delete(canonicalShimKey(name));
1705
+ return this;
1706
+ }
1707
+
1708
+ // -- virtual FS shortcuts (full API on instance.fs) --
1709
+ addFile(path, content) { return this.fs.addFile(path, content); }
1710
+ addFileSync(path, content) { return this.fs.addFileSync(path, content); }
1711
+ addFileFromUrl(path, url, opts) { return this.fs.addFileFromUrl(path, url, opts); }
1712
+ registerIncludeDir(path) { return this.fs.registerIncludeDir(path); }
1713
+ hasFile(path) { return this.fs.hasFile(path); }
1714
+ readFile(path) { return this.fs.readFile(path); }
1715
+ readTextFile(path) { return this.fs.readTextFile(path); }
1716
+ readFileAsync(path) { return this.fs.readFileAsync(path); }
1717
+ readTextFileAsync(path) { return this.fs.readTextFileAsync(path); }
1718
+ removeFile(path) { return this.fs.removeFile(path); }
1719
+ clearFiles() { return this.fs.clear(); }
1720
+ listFiles(prefix) { return this.fs.listFiles(prefix); }
1721
+
1722
+ /** Resolve once the virtual FS's queued store writes and deletes
1723
+ * (from addFileSync / removeFile / clearFiles) have landed in the
1724
+ * persistent store. */
1725
+ whenIdle() { return this.fs.whenIdle(); }
1726
+
1727
+ /** Read a compiled product (object file, executable, library —
1728
+ * including a Windows PE for the x86_64-windows target) out of
1729
+ * the virtual FS as bytes. This is how compile-to-file results
1730
+ * leave the browser package, for every target. With an Emscripten
1731
+ * module, a file that only exists in the module FS is read from
1732
+ * there and mirrored into the virtual FS. A file restored from
1733
+ * the persistent store that is not in the content cache falls
1734
+ * back to the module FS copy; when there is none either, the
1735
+ * read fails naming exportFileAsync as the alternative. */
1736
+ exportFile(path) {
1737
+ const p = normalizeVfsPath(path);
1738
+ let cacheMiss = null;
1739
+ if (this.fs.hasFile(p)) {
1740
+ try {
1741
+ return this.fs.readFile(p);
1742
+ } catch (err) {
1743
+ cacheMiss = err;
1744
+ }
1745
+ }
1746
+ const FS = this._bridge.native?.FS;
1747
+ if (FS && typeof FS.readFile === 'function') {
1748
+ try {
1749
+ const bytes = FS.readFile(this._bridge.modulePath(p));
1750
+ this.fs.addFileSync(p, bytes);
1751
+ return this.fs.readFile(p);
1752
+ } catch {
1753
+ // fall through to the error below
1754
+ }
1755
+ }
1756
+ if (cacheMiss) {
1757
+ throw new TinycError(
1758
+ `tinyc: ${p} is persisted in the virtual FS store but is not in ` +
1759
+ `the in-memory cache; read it with exportFileAsync() instead`
1760
+ );
1761
+ }
1762
+ throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
1763
+ }
1764
+
1765
+ /** exportFile, reading the content from the persistent store
1766
+ * when it is not in the content cache. */
1767
+ async exportFileAsync(path) {
1768
+ const p = normalizeVfsPath(path);
1769
+ if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
1770
+ const FS = this._bridge.native?.FS;
1771
+ if (FS && typeof FS.readFile === 'function') {
1772
+ try {
1773
+ const bytes = FS.readFile(this._bridge.modulePath(p));
1774
+ this.fs.addFileSync(p, bytes);
1775
+ return bytes;
1776
+ } catch {
1777
+ // fall through to the error below
1778
+ }
1779
+ }
1780
+ throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
1781
+ }
1782
+
1783
+ /** exportFile as a Blob, e.g. for a download link or a File
1784
+ * handed to another tool. */
1785
+ exportBlob(path, type = 'application/octet-stream') {
1786
+ return new Blob([this.exportFile(path)], { type });
1787
+ }
1788
+
1789
+ /** Execute a wasm32 product already sitting in the virtual FS —
1790
+ * a file produced by an earlier compile-to-file callMain, or one
1791
+ * placed there with addFile — without recompiling. The bytes are
1792
+ * read with exportFile and instantiated with runWasmModuleSync,
1793
+ * so the shim stack is exactly the one "-run" uses: default libc
1794
+ * shims, package-global shims, this instance's registered shims,
1795
+ * then options.shims and options.imports. options: { args, entry,
1796
+ * callArgs, env, imports, shims, stdin, heapBase, io } — args
1797
+ * defaults to [path]; io is a text IO partial (default: this
1798
+ * instance's IO). Returns the exit code for a _start module, or
1799
+ * the named entry's return value. */
1800
+ runWasmFile(path, options = {}) {
1801
+ const p = normalizeVfsPath(path);
1802
+ const bytes = this.exportFile(p);
1803
+ const io = normalizeIO(options.io, this._io);
1804
+ const result = runWasmModuleSync(bytes, {
1805
+ args: options.args ?? [p],
1806
+ entry: options.entry,
1807
+ callArgs: options.callArgs,
1808
+ env: options.env,
1809
+ shims: options.shims,
1810
+ imports: options.imports,
1811
+ stdin: options.stdin,
1812
+ heapBase: options.heapBase,
1813
+ _instanceShims: this._shims,
1814
+ io: textIOToByteIO(io),
1815
+ });
1816
+ flushIO(io);
1817
+ if (typeof result === 'number') return result;
1818
+ return result?.exitCode ?? 0;
1819
+ }
1820
+
1821
+ /** Command-line mode: assemble argv exactly like a shell would
1822
+ * (argv[0] filled with the virtual binary path) and call the
1823
+ * exported main / tinyc_main. When the OPFS backend is mounted,
1824
+ * path arguments are relocated under "/opfs" first (see
1825
+ * _moduleArgv). Returns the exit code. main is not
1826
+ * reentrant; a nested call (e.g. from an IO callback) throws.
1827
+ * A "-run" argument on a non-wasm32 target is rejected by the
1828
+ * glue layer with TinycRunNotSupportedError before the native
1829
+ * module is called: that target can only compile to a file here.
1830
+ * On the wasm32 target, "-run" is handled by the glue layer
1831
+ * itself (see _callMainRun): the exported main never sees it.
1832
+ * For "-run", the optional second argument forwards run options
1833
+ * ({ shims, imports, stdin, heapBase }) to that execution. */
1834
+ callMain(args = [], options = {}) {
1835
+ if (!Array.isArray(args)) throw new TinycError('tinyc: callMain expects an array of arguments');
1836
+ if (args.some((a) => a === '-run')) {
1837
+ if (!this.canRun) throw new TinycRunNotSupportedError(this.target);
1838
+ return this._callMainRun(args.map(String), options);
1839
+ }
1840
+ if (this._mainRunning) {
1841
+ throw new TinycError('tinyc: exported main is not reentrant (callMain already running)');
1842
+ }
1843
+ const argv = this._moduleArgv(args.map(String));
1844
+ this._mainRunning = true;
1845
+ try {
1846
+ const rc = this._bridge.callMain(argv);
1847
+ flushIO(this._io);
1848
+ return rc;
1849
+ } finally {
1850
+ this._mainRunning = false;
1851
+ }
1852
+ }
1853
+
1854
+ /** Assemble the argv handed to the exported main. argv[0] is the
1855
+ * virtual binary path. When the module FS has no prefix (memory
1856
+ * backend) the arguments pass through exactly as given. When the
1857
+ * OPFS backend is mounted (bridge.moduleFsPrefix set), every
1858
+ * argument that names a file inside the module FS — argv[0], the
1859
+ * values of path options in separate and joined form, --sysroot=
1860
+ * values, and bare input-file arguments — is relocated under the
1861
+ * prefix (bridge.modulePath), where the mirrored files actually
1862
+ * live; all other arguments pass through untouched. */
1863
+ _moduleArgv(args) {
1864
+ const bridge = this._bridge;
1865
+ if (!bridge.moduleFsPrefix) return [VIRTUAL_BIN_PATH, ...args];
1866
+ const out = [bridge.modulePath(VIRTUAL_BIN_PATH)];
1867
+ let pathValueNext = false;
1868
+ for (const arg of args) {
1869
+ if (pathValueNext) {
1870
+ pathValueNext = false;
1871
+ out.push(arg.startsWith('-') ? arg : bridge.modulePath(arg));
1872
+ continue;
1873
+ }
1874
+ if (PATH_VALUE_OPTIONS.has(arg)) {
1875
+ pathValueNext = true;
1876
+ out.push(arg);
1877
+ continue;
1878
+ }
1879
+ if (arg.startsWith('--sysroot=')) {
1880
+ out.push('--sysroot=' + bridge.modulePath(arg.slice('--sysroot='.length)));
1881
+ continue;
1882
+ }
1883
+ const joined = PATH_JOINED_OPTIONS.find(
1884
+ (opt) => arg.length > opt.length && arg.startsWith(opt)
1885
+ );
1886
+ if (joined) {
1887
+ out.push(joined + bridge.modulePath(arg.slice(joined.length)));
1888
+ continue;
1889
+ }
1890
+ // A bare argument in compiler mode is an input file.
1891
+ if (!arg.startsWith('-') && arg.length > 0) {
1892
+ out.push(bridge.modulePath(arg));
1893
+ continue;
1894
+ }
1895
+ out.push(arg);
1896
+ }
1897
+ return out;
1898
+ }
1899
+
1900
+ /** wasm32 "-run": the arguments before "-run" are compiler
1901
+ * options, the one after it is the source file, and the rest are
1902
+ * the program's arguments. The source is compiled to
1903
+ * DEFAULT_RUN_OUTPUT through the exported main (without "-run"),
1904
+ * then the product bytes are instantiated and executed in the
1905
+ * host by runWasmModuleSync, with the program arguments fed to
1906
+ * _start through the WASI args shim. The instance's registered
1907
+ * shims apply; options.shims / options.imports / options.stdin /
1908
+ * options.heapBase forward per-run. Returns the compiler's exit
1909
+ * code when compilation fails, otherwise the program's. */
1910
+ _callMainRun(args, options = {}) {
1911
+ const runIdx = args.indexOf('-run');
1912
+ const compileArgs = args.slice(0, runIdx);
1913
+ const [src, ...progArgs] = args.slice(runIdx + 1);
1914
+ if (!src) {
1915
+ throw new TinycError('tinyc: callMain: "-run" must be followed by a source file');
1916
+ }
1917
+ const rc = this.callMain([...compileArgs, '-o', DEFAULT_RUN_OUTPUT, src]);
1918
+ if (rc !== 0) return rc;
1919
+ const bytes = this.exportFile(DEFAULT_RUN_OUTPUT);
1920
+ const result = runWasmModuleSync(bytes, {
1921
+ args: [src, ...progArgs],
1922
+ shims: options.shims,
1923
+ imports: options.imports,
1924
+ stdin: options.stdin,
1925
+ heapBase: options.heapBase,
1926
+ _instanceShims: this._shims,
1927
+ io: textIOToByteIO(this._io),
1928
+ });
1929
+ flushIO(this._io);
1930
+ if (typeof result === 'number') return result;
1931
+ return result?.exitCode ?? 0;
1932
+ }
1933
+
1934
+ /** Fine-grained mode: create a TCCState, pre-loaded with the
1935
+ * virtual FS include directories (registration order, ahead of
1936
+ * the sysroot) and the instance error routing. */
1937
+ createState() {
1938
+ this._bridge.requireExport('tcc_new');
1939
+ const handle = this._bridge.call('tcc_new', 'number', [], []);
1940
+ if (!handle && this._bridge.mode !== 'mock') {
1941
+ throw new TinycError('tinyc: tcc_new returned null');
1942
+ }
1943
+ const state = new TinycState(this, handle ?? {});
1944
+ this._states.add(state);
1945
+ state._installErrorFunc();
1946
+ if (this._bridge.has('tcc_add_include_path')) {
1947
+ for (const dir of this.fs.getIncludeDirs()) state.addIncludePath(dir);
1948
+ }
1949
+ return state;
1950
+ }
1951
+
1952
+ _forgetState(state) {
1953
+ this._states.delete(state);
1954
+ }
1955
+
1956
+ /** Convenience: compile one source string in a throwaway state. */
1957
+ compileString(source, { outputType = TCC_OUTPUT.MEMORY } = {}) {
1958
+ const state = this.createState();
1959
+ try {
1960
+ state.setOutputType(outputType);
1961
+ return state.compileString(source);
1962
+ } finally {
1963
+ state.delete();
1964
+ }
1965
+ }
1966
+ }
1967
+
1968
+ // ---------------------------------------------------------------------
1969
+ // Loading
1970
+ // ---------------------------------------------------------------------
1971
+
1972
+ // Per-target native module cache. Only modules obtained through
1973
+ // loadModule or the shipped glue files are cached: a target's module
1974
+ // is loaded at most once, and only when an instance of that target
1975
+ // is actually requested. Injected modules (module / createModule /
1976
+ // wasmExports) are used as-is per call and never enter the cache, so
1977
+ // callers can inject a different module for the same target.
1978
+ const targetModuleCache = new Map();
1979
+
1980
+ /** Targets whose native module has been loaded through the
1981
+ * per-target loader (loadModule or the shipped glue files). */
1982
+ export function getLoadedTargets() {
1983
+ return [...targetModuleCache.keys()];
1984
+ }
1985
+
1986
+ export function clearTargetModuleCache() {
1987
+ targetModuleCache.clear();
1988
+ }
1989
+
1990
+ async function createModuleFromGlue(glueUrl, wasmUrl, io) {
1991
+ let factory;
1992
+ try {
1993
+ factory = (await import(/* @vite-ignore */ glueUrl)).default;
1994
+ } catch {
1995
+ throw new TinycError(
1996
+ `tinyc: the Emscripten glue ${glueUrl} could not be loaded. ` +
1997
+ `Build it with build.sh, or pass module / createModule / wasmExports / loadModule.`
1998
+ );
1999
+ }
2000
+ if (typeof factory !== 'function') {
2001
+ throw new TinycError(`tinyc: Emscripten glue ${glueUrl} does not default-export a module factory`);
2002
+ }
2003
+ return factory({
2004
+ print: (text) => io.out(text + '\n'),
2005
+ printErr: (text) => io.err(text + '\n'),
2006
+ locateFile: (path, prefix) =>
2007
+ wasmUrl && path.endsWith('.wasm') ? wasmUrl : prefix + path,
2008
+ });
2009
+ }
2010
+
2011
+ async function loadTargetModule(target, options, io) {
2012
+ const cached = targetModuleCache.get(target);
2013
+ if (cached) return cached;
2014
+ const files = targetModuleFiles(target);
2015
+ const promise = (async () => {
2016
+ if (typeof options.loadModule === 'function') {
2017
+ return options.loadModule(target, {
2018
+ ...files,
2019
+ wasmUrl: options.wasmUrl ?? assetUrl(files.wasmFile, options.baseUrl),
2020
+ glueUrl: options.glueUrl ?? assetUrl(files.glueFile, options.baseUrl),
2021
+ });
2022
+ }
2023
+ const glueUrl = options.glueUrl ?? assetUrl(files.glueFile, options.baseUrl);
2024
+ const wasmUrl = options.wasmUrl ?? assetUrl(files.wasmFile, options.baseUrl);
2025
+ return createModuleFromGlue(glueUrl, wasmUrl, io);
2026
+ })();
2027
+ targetModuleCache.set(target, promise);
2028
+ promise.catch(() => {
2029
+ if (targetModuleCache.get(target) === promise) targetModuleCache.delete(target);
2030
+ });
2031
+ return promise;
2032
+ }
2033
+
2034
+ async function resolveNative(options, io, target) {
2035
+ if (options.module) return options.module;
2036
+ if (options.wasmExports) return options.wasmExports;
2037
+ if (typeof options.createModule === 'function') {
2038
+ return await options.createModule({
2039
+ print: (text) => io.out(text + '\n'),
2040
+ printErr: (text) => io.err(text + '\n'),
2041
+ locateFile: (path, prefix) =>
2042
+ options.wasmUrl && path.endsWith('.wasm') ? options.wasmUrl : prefix + path,
2043
+ });
2044
+ }
2045
+ // Default: the per-target module file (options.loadModule when
2046
+ // given, otherwise the shipped glue tcc-<target>.mjs), cached and
2047
+ // loaded lazily by loadTargetModule.
2048
+ return loadTargetModule(target, options, io);
2049
+ }
2050
+
2051
+ /** The sysroot manifest for one target (sysroot-manifests/<target>.json).
2052
+ * All manifests are statically imported with this module (see
2053
+ * SYSROOT_MANIFESTS above), so this never fetches at runtime; the
2054
+ * default target's manifest is also exported as `sysrootManifest`. */
2055
+ export async function loadSysrootManifest(target = DEFAULT_TARGET) {
2056
+ assertKnownTarget(target);
2057
+ return SYSROOT_MANIFESTS[target];
2058
+ }
2059
+
2060
+ async function loadSysroot(instance, sysrootOpt) {
2061
+ if (!sysrootOpt) return;
2062
+ let manifest;
2063
+ let baseUrl = './sysroot/';
2064
+ let fetchImpl;
2065
+ let includeBinaries = false;
2066
+ if (sysrootOpt === true) {
2067
+ manifest = await loadSysrootManifest(instance.target);
2068
+ } else if (Array.isArray(sysrootOpt.includeFiles)) {
2069
+ manifest = sysrootOpt; // a bare manifest object
2070
+ } else {
2071
+ manifest = sysrootOpt.manifest ?? (await loadSysrootManifest(instance.target));
2072
+ baseUrl = sysrootOpt.baseUrl ?? baseUrl;
2073
+ fetchImpl = sysrootOpt.fetchImpl;
2074
+ includeBinaries = Boolean(sysrootOpt.includeBinaries);
2075
+ }
2076
+ const baseHref = /^[a-z][a-z0-9+.-]*:/i.test(baseUrl)
2077
+ ? baseUrl
2078
+ : assetUrl(baseUrl);
2079
+ const entries = [...(manifest.includeFiles ?? []), ...(manifest.libFiles ?? [])];
2080
+ for (const entry of entries) {
2081
+ if (entry.binary && !includeBinaries) continue;
2082
+ // Already in the virtual FS — persisted by an earlier load of
2083
+ // this target and restored from the store — is not fetched again.
2084
+ if (instance.fs.hasFile(entry.path)) continue;
2085
+ const url = entry.url ?? new URL(entry.source, baseHref).href;
2086
+ await instance.fs.addFileFromUrl(entry.path, url, { fetchImpl });
2087
+ }
2088
+ if (manifest.includeDir) instance.fs.registerIncludeDir(manifest.includeDir);
2089
+ }
2090
+
2091
+ // ---------------------------------------------------------------------
2092
+ // WasmFS OPFS mount
2093
+ //
2094
+ // The native module is built with -sWASMFS=1 (see build.sh): its
2095
+ // filesystem root is the WasmFS memory backend. Before the virtual
2096
+ // FS is mirrored in, loadTinyc tries to mount the WasmFS OPFS
2097
+ // backend — the browser's on-disk origin private file system — at
2098
+ // OPFS_MOUNT_POINT, through the C API the build exports for this
2099
+ // (wasmfs_create_opfs_backend / wasmfs_create_directory from
2100
+ // <emscripten/wasmfs.h>, called with ccall's async form: in builds
2101
+ // without pthreads the backend's operations are asynchronous JS
2102
+ // that suspends the call, in pthread builds they complete through
2103
+ // the backend's proxy worker, and the async form covers both).
2104
+ //
2105
+ // The attempt runs only inside a Web Worker: creating the OPFS
2106
+ // backend on the browser main thread can deadlock waiting for its
2107
+ // dedicated worker thread to be spawned, and OPFS synchronous
2108
+ // access handles exist only in workers. Every failure — not a
2109
+ // worker, no OPFS in the browser, a module built without the
2110
+ // exports, a rejected mount — is silent and leaves the memory
2111
+ // backend in place; loadTinyc succeeds either way. The outcome is
2112
+ // memoized per native module (repeat loads of a cached module do
2113
+ // not mount twice) and reported as instance.fsBackend.
2114
+ // ---------------------------------------------------------------------
2115
+
2116
+ const OPFS_MOUNT_POINT = '/opfs';
2117
+ const opfsBackendByModule = new WeakMap();
2118
+
2119
+ async function tryMountOpfsBackend(native, bridge) {
2120
+ const canMemo =
2121
+ native !== null &&
2122
+ (typeof native === 'object' || typeof native === 'function');
2123
+ if (canMemo) {
2124
+ const memo = opfsBackendByModule.get(native);
2125
+ if (memo) return memo;
2126
+ }
2127
+ let result = 'memory';
2128
+ try {
2129
+ if (
2130
+ bridge.mode === 'emscripten' &&
2131
+ typeof native.ccall === 'function' &&
2132
+ typeof native._wasmfs_create_opfs_backend === 'function' &&
2133
+ typeof native._wasmfs_create_directory === 'function' &&
2134
+ typeof WorkerGlobalScope !== 'undefined' &&
2135
+ typeof self !== 'undefined' &&
2136
+ self instanceof WorkerGlobalScope
2137
+ ) {
2138
+ const backend = await native.ccall(
2139
+ 'wasmfs_create_opfs_backend', 'number', [], [], { async: true }
2140
+ );
2141
+ if (backend) {
2142
+ const rc = await native.ccall(
2143
+ 'wasmfs_create_directory', 'number',
2144
+ ['string', 'number', 'number'],
2145
+ [OPFS_MOUNT_POINT, 0o777, backend],
2146
+ { async: true }
2147
+ );
2148
+ // wasmfs_create_directory returns 0 on success and a
2149
+ // negative errno on failure, like mkdir.
2150
+ if (rc === 0) result = 'opfs';
2151
+ }
2152
+ }
2153
+ } catch {
2154
+ result = 'memory';
2155
+ }
2156
+ if (canMemo) opfsBackendByModule.set(native, result);
2157
+ return result;
2158
+ }
2159
+
2160
+ /** Load the TinyC WASM module for one target and return a ready
2161
+ * instance. Instances of different targets coexist; each has its
2162
+ * own virtual FS and per-target sysroot.
2163
+ *
2164
+ * options:
2165
+ * target one of SUPPORTED_TARGETS; default "wasm32-wasi".
2166
+ * Only the wasm32 target can run compiled output in
2167
+ * the browser; every other target compiles to files.
2168
+ * wasmUrl URL of this target's tcc-<target>.wasm (the glue
2169
+ * tcc-<target>.mjs is loaded alongside), or inject a
2170
+ * module with module / createModule / wasmExports /
2171
+ * loadModule instead
2172
+ * baseUrl directory URL the per-target glue/wasm files
2173
+ * resolve against; default is the directory of
2174
+ * index.mjs (module build) or of tinyc-web.js
2175
+ * (script bundle). wasmUrl / glueUrl override
2176
+ * individual files
2177
+ * sysroot true for this target's bundled manifest, or
2178
+ * { manifest, baseUrl, fetchImpl, includeBinaries }
2179
+ * fsStore a custom FsStore instance for the virtual FS
2180
+ * (see vfs-store.mjs); storeFactory is the function
2181
+ * form, called with the target. Default: one
2182
+ * IndexedDB database per target
2183
+ * ("tinyc-web-fs-<target>"), or the in-memory
2184
+ * backend where IndexedDB does not exist. The store
2185
+ * is opened and its persisted index loaded before
2186
+ * this resolves, so files from an earlier session
2187
+ * of the same target are already in the index (and
2188
+ * sysroot files among them are not fetched again).
2189
+ * io { out, err, in } JS functions; default console
2190
+ */
2191
+ export async function loadTinyc(options = {}) {
2192
+ const target = options.target ?? DEFAULT_TARGET;
2193
+ assertKnownTarget(target);
2194
+ const io = normalizeIO(options.io);
2195
+ const store = await openFsStore(target, options);
2196
+ const fs = new VirtualFS(store);
2197
+ const native = await resolveNative(options, io, target);
2198
+ const bridge = new NativeBridge(native, io);
2199
+ const instance = new Tinyc(bridge, { fs, io, target });
2200
+
2201
+ // === Emscripten FS adaptation point ===
2202
+ // First try to mount the WasmFS OPFS backend at /opfs (fail-soft;
2203
+ // the outcome lands on instance.fsBackend). The bridge's
2204
+ // moduleFsPrefix records where native-side paths are rooted —
2205
+ // "/opfs" on success, "" (the memory-backed root) otherwise —
2206
+ // and is handed to the mirror so files land where the paths
2207
+ // handed to the native module point. Then, if the module carries
2208
+ // an FS, mirror the virtual FS into it and keep it in sync on
2209
+ // later writes (see VirtualFS.mountTo).
2210
+ instance._fsBackend = await tryMountOpfsBackend(native, bridge);
2211
+ bridge.moduleFsPrefix =
2212
+ instance._fsBackend === 'opfs' ? OPFS_MOUNT_POINT : '';
2213
+ if (native && native.FS) await fs.mountTo(native.FS, bridge.moduleFsPrefix);
2214
+
2215
+ await loadSysroot(instance, options.sysroot);
2216
+ return instance;
2217
+ }
2218
+
2219
+ export default loadTinyc;