tinyc-web 0.1.1 → 0.1.3

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 CHANGED
@@ -666,6 +666,14 @@ export class VirtualFS {
666
666
  const nativePath = this._nativePath(path);
667
667
  const dir = nativePath.slice(0, nativePath.lastIndexOf('/')) || '/';
668
668
  if (typeof FS.mkdirTree === 'function') FS.mkdirTree(dir);
669
+ // The mirror write is a replace: the native copy must end up
670
+ // holding exactly `bytes`. The WasmFS FS.writeFile appends to a
671
+ // file that already exists (it writes at the file's current
672
+ // size), so an existing native file is unlinked first and the
673
+ // write lands as a fresh file with exactly the mirrored content.
674
+ if (typeof FS.unlink === 'function') {
675
+ try { FS.unlink(nativePath); } catch { /* not present natively */ }
676
+ }
669
677
  FS.writeFile(nativePath, bytes);
670
678
  }
671
679
  }
@@ -1393,11 +1401,19 @@ export class TinycState {
1393
1401
  this.handle = handle;
1394
1402
  this._io = null;
1395
1403
  this._deleted = false;
1404
+ this._outputTypeSet = false;
1396
1405
  }
1397
1406
 
1398
1407
  _call(name, returnType, argTypes, args) {
1399
1408
  if (this._deleted) throw new TinycError('tinyc: state already deleted');
1400
- return this._bridge.call(name, returnType, argTypes, [this.handle, ...args]);
1409
+ // The handle goes in as the first argument AND as a leading
1410
+ // 'number' in argTypes: the bridge converts args[i] through
1411
+ // argTypes[i], so prepending the handle to the values alone
1412
+ // shifts every converter one slot left (a 'string' converter
1413
+ // lands on the numeric handle, and the real string argument
1414
+ // reaches the module unconverted, as 0).
1415
+ return this._bridge.call(name, returnType,
1416
+ ['number', ...argTypes], [this.handle, ...args]);
1401
1417
  }
1402
1418
 
1403
1419
  _checkRc(name, rc) {
@@ -1485,8 +1501,22 @@ export class TinycState {
1485
1501
  }
1486
1502
 
1487
1503
  setOutputType(type) {
1488
- return this._checkRc('tcc_set_output_type',
1504
+ const rc = this._checkRc('tcc_set_output_type',
1489
1505
  this._call('tcc_set_output_type', 'number', ['number'], [type]));
1506
+ this._outputTypeSet = true;
1507
+ return rc;
1508
+ }
1509
+
1510
+ /* tcc_set_output_type is not a plain setter in libtcc: it also
1511
+ * creates the state's ELF sections (tccelf_new), and upstream's
1512
+ * contract is that it MUST be called before any compilation —
1513
+ * compiling without it runs tccelf_end_file over sections that
1514
+ * do not exist and traps inside put_elf_sym. Establish the
1515
+ * MEMORY default lazily, exactly once, at the first compiling
1516
+ * entry point; an explicit setOutputType beforehand suppresses
1517
+ * the default, and tccelf_new is never run twice on one state. */
1518
+ _ensureOutputType() {
1519
+ if (!this._outputTypeSet) this.setOutputType(TCC_OUTPUT.MEMORY);
1490
1520
  }
1491
1521
 
1492
1522
  /** Add a file (source, object or archive) by virtual path. The file
@@ -1501,11 +1531,13 @@ export class TinycState {
1501
1531
  throw new TinycError(`tinyc: addFile: ${p} is not in the virtual FS`);
1502
1532
  }
1503
1533
  this._instance.fs.syncFile(p);
1534
+ this._ensureOutputType();
1504
1535
  return this._checkRc('tcc_add_file',
1505
1536
  this._call('tcc_add_file', 'number', ['string'], [this._bridge.modulePath(p)]));
1506
1537
  }
1507
1538
 
1508
1539
  compileString(source) {
1540
+ this._ensureOutputType();
1509
1541
  return this._checkRc('tcc_compile_string',
1510
1542
  this._call('tcc_compile_string', 'number', ['string'], [source]));
1511
1543
  }
@@ -1520,6 +1552,7 @@ export class TinycState {
1520
1552
  const p = normalizeVfsPath(path);
1521
1553
  const src = this._instance.fs.readTextFile(p);
1522
1554
  const marked = `#line 1 "${p}"\n${src}`;
1555
+ this._ensureOutputType();
1523
1556
  return this._checkRc('tcc_compile_string',
1524
1557
  this._call('tcc_compile_string', 'number', ['string'], [marked]));
1525
1558
  }
@@ -1735,14 +1768,11 @@ export class Tinyc {
1735
1768
  * read fails naming exportFileAsync as the alternative. */
1736
1769
  exportFile(path) {
1737
1770
  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
- }
1771
+ // The module FS copy is authoritative: it is where TCC writes,
1772
+ // and a compile can rewrite a path the virtual FS already holds
1773
+ // a mirror of (TinycState.run writes the fixed DEFAULT_RUN_OUTPUT
1774
+ // on every call). Read it first and refresh the mirror; only a
1775
+ // path the module FS does not have falls back to the mirror.
1746
1776
  const FS = this._bridge.native?.FS;
1747
1777
  if (FS && typeof FS.readFile === 'function') {
1748
1778
  try {
@@ -1750,14 +1780,18 @@ export class Tinyc {
1750
1780
  this.fs.addFileSync(p, bytes);
1751
1781
  return this.fs.readFile(p);
1752
1782
  } catch {
1753
- // fall through to the error below
1783
+ // not in the module FS: fall through to the virtual FS copy
1754
1784
  }
1755
1785
  }
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
- );
1786
+ if (this.fs.hasFile(p)) {
1787
+ try {
1788
+ return this.fs.readFile(p);
1789
+ } catch {
1790
+ throw new TinycError(
1791
+ `tinyc: ${p} is persisted in the virtual FS store but is not in ` +
1792
+ `the in-memory cache; read it with exportFileAsync() instead`
1793
+ );
1794
+ }
1761
1795
  }
1762
1796
  throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
1763
1797
  }
@@ -1766,7 +1800,6 @@ export class Tinyc {
1766
1800
  * when it is not in the content cache. */
1767
1801
  async exportFileAsync(path) {
1768
1802
  const p = normalizeVfsPath(path);
1769
- if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
1770
1803
  const FS = this._bridge.native?.FS;
1771
1804
  if (FS && typeof FS.readFile === 'function') {
1772
1805
  try {
@@ -1774,9 +1807,10 @@ export class Tinyc {
1774
1807
  this.fs.addFileSync(p, bytes);
1775
1808
  return bytes;
1776
1809
  } catch {
1777
- // fall through to the error below
1810
+ // not in the module FS: fall through to the virtual FS copy
1778
1811
  }
1779
1812
  }
1813
+ if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
1780
1814
  throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
1781
1815
  }
1782
1816
 
@@ -1943,6 +1977,19 @@ export class Tinyc {
1943
1977
  const state = new TinycState(this, handle ?? {});
1944
1978
  this._states.add(state);
1945
1979
  state._installErrorFunc();
1980
+ if (isRunnableTarget(this.target)) {
1981
+ // The wasm target is freestanding: no crt1.o/crti.o exist for
1982
+ // it anywhere, and this package's run model enters the product
1983
+ // through a named export, never through a C runtime startup.
1984
+ // Without -nostdlib, tcc_set_output_type for any non-MEMORY
1985
+ // type fails inside tccelf_add_crtbegin ('crt1.o not found')
1986
+ // and poisons the state's error count, which also makes the
1987
+ // next compile report failure. The backend's own test suite
1988
+ // drives the target with -nostdlib throughout; mirror that as
1989
+ // the state default here. Other targets keep the hosted
1990
+ // default: their EXE output does link the C runtime.
1991
+ state.setOptions('-nostdlib');
1992
+ }
1946
1993
  if (this._bridge.has('tcc_add_include_path')) {
1947
1994
  for (const dir of this.fs.getIncludeDirs()) state.addIncludePath(dir);
1948
1995
  }
@@ -2111,11 +2158,59 @@ async function loadSysroot(instance, sysrootOpt) {
2111
2158
  // backend in place; loadTinyc succeeds either way. The outcome is
2112
2159
  // memoized per native module (repeat loads of a cached module do
2113
2160
  // not mount twice) and reported as instance.fsBackend.
2161
+ //
2162
+ // A successful mount alone does not prove the backend works: in a
2163
+ // build without pthreads the backend's file operations are async
2164
+ // JS, and without Asyncify/JSPI to suspend into, the first real
2165
+ // operation traps — after wasmfs_create_directory has already
2166
+ // reported success. The mount is therefore followed by a
2167
+ // write/read probe through the same JS FS operations the
2168
+ // virtual-FS mirror uses (probeOpfsBackend below); only a probe
2169
+ // whose bytes read back intact lets the instance report 'opfs'.
2170
+ // A failed probe leaves the mount point in place but unused: the
2171
+ // instance reports 'memory' and no path is ever rooted under it.
2114
2172
  // ---------------------------------------------------------------------
2115
2173
 
2116
2174
  const OPFS_MOUNT_POINT = '/opfs';
2117
2175
  const opfsBackendByModule = new WeakMap();
2118
2176
 
2177
+ const OPFS_PROBE_DIR = OPFS_MOUNT_POINT + '/.tinyc-probe';
2178
+ const OPFS_PROBE_FILE = OPFS_PROBE_DIR + '/probe';
2179
+ const OPFS_PROBE_BYTES = new Uint8Array([0x74, 0x69, 0x6e, 0x79, 0x63]); // "tinyc"
2180
+
2181
+ /** First-use probe of a freshly mounted OPFS backend: create a
2182
+ * directory, write a small file into it and read the bytes back,
2183
+ * through the JS FS API the virtual-FS mirror drives. Returns
2184
+ * true only when every step succeeds and the bytes match. Any
2185
+ * throw — the trap a non-suspending async backend produces on
2186
+ * first use is a catchable RuntimeError at this boundary — and
2187
+ * any mismatch means the backend cannot serve the working set.
2188
+ * The probe directory is removed again on every path, so a
2189
+ * working backend keeps no trace of it. */
2190
+ function probeOpfsBackend(FS) {
2191
+ if (!FS || typeof FS.writeFile !== 'function' ||
2192
+ typeof FS.readFile !== 'function') {
2193
+ return false;
2194
+ }
2195
+ try {
2196
+ if (typeof FS.mkdirTree === 'function') FS.mkdirTree(OPFS_PROBE_DIR);
2197
+ FS.writeFile(OPFS_PROBE_FILE, OPFS_PROBE_BYTES);
2198
+ const back = FS.readFile(OPFS_PROBE_FILE);
2199
+ if (!back || back.length !== OPFS_PROBE_BYTES.length) return false;
2200
+ for (let i = 0; i < OPFS_PROBE_BYTES.length; i++) {
2201
+ if (back[i] !== OPFS_PROBE_BYTES[i]) return false;
2202
+ }
2203
+ return true;
2204
+ } catch {
2205
+ return false;
2206
+ } finally {
2207
+ try { FS.unlink(OPFS_PROBE_FILE); } catch { /* not there */ }
2208
+ if (typeof FS.rmdir === 'function') {
2209
+ try { FS.rmdir(OPFS_PROBE_DIR); } catch { /* not there */ }
2210
+ }
2211
+ }
2212
+ }
2213
+
2119
2214
  async function tryMountOpfsBackend(native, bridge) {
2120
2215
  const canMemo =
2121
2216
  native !== null &&
@@ -2146,8 +2241,9 @@ async function tryMountOpfsBackend(native, bridge) {
2146
2241
  { async: true }
2147
2242
  );
2148
2243
  // wasmfs_create_directory returns 0 on success and a
2149
- // negative errno on failure, like mkdir.
2150
- if (rc === 0) result = 'opfs';
2244
+ // negative errno on failure, like mkdir. A mounted backend
2245
+ // still has to survive the probe before it is reported.
2246
+ if (rc === 0 && probeOpfsBackend(native.FS)) result = 'opfs';
2151
2247
  }
2152
2248
  }
2153
2249
  } catch {
package/package.json CHANGED
@@ -1 +1 @@
1
- {"browser":"./index.mjs","description":"TinyC (TCC) in the browser: the compiler built to WebAssembly, one module per code generation target (wasm32-wasi by default), with a JS glue layer, a virtual filesystem and a Web Worker interface.","exports":{".":"./index.mjs","./package.json":"./package.json","./sysroot-manifest":"./sysroot-manifest.json","./sysroot-manifests/*":"./sysroot-manifests/*","./worker":"./worker.mjs"},"files":["README.md","README.zh-CN.md","index.mjs","vfs-store.mjs","tinyc-web.js","worker.mjs","sysroot-manifest.json","sysroot-manifests","tcc-*.mjs","tcc-*.wasm"],"keywords":["tcc","tinycc","compiler","wasm","webassembly","browser","cross-compiler"],"license":"LGPL-2.1-or-later","main":"./index.mjs","module":"./index.mjs","name":"tinyc-web","scripts":{"build":"./build.sh","build:web":"node build-web-bundle.mjs","test":"node --test test.mjs","test:web":"node --test test-web-bundle.mjs"},"type":"module","version":"0.1.1"}
1
+ {"browser":"./index.mjs","description":"TinyC (TCC) in the browser: the compiler built to WebAssembly, one module per code generation target (wasm32-wasi by default), with a JS glue layer, a virtual filesystem and a Web Worker interface.","exports":{".":"./index.mjs","./package.json":"./package.json","./sysroot-manifest":"./sysroot-manifest.json","./sysroot-manifests/*":"./sysroot-manifests/*","./worker":"./worker.mjs"},"files":["README.md","README.zh-CN.md","index.mjs","vfs-store.mjs","tinyc-web.js","worker.mjs","sysroot-manifest.json","sysroot-manifests","tcc-*.mjs","tcc-*.wasm"],"keywords":["tcc","tinycc","compiler","wasm","webassembly","browser","cross-compiler"],"license":"LGPL-2.1-or-later","main":"./index.mjs","module":"./index.mjs","name":"tinyc-web","scripts":{"build":"./build.sh","build:web":"node build-web-bundle.mjs","test":"node --test test.mjs","test:web":"node --test test-web-bundle.mjs"},"type":"module","version":"0.1.3"}
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/tinyc-web.js CHANGED
@@ -2247,6 +2247,12 @@ var TinycWeb = (() => {
2247
2247
  const nativePath = this._nativePath(path);
2248
2248
  const dir = nativePath.slice(0, nativePath.lastIndexOf("/")) || "/";
2249
2249
  if (typeof FS.mkdirTree === "function") FS.mkdirTree(dir);
2250
+ if (typeof FS.unlink === "function") {
2251
+ try {
2252
+ FS.unlink(nativePath);
2253
+ } catch {
2254
+ }
2255
+ }
2250
2256
  FS.writeFile(nativePath, bytes);
2251
2257
  }
2252
2258
  };
@@ -2768,10 +2774,16 @@ var TinycWeb = (() => {
2768
2774
  this.handle = handle;
2769
2775
  this._io = null;
2770
2776
  this._deleted = false;
2777
+ this._outputTypeSet = false;
2771
2778
  }
2772
2779
  _call(name, returnType, argTypes, args) {
2773
2780
  if (this._deleted) throw new TinycError("tinyc: state already deleted");
2774
- return this._bridge.call(name, returnType, argTypes, [this.handle, ...args]);
2781
+ return this._bridge.call(
2782
+ name,
2783
+ returnType,
2784
+ ["number", ...argTypes],
2785
+ [this.handle, ...args]
2786
+ );
2775
2787
  }
2776
2788
  _checkRc(name, rc) {
2777
2789
  if (typeof rc === "number" && rc < 0) {
@@ -2858,10 +2870,23 @@ var TinycWeb = (() => {
2858
2870
  return this;
2859
2871
  }
2860
2872
  setOutputType(type) {
2861
- return this._checkRc(
2873
+ const rc = this._checkRc(
2862
2874
  "tcc_set_output_type",
2863
2875
  this._call("tcc_set_output_type", "number", ["number"], [type])
2864
2876
  );
2877
+ this._outputTypeSet = true;
2878
+ return rc;
2879
+ }
2880
+ /* tcc_set_output_type is not a plain setter in libtcc: it also
2881
+ * creates the state's ELF sections (tccelf_new), and upstream's
2882
+ * contract is that it MUST be called before any compilation —
2883
+ * compiling without it runs tccelf_end_file over sections that
2884
+ * do not exist and traps inside put_elf_sym. Establish the
2885
+ * MEMORY default lazily, exactly once, at the first compiling
2886
+ * entry point; an explicit setOutputType beforehand suppresses
2887
+ * the default, and tccelf_new is never run twice on one state. */
2888
+ _ensureOutputType() {
2889
+ if (!this._outputTypeSet) this.setOutputType(TCC_OUTPUT.MEMORY);
2865
2890
  }
2866
2891
  /** Add a file (source, object or archive) by virtual path. The file
2867
2892
  * must exist in the instance's virtual FS; it is synced to the
@@ -2875,12 +2900,14 @@ var TinycWeb = (() => {
2875
2900
  throw new TinycError(`tinyc: addFile: ${p} is not in the virtual FS`);
2876
2901
  }
2877
2902
  this._instance.fs.syncFile(p);
2903
+ this._ensureOutputType();
2878
2904
  return this._checkRc(
2879
2905
  "tcc_add_file",
2880
2906
  this._call("tcc_add_file", "number", ["string"], [this._bridge.modulePath(p)])
2881
2907
  );
2882
2908
  }
2883
2909
  compileString(source) {
2910
+ this._ensureOutputType();
2884
2911
  return this._checkRc(
2885
2912
  "tcc_compile_string",
2886
2913
  this._call("tcc_compile_string", "number", ["string"], [source])
@@ -2897,6 +2924,7 @@ var TinycWeb = (() => {
2897
2924
  const src = this._instance.fs.readTextFile(p);
2898
2925
  const marked = `#line 1 "${p}"
2899
2926
  ${src}`;
2927
+ this._ensureOutputType();
2900
2928
  return this._checkRc(
2901
2929
  "tcc_compile_string",
2902
2930
  this._call("tcc_compile_string", "number", ["string"], [marked])
@@ -3138,14 +3166,6 @@ ${src}`;
3138
3166
  * read fails naming exportFileAsync as the alternative. */
3139
3167
  exportFile(path) {
3140
3168
  const p = normalizeVfsPath(path);
3141
- let cacheMiss = null;
3142
- if (this.fs.hasFile(p)) {
3143
- try {
3144
- return this.fs.readFile(p);
3145
- } catch (err) {
3146
- cacheMiss = err;
3147
- }
3148
- }
3149
3169
  const FS = this._bridge.native?.FS;
3150
3170
  if (FS && typeof FS.readFile === "function") {
3151
3171
  try {
@@ -3155,10 +3175,14 @@ ${src}`;
3155
3175
  } catch {
3156
3176
  }
3157
3177
  }
3158
- if (cacheMiss) {
3159
- throw new TinycError(
3160
- `tinyc: ${p} is persisted in the virtual FS store but is not in the in-memory cache; read it with exportFileAsync() instead`
3161
- );
3178
+ if (this.fs.hasFile(p)) {
3179
+ try {
3180
+ return this.fs.readFile(p);
3181
+ } catch {
3182
+ throw new TinycError(
3183
+ `tinyc: ${p} is persisted in the virtual FS store but is not in the in-memory cache; read it with exportFileAsync() instead`
3184
+ );
3185
+ }
3162
3186
  }
3163
3187
  throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
3164
3188
  }
@@ -3166,7 +3190,6 @@ ${src}`;
3166
3190
  * when it is not in the content cache. */
3167
3191
  async exportFileAsync(path) {
3168
3192
  const p = normalizeVfsPath(path);
3169
- if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
3170
3193
  const FS = this._bridge.native?.FS;
3171
3194
  if (FS && typeof FS.readFile === "function") {
3172
3195
  try {
@@ -3176,6 +3199,7 @@ ${src}`;
3176
3199
  } catch {
3177
3200
  }
3178
3201
  }
3202
+ if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
3179
3203
  throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
3180
3204
  }
3181
3205
  /** exportFile as a Blob, e.g. for a download link or a File
@@ -3335,6 +3359,9 @@ ${src}`;
3335
3359
  const state = new TinycState(this, handle ?? {});
3336
3360
  this._states.add(state);
3337
3361
  state._installErrorFunc();
3362
+ if (isRunnableTarget(this.target)) {
3363
+ state.setOptions("-nostdlib");
3364
+ }
3338
3365
  if (this._bridge.has("tcc_add_include_path")) {
3339
3366
  for (const dir of this.fs.getIncludeDirs()) state.addIncludePath(dir);
3340
3367
  }
@@ -3448,6 +3475,37 @@ ${src}`;
3448
3475
  }
3449
3476
  var OPFS_MOUNT_POINT = "/opfs";
3450
3477
  var opfsBackendByModule = /* @__PURE__ */ new WeakMap();
3478
+ var OPFS_PROBE_DIR = OPFS_MOUNT_POINT + "/.tinyc-probe";
3479
+ var OPFS_PROBE_FILE = OPFS_PROBE_DIR + "/probe";
3480
+ var OPFS_PROBE_BYTES = new Uint8Array([116, 105, 110, 121, 99]);
3481
+ function probeOpfsBackend(FS) {
3482
+ if (!FS || typeof FS.writeFile !== "function" || typeof FS.readFile !== "function") {
3483
+ return false;
3484
+ }
3485
+ try {
3486
+ if (typeof FS.mkdirTree === "function") FS.mkdirTree(OPFS_PROBE_DIR);
3487
+ FS.writeFile(OPFS_PROBE_FILE, OPFS_PROBE_BYTES);
3488
+ const back = FS.readFile(OPFS_PROBE_FILE);
3489
+ if (!back || back.length !== OPFS_PROBE_BYTES.length) return false;
3490
+ for (let i = 0; i < OPFS_PROBE_BYTES.length; i++) {
3491
+ if (back[i] !== OPFS_PROBE_BYTES[i]) return false;
3492
+ }
3493
+ return true;
3494
+ } catch {
3495
+ return false;
3496
+ } finally {
3497
+ try {
3498
+ FS.unlink(OPFS_PROBE_FILE);
3499
+ } catch {
3500
+ }
3501
+ if (typeof FS.rmdir === "function") {
3502
+ try {
3503
+ FS.rmdir(OPFS_PROBE_DIR);
3504
+ } catch {
3505
+ }
3506
+ }
3507
+ }
3508
+ }
3451
3509
  async function tryMountOpfsBackend(native, bridge) {
3452
3510
  const canMemo = native !== null && (typeof native === "object" || typeof native === "function");
3453
3511
  if (canMemo) {
@@ -3472,7 +3530,7 @@ ${src}`;
3472
3530
  [OPFS_MOUNT_POINT, 511, backend],
3473
3531
  { async: true }
3474
3532
  );
3475
- if (rc === 0) result = "opfs";
3533
+ if (rc === 0 && probeOpfsBackend(native.FS)) result = "opfs";
3476
3534
  }
3477
3535
  }
3478
3536
  } catch {