tinyc-web 0.0.0-stage → 0.1.1

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.
Files changed (35) hide show
  1. package/README.md +258 -2
  2. package/README.zh-CN.md +259 -0
  3. package/index.mjs +2219 -0
  4. package/package.json +1 -6
  5. package/sysroot-manifest.json +67 -0
  6. package/sysroot-manifests/aarch64-linux-android.json +82 -0
  7. package/sysroot-manifests/aarch64-linux-gnu.json +79 -0
  8. package/sysroot-manifests/arm64-apple-darwin.json +80 -0
  9. package/sysroot-manifests/riscv64-linux-gnu.json +79 -0
  10. package/sysroot-manifests/wasm32-wasi.json +67 -0
  11. package/sysroot-manifests/x86_64-apple-darwin.json +80 -0
  12. package/sysroot-manifests/x86_64-linux-android.json +82 -0
  13. package/sysroot-manifests/x86_64-linux-gnu.json +79 -0
  14. package/sysroot-manifests/x86_64-windows.json +79 -0
  15. package/tcc-aarch64-linux-android.mjs +16 -0
  16. package/tcc-aarch64-linux-android.wasm +0 -0
  17. package/tcc-aarch64-linux-gnu.mjs +16 -0
  18. package/tcc-aarch64-linux-gnu.wasm +0 -0
  19. package/tcc-arm64-apple-darwin.mjs +16 -0
  20. package/tcc-arm64-apple-darwin.wasm +0 -0
  21. package/tcc-riscv64-linux-gnu.mjs +16 -0
  22. package/tcc-riscv64-linux-gnu.wasm +0 -0
  23. package/tcc-wasm32-wasi.mjs +16 -0
  24. package/tcc-wasm32-wasi.wasm +0 -0
  25. package/tcc-x86_64-apple-darwin.mjs +16 -0
  26. package/tcc-x86_64-apple-darwin.wasm +0 -0
  27. package/tcc-x86_64-linux-android.mjs +16 -0
  28. package/tcc-x86_64-linux-android.wasm +0 -0
  29. package/tcc-x86_64-linux-gnu.mjs +16 -0
  30. package/tcc-x86_64-linux-gnu.wasm +0 -0
  31. package/tcc-x86_64-windows.mjs +16 -0
  32. package/tcc-x86_64-windows.wasm +0 -0
  33. package/tinyc-web.js +3501 -0
  34. package/vfs-store.mjs +180 -0
  35. package/worker.mjs +260 -0
package/README.md CHANGED
@@ -1,3 +1,259 @@
1
- # Temporary Holding Version
1
+ # tinyc-web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** | [简体中文](README.zh-CN.md)
4
+
5
+ TinyC (TCC) for the browser: the compiler built to WebAssembly, with a JavaScript glue layer, a virtual filesystem, and a Web Worker interface.
6
+
7
+ ## Build prerequisite
8
+
9
+ Producing the WASM modules requires an activated Emscripten SDK (`emcc` on `PATH`). `./build.sh` checks for `emcc` and stops with an error if it is missing; it installs nothing.
10
+
11
+ A TCC build has exactly one code generation target, so the package carries one WASM module per target, built by one `build.sh` run per target:
12
+
13
+ ```
14
+ TARGET=x86_64-linux-gnu ./build.sh # emits tcc-x86_64-linux-gnu.mjs + tcc-x86_64-linux-gnu.wasm
15
+ TARGET=aarch64-linux-gnu ./build.sh # emits tcc-aarch64-linux-gnu.mjs + tcc-aarch64-linux-gnu.wasm
16
+ ```
17
+
18
+ Each module exports the libtcc `tcc_*` API plus a main entry (`tinyc_main` where the kernel provides it, otherwise `main`; the glue prefers `tinyc_main` and falls back to `main`). The eight general targets compile the upstream TCC tree. The `wasm32-wasi` module is built from the project's own WebAssembly code generation backend (the `wasm-backend/` tree at the repository root): that branch of `build.sh` assembles the upstream tree with the backend's `wasm-gen.c` / `wasm-link.c` sources and its patches, then compiles it with emcc like every other target.
19
+
20
+ The glue layer (`index.mjs`, `worker.mjs`) is complete without the WASM build: `loadTinyc` also accepts an injected module (`module`, `createModule`, `wasmExports`, or an async `loadModule(target, files)` loader), which is how the test suite runs it.
21
+
22
+ ## Targets
23
+
24
+ ```js
25
+ import { loadTinyc } from 'tinyc-web';
26
+
27
+ const tinyc = await loadTinyc({ target: 'x86_64-linux-gnu', sysroot: true });
28
+ ```
29
+
30
+ Supported targets — the same set as the native target matrix, plus `wasm32-wasi`, the browser's own host format. There are no browser-only targets and no native-only targets:
31
+
32
+ | target | output | run in browser |
33
+ |---|---|---|
34
+ | `wasm32-wasi` (default) | WebAssembly (WASI) | yes |
35
+ | `x86_64-linux-gnu` | Linux x86-64 ELF | no |
36
+ | `aarch64-linux-gnu` | Linux AArch64 ELF | no |
37
+ | `riscv64-linux-gnu` | Linux RISC-V 64 ELF | no |
38
+ | `x86_64-windows` | Windows x86-64 PE | no |
39
+ | `aarch64-linux-android` | Android AArch64 ELF (bionic) | no |
40
+ | `x86_64-linux-android` | Android x86-64 ELF (bionic) | no |
41
+ | `arm64-apple-darwin` | macOS arm64 Mach-O | no |
42
+ | `x86_64-apple-darwin` | macOS x86-64 Mach-O | no |
43
+
44
+ The target's module (`tcc-<target>.wasm` / `tcc-<target>.mjs`) is loaded lazily — only the requested target's module is fetched, and at most once per page. Instances of different targets coexist; each instance has its own virtual filesystem and its own sysroot manifest (`sysroot-manifests/<target>.json`; the top-level `sysroot-manifest.json` is the default target's manifest). An unknown target is rejected with the supported list.
45
+
46
+ `sysroot: true` loads the target's bundled header set (TCC's own headers: `float.h`, `stdarg.h`, `stddef.h`, `stdbool.h`, `tcclib.h`, and the rest of that target's manifest) into the virtual filesystem under `/sysroot/include` and registers it as an include directory. A custom manifest can be passed as `{ manifest, baseUrl }`.
47
+
48
+ Target-specific manifest facts:
49
+
50
+ - The Android manifests describe the bionic sysroot layout of the native Android builds: `libc: "bionic"`, `androidApi: 30`, and `dynamicLinker: "/system/bin/linker64"` (the interpreter of 64-bit Android ELF products).
51
+ - The Darwin manifests contain TCC's own headers only. macOS system SDK headers are license-restricted and are not distributed with the package; the manifest marks this as `systemHeaders: "user-sdk"`, and system headers are supplied by adding them to the virtual filesystem and registering their directory (see *Virtual filesystem and adding files*). Darwin targets compile to files only; a Mach-O product needs a code signature to run on Apple Silicon — at least an ad-hoc signature — wherever it was compiled.
52
+
53
+ ## Output formats
54
+
55
+ The output file formats a target can produce are the same in every package and on every platform. Each target's manifest carries them in its `outputs` field; the full table:
56
+
57
+ | family (targets) | exe | obj | shared | ar |
58
+ |---|---|---|---|---|
59
+ | ELF (`*-linux-gnu`, `*-linux-android`) | ELF executable, no extension | ELF relocatable `.o` | ELF shared object `.so` | ar archive `.a` |
60
+ | PE (`x86_64-windows`) | PE executable `.exe` | COFF object `.o` | PE DLL `.dll` | ar archive `.a` |
61
+ | Mach-O (`*-apple-darwin`) | Mach-O executable, no extension | Mach-O object `.o` | Mach-O dylib `.dylib` | ar archive `.a` |
62
+ | WebAssembly (`wasm32-wasi`) | — | — | — | module: WebAssembly `.wasm` |
63
+
64
+ ## Running: wasm32 only
65
+
66
+ Compiling to a file works for every target. Running does not: the compiler's host platform in a browser is WebAssembly itself, so only the `wasm32-wasi` target's output can run here — the produced module is instantiated and executed by the browser.
67
+
68
+ For every other target, the glue layer rejects run requests up front with `TinycRunNotSupportedError`, before anything reaches the native module:
69
+
70
+ - `tinyc.callMain(['-run', ...])` throws;
71
+ - `state.run(...)` throws.
72
+
73
+ `instance.canRun` reports whether the instance's target can run.
74
+
75
+ ### How a wasm32 run works
76
+
77
+ A WebAssembly module cannot instantiate another WebAssembly module from inside itself — instantiation is a host capability. So running never goes through the compiler module: the glue layer takes the compiled product's bytes and instantiates them itself with the WebAssembly API:
78
+
79
+ - `state.run(args, options)` writes the product to a file in the virtual filesystem (`options.outputPath`, default `/a.out`), reads the bytes back and runs them; the WASI argv is `[outputPath, ...args]`.
80
+ - `tinyc.callMain(['-run', src, ...progArgs])` first compiles `src` to `/a.out` through the exported main (the native main never sees `-run`), then runs the product with WASI argv `[src, ...progArgs]`.
81
+ - `runWasmModule(bytes, options)` / `runWasmModuleSync(bytes, options)` run product bytes directly (async `WebAssembly.compile` variant, and a synchronous `WebAssembly.Module`/`Instance` variant used inside workers and by the two paths above).
82
+ - `tinyc.runWasmFile(path, options)` runs a product already stored in the virtual FS — compiled to a file earlier, or placed there with `addFile` — without recompiling; it reads the bytes with `exportFile` and runs them through the same runner and shim stack, with the instance's registered shims applied.
83
+
84
+ Entry conventions: with no `options.entry`, an exported `_start` is called (command style) and the result is `{ exitCode }`; with `options.entry`, that export is called with `options.callArgs` (default `options.args`) and its return value is returned as-is (function style). `state.run` returns the exit code, or the entry's return value.
85
+
86
+ The instance gets a minimal WASI shim (`wasi_snapshot_preview1`): `fd_write`, `fd_read`, `fd_close`, `fd_seek` (the stdio descriptors are not seekable: `ESPIPE`), `fd_fdstat_get`, `args_get`, `args_sizes_get`, `environ_get`, `environ_sizes_get`, `clock_time_get`, `random_get`, `sched_yield`, and `proc_exit`. `fd_write` output on fd 1/2 is routed to the run's IO as `Uint8Array` chunks. `proc_exit` never terminates the host: the shim throws, the runner catches it, and the code becomes the run's exit code.
87
+
88
+ Passing data into a module instance: `writeModuleData(instance, data, options)` writes a string/`Uint8Array` into the instance's exported memory — through the module's exported `malloc` when it has one (the result carries a `free()`), otherwise at `options.offset` (a number, or `(byteLength) => address`). `readModuleData` / `readModuleCString` read back.
89
+
90
+ ## Runtime shims: the default libc
91
+
92
+ A C program compiled to wasm32 imports the libc functions it uses, and there is no libc archive to link in this package. Every run therefore also gets the default shim library (`runtime-shims.mjs`) as imports under the module name `env`, implemented in JS against the instance's linear memory:
93
+
94
+ - memory/string: `memcpy`, `memmove`, `memset`, `memcmp`, `strlen`, `strcpy`, `strncpy`, `strcat`, `strncat`, `strcmp`, `strncmp`, `strchr`, `strrchr`, `strstr`, `strdup`
95
+ - allocation: `malloc`, `calloc`, `realloc`, `free`
96
+ - stdio: `printf`, `fprintf`, `vprintf`, `vfprintf`, `sprintf`, `vsprintf`, `snprintf`, `vsnprintf`, `puts`, `putchar`, `fputs`, `putc`, `fputc`, `fwrite`, `fread`, `fgetc`, `getchar`, `ungetc`
97
+ - stdlib: `exit`, `abort`, `atexit`, `atoi`, `atol`, `atoll`, `atof`, `strtol`, `strtoul`, `strtoll`, `strtoull`, `strtod`, `strtof`, `abs`, `labs`, `llabs`, `rand`, `srand`, `getenv` (returns NULL), `system` (returns -1)
98
+ - ctype: `isalpha`, `isdigit`, `isspace`, `isalnum`, `isupper`, `islower`, `ispunct`, `iscntrl`, `isxdigit`, `isblank`, `isprint`, `isgraph`, `tolower`, `toupper`
99
+ - math: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `log`, `log10`, `pow`, `sqrt`, `floor`, `ceil`, `fabs`, `round`, `trunc`, `fmod` (the JS `Math` functions)
100
+ - time: `time` (seconds from `Date.now()`), `clock`, `difftime`
101
+
102
+ Details that matter:
103
+
104
+ - **Timing.** Import functions are created before the instance exists, so they never capture the memory: they read it through a holder on every call. The glue fills the holder right after instantiation, before any entry point runs, so the memory is always in place when a shim is called.
105
+ - **Allocator.** `malloc` and friends are a first-fit free-list allocator (with block splitting) over the region starting at `heapBase` (default 65536, overridable per run); it grows the memory when it runs out. If the module exports its own `malloc`, the shim forwards allocation calls to the module's allocator instead and the internal one never touches the heap — exactly one allocator is ever in play.
106
+ - **stdio.** The printf family parses the format string in JS, reading it and the arguments from linear memory. Variadic arguments are read from the region the `va_list` points to, in order, each at its natural alignment: i32/pointers in 4-byte slots, i64/f64 in 8-byte slots aligned to 8. Supported: flags `- + space # 0`, width and precision (including `*`), length modifiers `hh h l ll z j t`, conversions `d i u x X o c s p f F e E g G a A n %`. Output is routed to the run's IO as bytes; a `FILE*` stream value of 2 goes to `err`, any other value to `out`. `fread`/`fgetc` read the run's stdin (`options.stdin`, then `io.in()` chunks).
107
+ - **exit.** `exit(code)` runs `atexit` handlers when the module exports its indirect function table (`__indirect_function_table`) — handlers are table indices and only callable through it — then unwinds as `{ exitCode: code }`, like `proc_exit`. `abort()` unwinds with exit code 134.
108
+
109
+ ### libtcc1 helpers
110
+
111
+ TCC's runtime support library (`vendor-tinycc/lib/`) was checked symbol by symbol against what a wasm32 target can emit. Almost none of it needs JS shims, for the reasons below; the one exception is a family of `libtcc1.c` helpers that does surface as imports.
112
+
113
+ - `libtcc1.c` conversions — the float conversions `__floatundisf/df/xf`, `__fixunssfdi`, `__fixsfdi`, `__fixunsdfdi`, `__fixdfdi`, `__fixunsxfdi`, `__fixxfdi`: wasm32 has native float↔i64 conversion instructions (and long double is f64 on this target), so the code generator emits instructions — saturating `trunc_sat` for float→integer — not calls. This version's `lib/` tree contains no `__tcc_cvt_*` symbols; the conversion helpers are the `__fix*`/`__float*` family above.
114
+ - `libtcc1.c` division and shifts — `__divdi3`, `__moddi3`, `__udivdi3`, `__umoddi3` (long long division and modulo) and `__ashldi3`, `__ashrdi3`, `__lshrdi3` (long long shifts by a variable count): these the code generator does emit as calls, and they appear in the compiled module as `env` imports. The target ships no libtcc1 and the package provides no default shim for them, so a program using long long division, modulo, or a variable-count long long shift fails to instantiate with `TinycMissingImportError` naming the helper; registering a JS implementation under that name as a custom shim (below) is the fix. Constant-count long long shifts are inlined by the code generator and need no helper.
115
+ - `builtin.c` — the `__tcc_builtin_*` family (`ffs`, `clz`, `ctz`, `popcount`, `parity`, …): wasm has native `clz`/`ctz`/`popcnt` instructions; code generation handles them.
116
+ - `va_list.c` — `__va_arg`: on the wasm target a va_list is a pointer into a memory argument area and `va_arg` is pointer advancement done by the code generator.
117
+ - `alloca.S` — `alloca`/`__alloca`: wasm alloca adjusts the stack-pointer global in generated code.
118
+ - `stdatomic.c` / `atomic.S` — the `__atomic_*` family: the C source is compiled by the wasm backend like any other C file when a program uses `<stdatomic.h>`; in single-threaded wasm the operations reduce to plain loads and stores. No host imports are involved.
119
+ - `bcheck.c` — the `__bound_*` family: emitted only in `-b` bounds-checking mode, and the implementation depends on mmap, signals and pthreads. Not provided.
120
+ - `runmain.c` — `_runmain`, `__run_on_exit`, `on_exit`, `atexit`, `exit`: the native `-run` support file. In the browser path the glue invokes `_start` directly, and `exit`/`atexit` semantics come from the libc shims above.
121
+ - `armeabi.c` (`__aeabi_*`), `lib-arm64.c`, `tcov.c`: ARM-target helpers and the coverage runtime; not applicable to wasm.
122
+
123
+ ## Custom shims
124
+
125
+ Programs that import symbols outside the WASI shim and the default libc — a host API, a peripheral, anything — get them from JS functions registered as shims. A shim is called as `fn(ctx, ...cArgs)`:
126
+
127
+ - `ctx.memory()` / `ctx.u8()` — the instance's linear memory and a `Uint8Array` view of it;
128
+ - `ctx.readCString(ptr)`, `ctx.writeCString(ptr, str)` (writes the UTF-8 bytes plus a NUL terminator, returns the byte count including the NUL), `ctx.readBytes(ptr, len)`, `ctx.writeBytes(ptr, bytes)` — memory helpers;
129
+ - `ctx.io` — the run's byte IO (`out`/`err` taking `Uint8Array`, optional `in()`).
130
+
131
+ C arguments arrive in their wasm types: i32/f32/f64 as numbers, i64 as `BigInt`; the return value goes back the same way, so an i64 result must be returned as a `BigInt`. The JS function declares no signature — the engine coerces the arguments and the return value to the import type the module itself declares.
132
+
133
+ Registration exists at three levels. For the same import, the higher level wins; within one level, a later registration replaces an earlier one:
134
+
135
+ 1. **Per-run** — `runWasmModule(bytes, { shims: { name: fn } })`; `state.run(args, { shims })` and `callMain(['-run', ...], { shims })` forward it.
136
+ 2. **Instance** — `tinyc.registerShim(name, fn)`, `tinyc.registerShims({ ... })`, `tinyc.unregisterShim(name)`; applies to every later run through that instance.
137
+ 3. **Package-global** — `registerGlobalShim(name, fn)`, `registerGlobalShims({ ... })`, `unregisterGlobalShim(name)`; applies to every later instance and `runWasmModule` call.
138
+
139
+ Below all three sit the default libc shims and the WASI shim. Above all three sits `options.imports`, merged into the import object as-is (the raw escape hatch — it can also supply non-function imports such as a memory). A registration key is a bare name (module `env`) or `"module.name"` for any other import module — including `wasi_snapshot_preview1`, whose built-in entries can be overridden the same way.
140
+
141
+ **Missing imports.** Before instantiation, the runner lists the module's required imports (`WebAssembly.Module.imports`) and diffs them against the assembled import object. Anything missing throws `TinycMissingImportError` — with the full `module.name` list on `err.missing` and the registration routes in the message — instead of the engine's raw `LinkError`. Registering the named symbols is the fix.
142
+
143
+ ## Getting compiled products out
144
+
145
+ Compilation products are files in the virtual filesystem, for every target (object files, executables, libraries, Windows PE files):
146
+
147
+ ```js
148
+ const bytes = tinyc.exportFile('/out/prog.exe'); // Uint8Array
149
+ const blob = tinyc.exportBlob('/out/prog.exe'); // Blob, e.g. for a download link
150
+ ```
151
+
152
+ ## Usage
153
+
154
+ ### Script tag
155
+
156
+ The package also builds as a single classic-script file, `tinyc-web.js`, which defines the global `TinycWeb` with the same API as the module build; `TinycWeb.loadTinyc` is the entry point. From the npm package via a CDN:
157
+
158
+ ```html
159
+ <script src="https://cdn.jsdelivr.net/npm/tinyc-web@0.1.0/tinyc-web.js"></script>
160
+ <script>
161
+ (async () => {
162
+ const tinyc = await TinycWeb.loadTinyc();
163
+ tinyc.compileString('int answer() { return 42; }');
164
+ })();
165
+ </script>
166
+ ```
167
+
168
+ The per-target native files are not inside the bundle: for the requested target, the glue `tcc-<target>.mjs` is loaded with a dynamic `import()` and `tcc-<target>.wasm` is fetched, both resolved relative to the bundle file's own URL — with the CDN address above they come from the same `tinyc-web@0.1.0` package prefix automatically. When self-hosting, place `tcc-<target>.mjs` and `tcc-<target>.wasm` in the same directory as `tinyc-web.js`. `loadTinyc({ baseUrl })` resolves them against a different directory; `wasmUrl` / `glueUrl` override one file each. The sysroot manifests are inlined in the bundle, so no JSON files are fetched for them.
169
+
170
+ `tinyc-web.js` is regenerated from the module sources with:
171
+
172
+ ```
173
+ npm run build:web # node build-web-bundle.mjs (esbuild)
174
+ ```
175
+
176
+ ### Command-line mode
177
+
178
+ ```js
179
+ const exitCode = tinyc.callMain(['-o', '/out/a.o', '-c', '/src/main.c']);
180
+ ```
181
+
182
+ `callMain` fills `argv[0]` with the virtual binary path (`/sysroot/bin/tinyc`) and calls the exported `tinyc_main` (falling back to `main`). It returns the exit code. The exported main is not reentrant; a nested `callMain` throws.
183
+
184
+ ### Fine-grained API
185
+
186
+ ```js
187
+ const state = tinyc.createState();
188
+ state.setOutputType(1); // TCC_OUTPUT.MEMORY
189
+ state.addIncludePath('/deps/include');
190
+ state.compileString('int answer() { return 42; }');
191
+ state.delete();
192
+ ```
193
+
194
+ State methods mirror the libtcc functions they call (`tcc_compile_string`, `tcc_add_include_path`, `tcc_add_file`, …). A method whose export is missing from the native module throws `TinycMissingExportError` naming that export.
195
+
196
+ ### Virtual filesystem and adding files
197
+
198
+ There is no real filesystem for TCC to point at in a browser, so user files enter the virtual filesystem by content. This is the browser form of the "dynamically add local files" rule:
199
+
200
+ ```js
201
+ await tinyc.addFile('/src/main.c', 'int main() { return 0; }'); // string / Uint8Array / ArrayBuffer
202
+ await tinyc.addFile('/src/util.h', fileFromAnInputElement); // File or Blob
203
+ await tinyc.addFileFromUrl('/deps/sqlite3.h', 'https://example.com/sqlite3.h');
204
+ tinyc.registerIncludeDir('/deps'); // -> tcc_add_include_path on new states
205
+ ```
206
+
207
+ File contents are persisted in a store (`vfs-store.mjs`), not held in memory: one IndexedDB database per target — `tinyc-web-fs-<target>`, a single `files` table keyed by path — wherever IndexedDB exists (browsers and Web Workers), and an in-memory backend where it does not (Node, tests), or when an IndexedDB open fails. A custom store or store factory can be injected per load (`loadTinyc({ fsStore })` / `loadTinyc({ storeFactory })`). What the virtual FS itself keeps in memory is only the path index (path → size/mtime) plus an LRU content cache (at most 32 files and 16 MiB in total, `VFS_CACHE_MAX_ENTRIES` / `VFS_CACHE_MAX_BYTES`). `loadTinyc` opens the store and loads the index before resolving, so an instance starts with the files an earlier session of the same target left behind — sysroot files among them are recognized and not fetched again. When the native module is an Emscripten build, files are additionally mirrored into the module's `FS` (the compile working set has to live there while TCC runs); that mirroring is confined to `VirtualFS.mountTo`/`syncFile`, the Emscripten FS adaptation point.
208
+
209
+ The native module's filesystem is WasmFS (build.sh passes `-sWASMFS=1`; `-sFORCE_FILESYSTEM=1` is what includes the JS `FS` API the mirroring goes through), and its root backend is memory. Before mirroring, `loadTinyc` tries to mount the WasmFS OPFS backend — the browser's on-disk origin private file system — at `/opfs` inside the module filesystem, through the `wasmfs_create_opfs_backend` / `wasmfs_create_directory` functions the build exports. The attempt runs only inside a Web Worker: creating the OPFS backend on the browser main thread can deadlock, and OPFS synchronous access handles exist only in workers. Any failure — main thread, a browser without OPFS, a module built without the exports, a rejected mount — silently leaves the memory backend in place, and `tinyc.fsBackend` reports which happened: `'opfs'` or `'memory'`. With `'opfs'`, the mirrored compile working set is rooted at the mount point: a virtual-FS path `P` lives inside the module at `/opfs` + `P`, on disk, and every path handed to the native module is relocated to match — the mirror writes and unlinks, `tcc_add_file`, the include/library/lib path registrations, `tcc_output_file`, and the path arguments in `callMain` argv (argv[0], `-o` values, input files) — with compiled products read back from there into the virtual FS. The virtual FS's own paths never change; only the module-side location moves. With `'memory'`, the working set sits at the virtual-FS paths in the memory-backed root, exactly as the paths read.
210
+
211
+ The full file lifecycle is available on the instance (and on `tinyc.fs`): write with `addFile` / `addFileSync`, read with `readFile` (bytes) / `readTextFile` (string) — `exportFile` / `exportBlob` are the same read for compiled products — enumerate with `listFiles(prefix)`, and delete with `removeFile(path)` (index entry, persisted record and the mirrored copy inside the native module) or `clearFiles()` (everything except the mounted sysroot under `/sysroot/`).
212
+
213
+ Two timing rules follow from the store being asynchronous. `addFile` resolves once its content is persisted; `addFileSync` updates the index, cache and native mirror immediately but only queues the store write (the deletes from `removeFile` / `clearFiles` are queued the same way) — `await tinyc.whenIdle()` is the point where everything queued has landed. And synchronous reads are served from the content cache: anything written or read during the session is cached, but a file restored from the store that has not been touched yet is not — reading it with `readFile` / `exportFile` throws and names the async form, `readFileAsync` / `readTextFileAsync` / `exportFileAsync`, which reads it from the store and warms the cache.
214
+
215
+ `compileFile(path)` compiles a virtual-FS source through `tcc_compile_string` with a `#line` marker carrying the path; `state.addFile(path)` passes the path to `tcc_add_file` for sources, objects and archives.
216
+
217
+ ### IO
218
+
219
+ IO is plain JS functions — this package needs no trampoline layer:
220
+
221
+ ```js
222
+ const lines = [];
223
+ tinyc.setIO({
224
+ out: (text) => lines.push(text),
225
+ err: (text) => console.error(text),
226
+ in: () => null, // EOF
227
+ });
228
+ ```
229
+
230
+ Defaults: `out`/`err` are line-buffered writers onto `console.log`/`console.error`, `in` returns EOF. Per-state `state.setIO(...)` reroutes that state's error channel through `tcc_set_error_func`; native stdout routing is per-module and follows the instance IO.
231
+
232
+ ### Web Worker
233
+
234
+ ```js
235
+ import { TinycWorker } from 'tinyc-web/worker';
236
+
237
+ const worker = new TinycWorker({ target: 'x86_64-linux-gnu', sysroot: true });
238
+ await worker.compileString('int f() { return 1; }');
239
+ const exitCode = await worker.runCli(['-c', '/src/main.c', '-o', '/out/a.o']);
240
+ worker.terminate();
241
+ ```
242
+
243
+ `TinycWorker` spawns `worker.mjs` as a module worker and returns promises for `compileString`, `compileFile`, `addFile`, `registerIncludeDir` and `runCli`. The `target` option selects the per-target module inside the worker (default `wasm32-wasi`); the run guard applies there too, so `runCli(['-run', ...])` rejects for non-wasm32 targets. Native output inside the worker is forwarded to the main thread and dispatched to the `io` option.
244
+
245
+ Shim functions cannot be registered on a `TinycWorker` from the main thread — a JS function cannot cross `postMessage`, and `worker.registerShim(...)` / `worker.registerShims(...)` throw saying so. The worker-side route is the constructor's `shimModules` option: an array of module URLs. The worker imports each module and registers its default export — a shim map object (`{ name: fn }`) — on its instance:
246
+
247
+ ```js
248
+ const worker = new TinycWorker({ shimModules: ['./my-shims.mjs'] });
249
+ // my-shims.mjs: export default { host_log: (ctx, ptr) => { ... } };
250
+ ```
251
+
252
+ ## Tests
253
+
254
+ ```
255
+ npm test # node --test test.mjs
256
+ npm run test:web # node --test test-web-bundle.mjs
257
+ ```
258
+
259
+ The suite runs the glue logic in Node against an injected mock module implementing the `tcc_*` names: virtual FS intake from string, `Blob`/`File` and URL sources, include-dir registration reaching `tcc_add_include_path`, IO routing at the Emscripten wiring point and through the error callback, `callMain` argv assembly, the missing-export error, the target registry (two targets coexisting with isolated virtual filesystems, per-target lazy loading), the run guard on non-wasm32 targets and the wasm32 run path, product export, and the per-target sysroot manifests. The run paths are additionally tested with real hand-assembled wasm modules (byte arrays in `test.mjs`, each with its WAT described): a function-style `add` export, a `_start` module writing through the WASI `fd_write` shim and exiting via `proc_exit`, the WASI argv shim, the default libc shims (`printf` formatting into IO, `memcpy`, `malloc`/`free` heap reuse, `options.imports` overriding a default shim), and the custom-shim surface — the missing-import diagnostic with its exact list, instance-level registration with `ctx.readCString`, per-run override of an instance registration, `unregisterShim`, `callMain -run` shim forwarding, package-global registration, and the `TinycWorker.registerShim` boundary error. The second suite (`test-web-bundle.mjs`) rebuilds `tinyc-web.js`, loads it as a classic script in a Node `vm` context dressed up as a browser page (fake `document.currentScript` and `location`), and checks the `TinycWeb` global against the module build's export list, the script-scenario base-URL rules (script directory, page-directory fallback, `baseUrl`/`wasmUrl` overrides), the inlined per-target sysroot manifests, and the mock-module and hand-written-wasm run paths inside the bundle.
@@ -0,0 +1,259 @@
1
+ # tinyc-web
2
+
3
+ [English](README.md) | **简体中文**
4
+
5
+ 浏览器版 TinyC(TCC):编译器编成 WebAssembly,配 JavaScript 胶水层、虚拟文件系统与 Web Worker 接口。
6
+
7
+ ## 构建前提
8
+
9
+ 产出 WASM 模块需要已激活的 Emscripten SDK(`emcc` 在 `PATH` 上)。`./build.sh` 会检查 `emcc`,缺失时报错停下;它不安装任何东西。
10
+
11
+ TCC 的一份构建只有一个代码生成目标,所以本包每个目标带一份 WASM 模块、每个目标跑一次 `build.sh`:
12
+
13
+ ```
14
+ TARGET=x86_64-linux-gnu ./build.sh # emits tcc-x86_64-linux-gnu.mjs + tcc-x86_64-linux-gnu.wasm
15
+ TARGET=aarch64-linux-gnu ./build.sh # emits tcc-aarch64-linux-gnu.mjs + tcc-aarch64-linux-gnu.wasm
16
+ ```
17
+
18
+ 每个模块导出 libtcc 的 `tcc_*` API 加一个主入口(内核提供时是 `tinyc_main`,否则是 `main`;胶水优先用 `tinyc_main`、回退到 `main`)。八个通用目标编上游 TCC 树。`wasm32-wasi` 模块由项目自己的 WebAssembly 代码生成后端构建(仓库根的 `wasm-backend/` 树):`build.sh` 的该分支用后端的 `wasm-gen.c` / `wasm-link.c` 源码与其补丁组装上游树,然后与其它目标一样用 emcc 编译。
19
+
20
+ 胶水层(`index.mjs`、`worker.mjs`)不依赖 WASM 构建即完整:`loadTinyc` 也接受注入的模块(`module`、`createModule`、`wasmExports`,或异步的 `loadModule(target, files)` 加载器),测试套件就是这样跑它的。
21
+
22
+ ## 目标
23
+
24
+ ```js
25
+ import { loadTinyc } from 'tinyc-web';
26
+
27
+ const tinyc = await loadTinyc({ target: 'x86_64-linux-gnu', sysroot: true });
28
+ ```
29
+
30
+ 支持的目标——与原生目标矩阵同一集合,外加 `wasm32-wasi`(浏览器自身的宿主形式)。没有浏览器专属目标,也没有原生专属目标:
31
+
32
+ | 目标 | 产物 | 在浏览器里 run |
33
+ |---|---|---|
34
+ | `wasm32-wasi`(缺省) | WebAssembly(WASI) | 能 |
35
+ | `x86_64-linux-gnu` | Linux x86-64 ELF | 不能 |
36
+ | `aarch64-linux-gnu` | Linux AArch64 ELF | 不能 |
37
+ | `riscv64-linux-gnu` | Linux RISC-V 64 ELF | 不能 |
38
+ | `x86_64-windows` | Windows x86-64 PE | 不能 |
39
+ | `aarch64-linux-android` | Android AArch64 ELF(bionic) | 不能 |
40
+ | `x86_64-linux-android` | Android x86-64 ELF(bionic) | 不能 |
41
+ | `arm64-apple-darwin` | macOS arm64 Mach-O | 不能 |
42
+ | `x86_64-apple-darwin` | macOS x86-64 Mach-O | 不能 |
43
+
44
+ 目标的模块(`tcc-<target>.wasm` / `tcc-<target>.mjs`)按需加载——只取请求目标的那一份,每个页面至多取一次。不同目标的实例可共存;每个实例有自己的虚拟文件系统与自己的 sysroot 清单(`sysroot-manifests/<target>.json`;顶层的 `sysroot-manifest.json` 是缺省目标的清单)。未知目标会被拒绝,并列出支持的清单。
45
+
46
+ `sysroot: true` 把该目标自带的头文件集合(TCC 自带头:`float.h`、`stdarg.h`、`stddef.h`、`stdbool.h`、`tcclib.h`,以及该目标清单里的其余头)加载进虚拟文件系统的 `/sysroot/include` 并注册为 include 目录。自定义清单可以以 `{ manifest, baseUrl }` 传入。
47
+
48
+ 各目标清单的特有事实:
49
+
50
+ - Android 清单描述的是原生 Android 构建的 bionic sysroot 布局:`libc: "bionic"`、`androidApi: 30`、`dynamicLinker: "/system/bin/linker64"`(64 位 Android ELF 产物的解释器)。
51
+ - Darwin 清单只含 TCC 自带头。macOS 系统 SDK 头受许可限制、不随包分发;清单以 `systemHeaders: "user-sdk"` 标记这一点,系统头由使用者加进虚拟文件系统并注册其目录来提供(见*虚拟文件系统与添加文件*)。Darwin 目标只能编译成文件;Mach-O 产物要在 Apple Silicon 上运行需要代码签名——至少是 ad-hoc 签名——无论它在哪里编译。
52
+
53
+ ## 输出格式
54
+
55
+ 每个目标能产出的输出文件格式在每个包、每个平台上都相同。各目标的清单在 `outputs` 字段里带这份表,全表如下:
56
+
57
+ | 族(目标) | exe | obj | shared | ar |
58
+ |---|---|---|---|---|
59
+ | ELF(`*-linux-gnu`、`*-linux-android`) | ELF 可执行文件,无扩展名 | ELF 可重定位 `.o` | ELF 共享对象 `.so` | ar 归档 `.a` |
60
+ | PE(`x86_64-windows`) | PE 可执行文件 `.exe` | COFF 目标文件 `.o` | PE DLL `.dll` | ar 归档 `.a` |
61
+ | Mach-O(`*-apple-darwin`) | Mach-O 可执行文件,无扩展名 | Mach-O 目标文件 `.o` | Mach-O dylib `.dylib` | ar 归档 `.a` |
62
+ | WebAssembly(`wasm32-wasi`) | — | — | — | 模块:WebAssembly `.wasm` |
63
+
64
+ ## 运行:只有 wasm32
65
+
66
+ 编译成文件对每个目标都成立。运行不成立:编译器在浏览器里的宿主平台就是 WebAssembly 本身,所以只有 `wasm32-wasi` 目标的产物能在这里跑——产出的模块由浏览器实例化并执行。
67
+
68
+ 对其它每个目标,胶水层在请求到达原生模块之前就先行拒绝 run 请求,抛 `TinycRunNotSupportedError`:
69
+
70
+ - `tinyc.callMain(['-run', ...])` 抛错;
71
+ - `state.run(...)` 抛错。
72
+
73
+ `instance.canRun` 报告实例的目标能不能 run。
74
+
75
+ ### wasm32 的运行方式
76
+
77
+ WebAssembly 模块不能从自身内部实例化另一个 WebAssembly 模块——实例化是宿主能力。所以运行从不经过编译器模块:胶水层拿编译产物的字节,用 WebAssembly API 自己实例化它:
78
+
79
+ - `state.run(args, options)` 把产物写进虚拟文件系统的文件(`options.outputPath`,缺省 `/a.out`),读回字节并运行;WASI argv 是 `[outputPath, ...args]`。
80
+ - `tinyc.callMain(['-run', src, ...progArgs])` 先经导出的 main 把 `src` 编到 `/a.out`(原生 main 从不见到 `-run`),然后以 WASI argv `[src, ...progArgs]` 运行产物。
81
+ - `runWasmModule(bytes, options)` / `runWasmModuleSync(bytes, options)` 直接运行产物字节(前者是异步 `WebAssembly.compile` 版,后者是同步 `WebAssembly.Module`/`Instance` 版,Worker 内与上面两条路径用的都是它)。
82
+ - `tinyc.runWasmFile(path, options)` 运行已经存在虚拟 FS 里的产物——先前编译成文件的、或用 `addFile` 放进去的——不重新编译;它用 `exportFile` 读出字节,经同一个运行器与垫片栈运行,并应用实例注册的垫片。
83
+
84
+ 入口约定:不给 `options.entry` 时,调导出的 `_start`(命令式),结果是 `{ exitCode }`;给 `options.entry` 时,以 `options.callArgs`(缺省 `options.args`)调该导出,返回值原样返回(函数式)。`state.run` 返回退出码,或入口的返回值。
85
+
86
+ 实例得到一个最小 WASI 垫片(`wasi_snapshot_preview1`):`fd_write`、`fd_read`、`fd_close`、`fd_seek`(stdio 描述符不可 seek:`ESPIPE`)、`fd_fdstat_get`、`args_get`、`args_sizes_get`、`environ_get`、`environ_sizes_get`、`clock_time_get`、`random_get`、`sched_yield` 与 `proc_exit`。`fd_write` 写到 fd 1/2 的输出以 `Uint8Array` 块路由到该次运行的 IO。`proc_exit` 从不结束宿主:垫片抛错、运行器接住它,代码成为该次运行的退出码。
87
+
88
+ 往模块实例里传数据:`writeModuleData(instance, data, options)` 把字符串/`Uint8Array` 写进实例导出的内存——模块有导出的 `malloc` 时经它分配(结果带一个 `free()`),否则写到 `options.offset`(数字,或 `(byteLength) => address`)。`readModuleData` / `readModuleCString` 读回。
89
+
90
+ ## 运行时垫片:缺省 libc
91
+
92
+ 编到 wasm32 的 C 程序会导入它用到的 libc 函数,而本包里没有可链接的 libc 归档。所以每次运行还会得到缺省垫片库(`runtime-shims.mjs`)作为 `env` 名下的导入,用 JS 对着实例的线性内存实现:
93
+
94
+ - 内存/字符串:`memcpy`、`memmove`、`memset`、`memcmp`、`strlen`、`strcpy`、`strncpy`、`strcat`、`strncat`、`strcmp`、`strncmp`、`strchr`、`strrchr`、`strstr`、`strdup`
95
+ - 分配:`malloc`、`calloc`、`realloc`、`free`
96
+ - stdio:`printf`、`fprintf`、`vprintf`、`vfprintf`、`sprintf`、`vsprintf`、`snprintf`、`vsnprintf`、`puts`、`putchar`、`fputs`、`putc`、`fputc`、`fwrite`、`fread`、`fgetc`、`getchar`、`ungetc`
97
+ - stdlib:`exit`、`abort`、`atexit`、`atoi`、`atol`、`atoll`、`atof`、`strtol`、`strtoul`、`strtoll`、`strtoull`、`strtod`、`strtof`、`abs`、`labs`、`llabs`、`rand`、`srand`、`getenv`(返回 NULL)、`system`(返回 -1)
98
+ - ctype:`isalpha`、`isdigit`、`isspace`、`isalnum`、`isupper`、`islower`、`ispunct`、`iscntrl`、`isxdigit`、`isblank`、`isprint`、`isgraph`、`tolower`、`toupper`
99
+ - math:`sin`、`cos`、`tan`、`asin`、`acos`、`atan`、`atan2`、`exp`、`log`、`log10`、`pow`、`sqrt`、`floor`、`ceil`、`fabs`、`round`、`trunc`、`fmod`(即 JS 的 `Math` 函数)
100
+ - time:`time`(由 `Date.now()` 来的秒数)、`clock`、`difftime`
101
+
102
+ 值得注意的细节:
103
+
104
+ - **时机。** 导入函数在实例存在之前就已创建,所以它们从不捕获内存:每次调用都经一个 holder 读内存。胶水在实例化之后、任何入口运行之前立即填好 holder,所以垫片被调用时内存必然已就位。
105
+ - **分配器。** `malloc` 一家是首次适配空闲链表分配器(带块分裂),管辖自 `heapBase` 起的区域(缺省 65536,可按次运行覆盖);不够时它扩内存。模块若导出自己的 `malloc`,垫片把分配调用转发给模块的分配器,内部的那个从不碰堆——任何时候只有一个分配器在工作。
106
+ - **stdio。** printf 一家在 JS 里解析格式串,从线性内存读格式串与参数。变参从 `va_list` 指向的区域按顺序读,每个按其自然对齐:i32/指针占 4 字节槽,i64/f64 占 8 字节槽并对齐到 8。支持:标志 `- + space # 0`、宽度与精度(含 `*`)、长度修饰 `hh h l ll z j t`、转换 `d i u x X o c s p f F e E g G a A n %`。输出以字节路由到该次运行的 IO;`FILE*` 流值 2 走 `err`,其它值走 `out`。`fread`/`fgetc` 读该次运行的 stdin(`options.stdin`,其次是 `io.in()` 的块)。
107
+ - **exit。** `exit(code)` 在模块导出间接函数表(`__indirect_function_table`)时运行 `atexit` 处理器——处理器是表索引、只能经表调用——然后以 `{ exitCode: code }` 展开退出,与 `proc_exit` 相同。`abort()` 以退出码 134 展开退出。
108
+
109
+ ### libtcc1 辅助函数
110
+
111
+ TCC 的运行时支持库(`vendor-tinycc/lib/`)已逐符号对照过 wasm32 目标能发出的东西。其中几乎没有需要 JS 垫片的,原因如下;唯一的例外是 `libtcc1.c` 里的一族辅助函数,它们确实会以导入形式出现。
112
+
113
+ - `libtcc1.c` 的转换——浮点转换 `__floatundisf/df/xf`、`__fixunssfdi`、`__fixsfdi`、`__fixunsdfdi`、`__fixdfdi`、`__fixunsxfdi`、`__fixxfdi`:wasm32 有原生 float↔i64 转换指令(且该目标上 long double 是 f64),所以代码生成器发的是指令——float→整数用饱和的 `trunc_sat`——不是调用。本版本的 `lib/` 树里没有 `__tcc_cvt_*` 符号;转换辅助就是上面的 `__fix*`/`__float*` 一族。
114
+ - `libtcc1.c` 的除法与移位——`__divdi3`、`__moddi3`、`__udivdi3`、`__umoddi3`(长长整除与取模)与 `__ashldi3`、`__ashrdi3`、`__lshrdi3`(变量计数的长长移位):这些代码生成器确实发成调用,在编译出的模块里以 `env` 导入出现。该目标不带 libtcc1,本包也不为它们提供缺省垫片,所以用了长长整除、取模或变量计数长长移位的程序会实例化失败,抛 `TinycMissingImportError` 并指名该辅助函数;把 JS 实现以该名字注册为自定义垫片(见下)即可补上。常量计数的长长移位由代码生成器内联,不需要辅助函数。
115
+ - `builtin.c`——`__tcc_builtin_*` 一族(`ffs`、`clz`、`ctz`、`popcount`、`parity`,……):wasm 有原生 `clz`/`ctz`/`popcnt` 指令;代码生成处理它们。
116
+ - `va_list.c`——`__va_arg`:wasm 目标上 va_list 是指向内存参数区的指针,`va_arg` 是代码生成器做的指针推进。
117
+ - `alloca.S`——`alloca`/`__alloca`:wasm 的 alloca 在生成的代码里调整栈指针全局量。
118
+ - `stdatomic.c` / `atomic.S`——`__atomic_*` 一族:程序用到 `<stdatomic.h>` 时,C 源码由 wasm 后端像任何 C 文件一样编译;在单线程 wasm 里这些操作归结为普通 load 与 store。不涉及宿主导入。
119
+ - `bcheck.c`——`__bound_*` 一族:只在 `-b` 边界检查模式下发出,且实现依赖 mmap、信号与 pthread。不提供。
120
+ - `runmain.c`——`_runmain`、`__run_on_exit`、`on_exit`、`atexit`、`exit`:原生 `-run` 的支持文件。浏览器路径里胶水直接调 `_start`,`exit`/`atexit` 语义来自上面的 libc 垫片。
121
+ - `armeabi.c`(`__aeabi_*`)、`lib-arm64.c`、`tcov.c`:ARM 目标的辅助与覆盖率运行时;与 wasm 无关。
122
+
123
+ ## 自定义垫片
124
+
125
+ 导入 WASI 垫片与缺省 libc 之外符号的程序——宿主 API、外设、任何东西——由注册为垫片的 JS 函数提供它们。垫片以 `fn(ctx, ...cArgs)` 形式被调用:
126
+
127
+ - `ctx.memory()` / `ctx.u8()`——实例的线性内存与它的一个 `Uint8Array` 视图;
128
+ - `ctx.readCString(ptr)`、`ctx.writeCString(ptr, str)`(写入 UTF-8 字节加一个 NUL 终止符,返回含 NUL 的字节数)、`ctx.readBytes(ptr, len)`、`ctx.writeBytes(ptr, bytes)`——内存辅助;
129
+ - `ctx.io`——该次运行的字节 IO(`out`/`err` 收 `Uint8Array`,可选的 `in()`)。
130
+
131
+ C 参数以其 wasm 类型到达:i32/f32/f64 是数字,i64 是 `BigInt`;返回值同路返回,所以 i64 结果必须以 `BigInt` 返回。JS 函数不声明签名——引擎把参数与返回值强制转换成模块自己声明的导入类型。
132
+
133
+ 注册有三个层级。同一个导入,层级高者胜;同一层级内,后注册的替换先注册的:
134
+
135
+ 1. **单次运行**——`runWasmModule(bytes, { shims: { name: fn } })`;`state.run(args, { shims })` 与 `callMain(['-run', ...], { shims })` 会转发它。
136
+ 2. **实例**——`tinyc.registerShim(name, fn)`、`tinyc.registerShims({ ... })`、`tinyc.unregisterShim(name)`;适用于经该实例的每一次后续运行。
137
+ 3. **包级全局**——`registerGlobalShim(name, fn)`、`registerGlobalShims({ ... })`、`unregisterGlobalShim(name)`;适用于每一个后续实例与 `runWasmModule` 调用。
138
+
139
+ 这三层之下是缺省 libc 垫片与 WASI 垫片。三层之上是 `options.imports`,原样合并进导入对象(原始逃生口——也能提供内存这类非函数导入)。注册键是裸名字(模块 `env`),或 `"module.name"` 表示任何其它导入模块——包括 `wasi_snapshot_preview1`,其内置条目也能以同样方式覆盖。
140
+
141
+ **缺失的导入。** 实例化之前,运行器列出模块所需的导入(`WebAssembly.Module.imports`),与组装好的导入对象做差。缺任何一个都抛 `TinycMissingImportError`——完整的 `module.name` 清单在 `err.missing` 上、注册路径写在消息里——而不是引擎原始的 `LinkError`。把指名的符号注册上即可修复。
142
+
143
+ ## 取出编译产物
144
+
145
+ 编译产物是虚拟文件系统里的文件,对每个目标都成立(目标文件、可执行文件、库、Windows PE 文件):
146
+
147
+ ```js
148
+ const bytes = tinyc.exportFile('/out/prog.exe'); // Uint8Array
149
+ const blob = tinyc.exportBlob('/out/prog.exe'); // Blob, e.g. for a download link
150
+ ```
151
+
152
+ ## 用法
153
+
154
+ ### script 标签
155
+
156
+ 本包也能构建为单个经典脚本文件 `tinyc-web.js`,它定义全局 `TinycWeb`,API 与模块版相同;`TinycWeb.loadTinyc` 是入口点。从 npm 包经 CDN:
157
+
158
+ ```html
159
+ <script src="https://cdn.jsdelivr.net/npm/tinyc-web@0.1.0/tinyc-web.js"></script>
160
+ <script>
161
+ (async () => {
162
+ const tinyc = await TinycWeb.loadTinyc();
163
+ tinyc.compileString('int answer() { return 42; }');
164
+ })();
165
+ </script>
166
+ ```
167
+
168
+ 按目标分的原生文件不在 bundle 里:对请求的目标,胶水以动态 `import()` 加载 `tcc-<target>.mjs` 并取 `tcc-<target>.wasm`,两者都相对 bundle 文件自身的 URL 解析——用上面的 CDN 地址时,它们自动来自同一个 `tinyc-web@0.1.0` 包前缀。自托管时,把 `tcc-<target>.mjs` 与 `tcc-<target>.wasm` 放在与 `tinyc-web.js` 相同的目录。`loadTinyc({ baseUrl })` 改对另一个目录解析;`wasmUrl` / `glueUrl` 各覆盖一个文件。sysroot 清单已内联进 bundle,所以它们不需要取 JSON 文件。
169
+
170
+ `tinyc-web.js` 由模块源码以以下命令重新生成:
171
+
172
+ ```
173
+ npm run build:web # node build-web-bundle.mjs (esbuild)
174
+ ```
175
+
176
+ ### 命令行模式
177
+
178
+ ```js
179
+ const exitCode = tinyc.callMain(['-o', '/out/a.o', '-c', '/src/main.c']);
180
+ ```
181
+
182
+ `callMain` 把 `argv[0]` 填为虚拟二进制路径(`/sysroot/bin/tinyc`),并调导出的 `tinyc_main`(回退到 `main`)。它返回退出码。导出的 main 不可重入;嵌套的 `callMain` 抛错。
183
+
184
+ ### 细粒度 API
185
+
186
+ ```js
187
+ const state = tinyc.createState();
188
+ state.setOutputType(1); // TCC_OUTPUT.MEMORY
189
+ state.addIncludePath('/deps/include');
190
+ state.compileString('int answer() { return 42; }');
191
+ state.delete();
192
+ ```
193
+
194
+ State 的方法镜像它们调用的 libtcc 函数(`tcc_compile_string`、`tcc_add_include_path`、`tcc_add_file`,……)。某个方法所需的导出在原生模块里缺失时,抛 `TinycMissingExportError` 并指名该导出。
195
+
196
+ ### 虚拟文件系统与添加文件
197
+
198
+ 浏览器里没有真实文件系统可供 TCC 指向,所以用户文件以内容进入虚拟文件系统。这是「动态添加本地文件」规则的浏览器形态:
199
+
200
+ ```js
201
+ await tinyc.addFile('/src/main.c', 'int main() { return 0; }'); // string / Uint8Array / ArrayBuffer
202
+ await tinyc.addFile('/src/util.h', fileFromAnInputElement); // File or Blob
203
+ await tinyc.addFileFromUrl('/deps/sqlite3.h', 'https://example.com/sqlite3.h');
204
+ tinyc.registerIncludeDir('/deps'); // 对新 state 走 tcc_add_include_path
205
+ ```
206
+
207
+ 文件内容持久化在一个存储里(`vfs-store.mjs`),不留在内存:每个目标一个 IndexedDB 数据库——`tinyc-web-fs-<target>`,一张以路径为键的 `files` 表——在有 IndexedDB 的地方(浏览器与 Web Worker),没有的地方(Node、测试)或 IndexedDB 打开失败时用内存后端。自定义存储或存储工厂可按次加载注入(`loadTinyc({ fsStore })` / `loadTinyc({ storeFactory })`)。虚拟 FS 本身在内存里只留路径索引(路径 → 大小/mtime)加一个 LRU 内容缓存(至多 32 个文件、总共 16 MiB,`VFS_CACHE_MAX_ENTRIES` / `VFS_CACHE_MAX_BYTES`)。`loadTinyc` 在 resolve 之前打开存储并载入索引,所以实例启动时就带着同一目标先前会话留下的文件——其中 sysroot 文件会被认出、不再重新取。当原生模块是 Emscripten 构建时,文件还会额外镜像进模块的 `FS`(TCC 运行期间编译工作集必须在那里);这层镜像被限定在 `VirtualFS.mountTo`/`syncFile`,即 Emscripten FS 的适配点。
208
+
209
+ 原生模块的文件系统是 WasmFS(build.sh 传 `-sWASMFS=1`;`-sFORCE_FILESYSTEM=1` 是把镜像所走的 JS `FS` API 包含进来的开关),其根后端是内存。镜像之前,`loadTinyc` 尝试把 WasmFS 的 OPFS 后端——浏览器在磁盘上的源私有文件系统——挂到模块文件系统内的 `/opfs`,经构建导出的 `wasmfs_create_opfs_backend` / `wasmfs_create_directory` 函数。这个尝试只在 Web Worker 里运行:在浏览器主线程上创建 OPFS 后端可能死锁,而 OPFS 同步访问句柄只在 Worker 里存在。任何失败——主线程、没有 OPFS 的浏览器、没构建出这些导出的模块、挂载被拒——都静默地把内存后端留在原地,`tinyc.fsBackend` 报告发生了哪一种:`'opfs'` 或 `'memory'`。是 `'opfs'` 时,镜像的编译工作集以挂载点为根:虚拟 FS 路径 `P` 在模块里位于 `/opfs` + `P`,在磁盘上,且每个交给原生模块的路径都被重定位以与之匹配——镜像的写与删、`tcc_add_file`、include/library/lib 路径注册、`tcc_output_file`,以及 `callMain` argv 里的路径参数(argv[0]、`-o` 的值、输入文件)——编译产物从那里读回虚拟 FS。虚拟 FS 自己的路径从不变;变的只有模块侧的位置。是 `'memory'` 时,工作集就位于内存后端根里的虚拟 FS 路径处,与路径字面完全一致。
210
+
211
+ 实例上(以及 `tinyc.fs` 上)有完整的文件生命周期:写用 `addFile` / `addFileSync`,读用 `readFile`(字节)/ `readTextFile`(字符串)——`exportFile` / `exportBlob` 是同一读操作对编译产物的叫法——列举用 `listFiles(prefix)`,删用 `removeFile(path)`(索引条目、持久记录与原生模块里的镜像副本)或 `clearFiles()`(除 `/sysroot/` 下挂载的 sysroot 外的全部)。
212
+
213
+ 存储是异步的,由此有两条时机规则。`addFile` 在其内容持久化后 resolve;`addFileSync` 立即更新索引、缓存与原生镜像,但只把存储写排队(`removeFile` / `clearFiles` 的删除同样排队)——`await tinyc.whenIdle()` 是排队的一切都已落定的点。而同步读由内容缓存提供:会话期间写过或读过的都会缓存,但从存储恢复、尚未碰过的文件不会——用 `readFile` / `exportFile` 读它会抛错并指名异步形式 `readFileAsync` / `readTextFileAsync` / `exportFileAsync`,后者从存储读它并暖缓存。
214
+
215
+ `compileFile(path)` 经 `tcc_compile_string` 编译一个虚拟 FS 源码,带一个携带该路径的 `#line` 标记;`state.addFile(path)` 把路径传给 `tcc_add_file`,用于源码、目标文件与归档。
216
+
217
+ ### IO
218
+
219
+ IO 就是普通 JS 函数——本包不需要跳板层:
220
+
221
+ ```js
222
+ const lines = [];
223
+ tinyc.setIO({
224
+ out: (text) => lines.push(text),
225
+ err: (text) => console.error(text),
226
+ in: () => null, // EOF
227
+ });
228
+ ```
229
+
230
+ 缺省:`out`/`err` 是行缓冲的写者,写到 `console.log`/`console.error`,`in` 返回 EOF。按 state 的 `state.setIO(...)` 经 `tcc_set_error_func` 把该 state 的错误通道改道;原生 stdout 的路由按模块走,跟随实例 IO。
231
+
232
+ ### Web Worker
233
+
234
+ ```js
235
+ import { TinycWorker } from 'tinyc-web/worker';
236
+
237
+ const worker = new TinycWorker({ target: 'x86_64-linux-gnu', sysroot: true });
238
+ await worker.compileString('int f() { return 1; }');
239
+ const exitCode = await worker.runCli(['-c', '/src/main.c', '-o', '/out/a.o']);
240
+ worker.terminate();
241
+ ```
242
+
243
+ `TinycWorker` 把 `worker.mjs` 作为模块 Worker 拉起,为 `compileString`、`compileFile`、`addFile`、`registerIncludeDir` 与 `runCli` 返回 promise。`target` 选项选择 Worker 内的按目标模块(缺省 `wasm32-wasi`);run 守卫在那里同样适用,所以非 wasm32 目标的 `runCli(['-run', ...])` 会被拒绝。Worker 内的原生输出被转发到主线程,并分发给 `io` 选项。
244
+
245
+ 垫片函数不能从主线程注册到 `TinycWorker` 上——JS 函数过不了 `postMessage`,`worker.registerShim(...)` / `worker.registerShims(...)` 会抛错说明这一点。Worker 侧的路径是构造器的 `shimModules` 选项:一个模块 URL 数组。Worker 导入每个模块,把它的默认导出——一个垫片映射对象(`{ name: fn }`)——注册到它的实例上:
246
+
247
+ ```js
248
+ const worker = new TinycWorker({ shimModules: ['./my-shims.mjs'] });
249
+ // my-shims.mjs: export default { host_log: (ctx, ptr) => { ... } };
250
+ ```
251
+
252
+ ## 测试
253
+
254
+ ```
255
+ npm test # node --test test.mjs
256
+ npm run test:web # node --test test-web-bundle.mjs
257
+ ```
258
+
259
+ 该套件在 Node 里对着一个注入的 mock 模块跑胶水逻辑,该 mock 实现 `tcc_*` 名字:从字符串、`Blob`/`File` 与 URL 来源摄入虚拟 FS,include 目录注册到达 `tcc_add_include_path`,在 Emscripten 接线点与经错误回调两条路上的 IO 路由,`callMain` 的 argv 组装,缺失导出错误,目标注册表(两个目标共存、虚拟文件系统隔离、按目标懒加载),非 wasm32 目标上的 run 守卫与 wasm32 run 路径,产物导出,以及各目标 sysroot 清单。run 路径还用真实手工汇编的 wasm 模块额外测过(`test.mjs` 里的字节数组,每个都附 WAT 描述):一个函数式的 `add` 导出,一个经 WASI `fd_write` 垫片写出并经 `proc_exit` 退出的 `_start` 模块,WASI argv 垫片,缺省 libc 垫片(`printf` 格式化进 IO、`memcpy`、`malloc`/`free` 堆复用、`options.imports` 覆盖一个缺省垫片),以及自定义垫片面——带确切清单的缺失导入诊断、带 `ctx.readCString` 的实例级注册、对实例注册的单次运行覆盖、`unregisterShim`、`callMain -run` 的垫片转发、包级注册,与 `TinycWorker.registerShim` 的边界错误。第二个套件(`test-web-bundle.mjs`)重新构建 `tinyc-web.js`,把它作为经典脚本加载进一个打扮成浏览器页面的 Node `vm` 上下文(假的 `document.currentScript` 与 `location`),并核对:`TinycWeb` 全局与模块构建的导出清单、脚本场景的 base-URL 规则(脚本目录、页面目录回退、`baseUrl`/`wasmUrl` 覆盖)、内联的各目标 sysroot 清单,以及 bundle 内的 mock 模块与手写 wasm run 路径。