wasm-idle 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +250 -146
- package/dist/container/clang-runtime.js +32 -8
- package/dist/container/runtime-adapter.d.ts +2 -0
- package/dist/container/runtime-adapter.js +37 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/playground/assetBridge.js +10 -8
- package/dist/playground/assets.d.ts +4 -0
- package/dist/playground/assets.js +9 -4
- package/dist/playground/c3.js +1 -1
- package/dist/playground/compiledLldb.d.ts +2 -0
- package/dist/playground/compiledLldb.js +37 -2
- package/dist/playground/d.d.ts +1 -0
- package/dist/playground/d.js +18 -8
- package/dist/playground/index.d.ts +1 -1
- package/dist/playground/index.js +7 -0
- package/dist/playground/{java-debug-FMHDKUN6.js → java-debug-64JGCLTC.js} +1 -1
- package/dist/playground/java-debug-notices.txt +26 -1
- package/dist/playground/java.js +3 -2
- package/dist/playground/javaDebugBridge.js +42 -7
- package/dist/playground/javaDebugSource.js +4 -4
- package/dist/playground/javaMain.d.ts +3 -0
- package/dist/playground/javaMain.js +2 -0
- package/dist/playground/javaRuntimeErrors.d.ts +2 -1
- package/dist/playground/javaRuntimeErrors.js +9 -2
- package/dist/playground/javaSource.d.ts +1 -1
- package/dist/playground/javaSource.js +7 -2
- package/dist/playground/lldbSession.d.ts +2 -0
- package/dist/playground/lldbSession.js +60 -4
- package/dist/playground/objectivec.d.ts +1 -1
- package/dist/playground/objectivec.js +2 -1
- package/dist/playground/options.d.ts +1 -1
- package/dist/playground/python.d.ts +3 -0
- package/dist/playground/python.js +122 -2
- package/dist/playground/pythonCompileOptions.d.ts +52 -0
- package/dist/playground/pythonCompileOptions.js +40 -0
- package/dist/playground/scala.d.ts +34 -0
- package/dist/playground/scala.js +397 -0
- package/dist/playground/scalaAssets.d.ts +16 -0
- package/dist/playground/scalaAssets.js +51 -0
- package/dist/playground/scalaDiagnostics.d.ts +3 -0
- package/dist/playground/scalaDiagnostics.js +29 -0
- package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
- package/dist/playground/staticRuntimeModuleVersion.js +1 -1
- package/dist/playground/staticWorkerRuntime.d.ts +2 -0
- package/dist/playground/staticWorkerRuntime.js +85 -11
- package/dist/playground/tinygo.js +21 -8
- package/dist/playground/tinygoExecutableGraph.js +1 -1
- package/dist/playground/v.d.ts +1 -0
- package/dist/playground/v.js +17 -7
- package/dist/playground/wasmC3Version.d.ts +8 -8
- package/dist/playground/wasmC3Version.js +8 -8
- package/dist/playground/wasmDebugVersion.d.ts +1 -1
- package/dist/playground/wasmDebugVersion.js +1 -1
- package/dist/playground/wasmDotnetVersion.d.ts +1 -1
- package/dist/playground/wasmDotnetVersion.js +1 -1
- package/dist/playground/wasmGoVersion.d.ts +1 -1
- package/dist/playground/wasmGoVersion.js +1 -1
- package/dist/playground/wasmLispVersion.d.ts +5 -0
- package/dist/playground/wasmLispVersion.js +5 -0
- package/dist/playground/wasmOcamlVersion.d.ts +4 -4
- package/dist/playground/wasmOcamlVersion.js +3 -3
- package/dist/playground/wasmPrologVersion.d.ts +17 -17
- package/dist/playground/wasmPrologVersion.js +16 -16
- package/dist/playground/wasmTinyGoVersion.d.ts +57 -57
- package/dist/playground/wasmTinyGoVersion.js +57 -57
- package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
- package/dist/playground/wasmTypeScriptVersion.js +3 -3
- package/dist/playground/wasmZigVersion.d.ts +7 -7
- package/dist/playground/wasmZigVersion.js +7 -7
- package/dist/playground/worker/java.js +18 -4
- package/dist/playground/worker/javaDebugEvaluator.js +2 -2
- package/dist/playground/worker/javaDebugRuntime.js +8 -1
- package/dist/playground/worker/javaStreaming.js +4 -2
- package/dist/playground/worker/ocaml.js +11 -10
- package/dist/playground/worker/python.js +45 -165
- package/dist/playground/worker/pythonCompile.d.ts +4 -0
- package/dist/playground/worker/pythonCompile.js +127 -0
- package/dist/playground/worker/pythonDebug.d.ts +20 -0
- package/dist/playground/worker/pythonDebug.js +205 -0
- package/dist/playground/worker/scala/UPSTREAM-LICENSE.txt +201 -0
- package/dist/playground/worker/scala/UPSTREAM-NOTICE.txt +108 -0
- package/dist/playground/worker/scala/asset-bootstrap.d.ts +6 -0
- package/dist/playground/worker/scala/asset-bootstrap.js +58 -0
- package/dist/playground/worker/scala/asset-receipts.d.ts +7 -0
- package/dist/playground/worker/scala/asset-receipts.js +58 -0
- package/dist/playground/worker/scala/compiler.worker.d.ts +1 -0
- package/dist/playground/worker/scala/compiler.worker.js +204 -0
- package/dist/playground/worker/scala/execution.worker.d.ts +1 -0
- package/dist/playground/worker/scala/execution.worker.js +89 -0
- package/dist/playground/worker/scala/memory-fs.d.ts +29 -0
- package/dist/playground/worker/scala/memory-fs.js +333 -0
- package/dist/playground/worker/scala/runner.d.ts +1 -0
- package/dist/playground/worker/scala/runner.js +36 -0
- package/dist/playground/worker/zig.d.ts +2 -1
- package/dist/playground/worker/zig.js +212 -86
- package/dist/playground/worker/zigDebug.d.ts +39 -0
- package/dist/playground/worker/zigDebug.js +156 -0
- package/dist/playground/zig.d.ts +27 -4
- package/dist/playground/zig.js +266 -23
- package/dist/playground/zigDebugValues.d.ts +20 -0
- package/dist/playground/zigDebugValues.js +248 -0
- package/dist/pythonCompiler.d.ts +8 -0
- package/dist/pythonCompiler.js +52 -0
- package/package.json +37 -26
|
@@ -3,6 +3,7 @@ import { type ZigExecutionAssetReceipt } from '../zigAssets';
|
|
|
3
3
|
interface ZigStdlibArchiveLimits {
|
|
4
4
|
maxExpandedBytes?: number;
|
|
5
5
|
maxFiles?: number;
|
|
6
|
+
signal?: AbortSignal;
|
|
6
7
|
}
|
|
7
|
-
export declare function
|
|
8
|
+
export declare function loadLibDirectory(source: Uint8Array, assetUrl: string, limits?: ZigStdlibArchiveLimits, receipt?: ZigExecutionAssetReceipt): Promise<Directory>;
|
|
8
9
|
export {};
|
|
@@ -5,8 +5,8 @@ import { waitForBufferedStdin } from '../stdinBuffer';
|
|
|
5
5
|
import { snapshotZigExecutionAssetReceipts } from '../zigAssets';
|
|
6
6
|
import { fetchRuntimeAssetBytes, resolveRuntimeAssetUrl } from './runtimeAssetFetch';
|
|
7
7
|
const encoder = new TextEncoder();
|
|
8
|
-
const DEFAULT_ZIG_STDLIB_MAX_EXPANDED_BYTES =
|
|
9
|
-
const DEFAULT_ZIG_STDLIB_MAX_FILES =
|
|
8
|
+
const DEFAULT_ZIG_STDLIB_MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
|
9
|
+
const DEFAULT_ZIG_STDLIB_MAX_FILES = 32768;
|
|
10
10
|
const DEFAULT_ZIP_FILE_BUFFER_BYTES = 64 * 1024;
|
|
11
11
|
let stdinBufferZig = null;
|
|
12
12
|
let stdinChunkZig = new Uint8Array(0);
|
|
@@ -20,6 +20,19 @@ let assetIntegrity = null;
|
|
|
20
20
|
let runtimeMaxAssetBytes = 0;
|
|
21
21
|
let compiledArtifact = null;
|
|
22
22
|
let compiledCacheKey = '';
|
|
23
|
+
// std.Io first attempts positional I/O, then switches to streaming on ESPIPE.
|
|
24
|
+
// The base shim returns NOTSUP, which Zig reports as an unexpected I/O error.
|
|
25
|
+
class ZigStdout extends ConsoleStdout {
|
|
26
|
+
fd_pwrite(_data, _offset) {
|
|
27
|
+
return { ret: wasi.ERRNO_SPIPE, nwritten: 0 };
|
|
28
|
+
}
|
|
29
|
+
fd_seek(_offset, _whence) {
|
|
30
|
+
return { ret: wasi.ERRNO_SPIPE, offset: 0n };
|
|
31
|
+
}
|
|
32
|
+
fd_tell() {
|
|
33
|
+
return { ret: wasi.ERRNO_SPIPE, offset: 0n };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
23
36
|
class ZigStdin extends Fd {
|
|
24
37
|
initialStdin;
|
|
25
38
|
hasInitialStdin;
|
|
@@ -42,6 +55,15 @@ class ZigStdin extends Fd {
|
|
|
42
55
|
filestat: new wasi.Filestat(0n, wasi.FILETYPE_CHARACTER_DEVICE, 0n)
|
|
43
56
|
};
|
|
44
57
|
}
|
|
58
|
+
fd_pread(_size, _offset) {
|
|
59
|
+
return { ret: wasi.ERRNO_SPIPE, data: new Uint8Array(0) };
|
|
60
|
+
}
|
|
61
|
+
fd_seek(_offset, _whence) {
|
|
62
|
+
return { ret: wasi.ERRNO_SPIPE, offset: 0n };
|
|
63
|
+
}
|
|
64
|
+
fd_tell() {
|
|
65
|
+
return { ret: wasi.ERRNO_SPIPE, offset: 0n };
|
|
66
|
+
}
|
|
45
67
|
fd_read(size) {
|
|
46
68
|
if (stdinChunkOffsetZig >= stdinChunkZig.length) {
|
|
47
69
|
const nextChunk = this.readNextChunk();
|
|
@@ -130,20 +152,24 @@ function buildWorkspaceRoot(code, activePath, workspaceFiles) {
|
|
|
130
152
|
const root = new Directory(new Map());
|
|
131
153
|
const entryPath = normalizeWorkspacePath(activePath || 'main.zig');
|
|
132
154
|
for (const file of workspaceFiles) {
|
|
133
|
-
if (!file || typeof file.path !== 'string'
|
|
155
|
+
if (!file || typeof file.path !== 'string')
|
|
156
|
+
continue;
|
|
157
|
+
const content = file.path === activePath ? code : file.content;
|
|
158
|
+
if (typeof content !== 'string' && !(content instanceof Uint8Array))
|
|
134
159
|
continue;
|
|
135
|
-
addFileToDirectory(root, file.path,
|
|
160
|
+
addFileToDirectory(root, file.path, typeof content === 'string' ? encoder.encode(content) : content);
|
|
136
161
|
}
|
|
137
162
|
addFileToDirectory(root, entryPath, encoder.encode(code));
|
|
138
163
|
return { root, entryPath };
|
|
139
164
|
}
|
|
140
|
-
async function fetchBytes(url, asset, maxAssetBytes, progressStart, progressEnd, expected) {
|
|
165
|
+
async function fetchBytes(url, asset, maxAssetBytes, progressStart, progressEnd, expected, signal) {
|
|
141
166
|
const data = await fetchRuntimeAssetBytes({
|
|
142
167
|
url,
|
|
143
168
|
label: asset,
|
|
144
169
|
expected,
|
|
145
170
|
integrityContext: { asset, runtimeId: 'ZIG' },
|
|
146
171
|
maxAssetBytes,
|
|
172
|
+
signal,
|
|
147
173
|
onProgress: ({ loaded, total }) => {
|
|
148
174
|
if (total && total > 0) {
|
|
149
175
|
postProgress(progressStart + ((progressEnd - progressStart) * loaded) / total);
|
|
@@ -160,6 +186,7 @@ class ZigStdlibArchiveBudget {
|
|
|
160
186
|
expandedBytes = 0;
|
|
161
187
|
fileCount = 0;
|
|
162
188
|
entries = new Map();
|
|
189
|
+
archiveRoot = null;
|
|
163
190
|
constructor(maxExpandedBytes, maxFiles) {
|
|
164
191
|
this.maxExpandedBytes = maxExpandedBytes;
|
|
165
192
|
this.maxFiles = maxFiles;
|
|
@@ -230,16 +257,22 @@ class ZigStdlibArchiveBudget {
|
|
|
230
257
|
throw new Error(`Zig standard library archive has an unsafe path: ${path}`);
|
|
231
258
|
}
|
|
232
259
|
const normalized = parts.join('/');
|
|
233
|
-
if (
|
|
234
|
-
throw new Error(`Zig standard library archive path is outside std/: ${path}`);
|
|
260
|
+
if (parts[0] !== 'lib' && parts[0] !== 'std') {
|
|
261
|
+
throw new Error(`Zig standard library archive path is outside lib/ or std/: ${path}`);
|
|
262
|
+
}
|
|
263
|
+
if (this.archiveRoot && this.archiveRoot !== parts[0]) {
|
|
264
|
+
throw new Error('Zig standard library archive must use a single lib/ or std/ root');
|
|
235
265
|
}
|
|
236
|
-
|
|
266
|
+
this.archiveRoot = parts[0];
|
|
267
|
+
if (!directory && parts.length === 1) {
|
|
237
268
|
throw new Error(`Zig standard library archive has an unsafe file path: ${path}`);
|
|
238
269
|
}
|
|
239
270
|
return normalized;
|
|
240
271
|
}
|
|
241
272
|
}
|
|
242
|
-
export async function
|
|
273
|
+
export async function loadLibDirectory(source, assetUrl, limits = {}, receipt) {
|
|
274
|
+
const signal = limits.signal;
|
|
275
|
+
signal?.throwIfAborted();
|
|
243
276
|
const maxExpandedBytes = limits.maxExpandedBytes ?? DEFAULT_ZIG_STDLIB_MAX_EXPANDED_BYTES;
|
|
244
277
|
const maxFiles = limits.maxFiles ?? DEFAULT_ZIG_STDLIB_MAX_FILES;
|
|
245
278
|
if (!Number.isSafeInteger(maxExpandedBytes) || maxExpandedBytes <= 0) {
|
|
@@ -255,6 +288,7 @@ export async function loadStdDirectory(source, assetUrl, limits = {}, receipt) {
|
|
|
255
288
|
throw new Error('Zig receipt-backed standard library must be a gzip archive or TAR');
|
|
256
289
|
}
|
|
257
290
|
const { Unzip, UnzipInflate } = await import('fflate');
|
|
291
|
+
signal?.throwIfAborted();
|
|
258
292
|
let archiveError;
|
|
259
293
|
const unzip = new Unzip((file) => {
|
|
260
294
|
const stopFile = (error) => {
|
|
@@ -337,9 +371,11 @@ export async function loadStdDirectory(source, assetUrl, limits = {}, receipt) {
|
|
|
337
371
|
runtimeId: 'ZIG'
|
|
338
372
|
});
|
|
339
373
|
}
|
|
374
|
+
signal?.throwIfAborted();
|
|
340
375
|
const expanded = sourceIsGzip
|
|
341
|
-
? await decompressGzip(source, assetUrl, maxExpandedBytes)
|
|
376
|
+
? await decompressGzip(source, assetUrl, maxExpandedBytes, signal)
|
|
342
377
|
: source;
|
|
378
|
+
signal?.throwIfAborted();
|
|
343
379
|
if (receipt) {
|
|
344
380
|
await verifyRuntimeAssetIntegrity({
|
|
345
381
|
asset: 'std.tar.gz',
|
|
@@ -349,6 +385,7 @@ export async function loadStdDirectory(source, assetUrl, limits = {}, receipt) {
|
|
|
349
385
|
runtimeId: 'ZIG'
|
|
350
386
|
});
|
|
351
387
|
}
|
|
388
|
+
signal?.throwIfAborted();
|
|
352
389
|
untar(expanded, {
|
|
353
390
|
addDirectory(directoryPath) {
|
|
354
391
|
budget.addDirectory(directoryPath);
|
|
@@ -360,11 +397,18 @@ export async function loadStdDirectory(source, assetUrl, limits = {}, receipt) {
|
|
|
360
397
|
}
|
|
361
398
|
});
|
|
362
399
|
}
|
|
363
|
-
const
|
|
364
|
-
if (
|
|
365
|
-
|
|
400
|
+
const libDirectory = root.contents.get('lib');
|
|
401
|
+
if (libDirectory instanceof Directory) {
|
|
402
|
+
if (!(libDirectory.contents.get('std') instanceof Directory)) {
|
|
403
|
+
throw new Error('Zig library archive must contain lib/std/');
|
|
404
|
+
}
|
|
405
|
+
return libDirectory;
|
|
406
|
+
}
|
|
407
|
+
if (!(root.contents.get('std') instanceof Directory)) {
|
|
408
|
+
throw new Error('Zig standard library archive must contain lib/std/ or std/');
|
|
366
409
|
}
|
|
367
|
-
|
|
410
|
+
// Legacy std-only bundles are already a valid /lib tree.
|
|
411
|
+
return root;
|
|
368
412
|
}
|
|
369
413
|
function postProgress(percent) {
|
|
370
414
|
postMessage({ progress: { percent: Math.max(0, Math.min(100, percent)) } });
|
|
@@ -398,22 +442,34 @@ async function loadAssets(nextCompilerUrl, nextStdlibUrl, nextIntegrity, maxAsse
|
|
|
398
442
|
return await loadingAssets.promise;
|
|
399
443
|
const pending = (async () => {
|
|
400
444
|
postProgress(5);
|
|
401
|
-
const
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
445
|
+
const controller = new AbortController();
|
|
446
|
+
try {
|
|
447
|
+
// Each asset can finish verification and preparation while its peer is downloading.
|
|
448
|
+
// Observe both branches together so a failure cancels outstanding sibling I/O.
|
|
449
|
+
const [compilerModule, libDirectory] = await Promise.all([
|
|
450
|
+
(async () => {
|
|
451
|
+
const compilerBytes = await fetchBytes(nextCompilerUrl, 'zig_small.wasm', receipts['zig_small.wasm'].bytes, 5, 45, receipts['zig_small.wasm'], controller.signal);
|
|
452
|
+
await verifyRuntimeAssetIntegrity({
|
|
453
|
+
asset: 'zig_small.wasm',
|
|
454
|
+
bytes: compilerBytes,
|
|
455
|
+
expected: receipts['zig_small.wasm'],
|
|
456
|
+
runtimeId: 'ZIG'
|
|
457
|
+
});
|
|
458
|
+
controller.signal.throwIfAborted();
|
|
459
|
+
return WebAssembly.compile(compilerBytes);
|
|
460
|
+
})(),
|
|
461
|
+
(async () => {
|
|
462
|
+
const stdlibBytes = await fetchBytes(nextStdlibUrl, 'std.tar.gz', Math.max(receipts['std.tar.gz'].bytes, receipts['std.tar.gz'].uncompressedBytes || 0), 45, 70, receipts['std.tar.gz'], controller.signal);
|
|
463
|
+
return loadLibDirectory(stdlibBytes, nextStdlibUrl, { maxExpandedBytes: maxAssetBytes, signal: controller.signal }, receipts['std.tar.gz']);
|
|
464
|
+
})()
|
|
465
|
+
]);
|
|
466
|
+
postProgress(100);
|
|
467
|
+
return { compilerModule, libDirectory };
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
controller.abort(error);
|
|
471
|
+
throw error;
|
|
472
|
+
}
|
|
417
473
|
})();
|
|
418
474
|
loadingAssets = { key: nextAssetKey, promise: pending };
|
|
419
475
|
try {
|
|
@@ -436,78 +492,128 @@ async function loadAssets(nextCompilerUrl, nextStdlibUrl, nextIntegrity, maxAsse
|
|
|
436
492
|
function instantiateResult(result) {
|
|
437
493
|
return result instanceof WebAssembly.Instance ? result : result.instance;
|
|
438
494
|
}
|
|
439
|
-
async function compileZig({ code, activePath, workspaceFiles, targetTriple, compileArgs, log }) {
|
|
495
|
+
async function compileZig({ code, activePath, workspaceFiles, targetTriple, compileArgs, debugBackend, log }) {
|
|
440
496
|
if (!assetIntegrity)
|
|
441
497
|
throw new Error('Zig runtime assets are not loaded');
|
|
442
|
-
const { compilerModule,
|
|
498
|
+
const { compilerModule, libDirectory } = await loadAssets(compilerUrl, stdlibUrl, assetIntegrity, runtimeMaxAssetBytes);
|
|
443
499
|
const { root, entryPath } = buildWorkspaceRoot(code, activePath, workspaceFiles);
|
|
444
|
-
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
'
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
500
|
+
const cache = new Map();
|
|
501
|
+
const emit = async (args, outputPath) => {
|
|
502
|
+
let compilerOutput = '';
|
|
503
|
+
const outputDecoder = new TextDecoder();
|
|
504
|
+
const errorDecoder = new TextDecoder();
|
|
505
|
+
const outputFd = new ZigStdout((chunk) => {
|
|
506
|
+
compilerOutput += outputDecoder.decode(chunk, { stream: true });
|
|
507
|
+
});
|
|
508
|
+
const errorFd = new ZigStdout((chunk) => {
|
|
509
|
+
compilerOutput += errorDecoder.decode(chunk, { stream: true });
|
|
510
|
+
});
|
|
511
|
+
const zigWasi = new WASI(['zigc.wasm', ...args], ['ZIG_LOCAL_CACHE_DIR=.zig-cache/local'], [
|
|
512
|
+
new OpenFile(new File([])),
|
|
513
|
+
outputFd,
|
|
514
|
+
errorFd,
|
|
515
|
+
new PreopenDirectory('.', root.contents),
|
|
516
|
+
new PreopenDirectory('/lib', libDirectory.contents),
|
|
517
|
+
new PreopenDirectory('/cache', cache)
|
|
518
|
+
], { debug: false });
|
|
519
|
+
const instance = instantiateResult(await WebAssembly.instantiate(compilerModule, {
|
|
520
|
+
wasi_snapshot_preview1: zigWasi.wasiImport
|
|
521
|
+
}));
|
|
522
|
+
const exitCode = zigWasi.start(instance);
|
|
523
|
+
compilerOutput += outputDecoder.decode() + errorDecoder.decode();
|
|
524
|
+
if (compilerOutput)
|
|
525
|
+
postMessage({ output: compilerOutput });
|
|
526
|
+
if (exitCode !== 0)
|
|
527
|
+
throw new Error(compilerOutput || `Zig compilation failed with code ${exitCode}`);
|
|
528
|
+
const outputFile = getFile(root, outputPath);
|
|
529
|
+
if (!outputFile?.data?.byteLength)
|
|
530
|
+
throw new Error(`Zig compiler did not emit ${outputPath}`);
|
|
531
|
+
return new Uint8Array(outputFile.data);
|
|
532
|
+
};
|
|
533
|
+
if (log)
|
|
474
534
|
console.log(`[wasm-idle:zig-worker] compile start target=${targetTriple} activePath=${entryPath} bytes=${code.length}`);
|
|
535
|
+
if (!debugBackend) {
|
|
536
|
+
const bytes = await emit([
|
|
537
|
+
'build-exe',
|
|
538
|
+
entryPath,
|
|
539
|
+
'-target',
|
|
540
|
+
targetTriple,
|
|
541
|
+
'-fno-llvm',
|
|
542
|
+
'-fno-lld',
|
|
543
|
+
'-O',
|
|
544
|
+
'fast',
|
|
545
|
+
'-femit-bin=output.wasm',
|
|
546
|
+
...compileArgs
|
|
547
|
+
], 'output.wasm');
|
|
548
|
+
return { bytes };
|
|
549
|
+
}
|
|
550
|
+
const sources = new Map();
|
|
551
|
+
// The container supplies file bytes, including binary @embedFile resources.
|
|
552
|
+
// Only Zig source bytes need a lossless text representation in LLDB.
|
|
553
|
+
const sourceDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
554
|
+
for (const file of workspaceFiles) {
|
|
555
|
+
if (!file || typeof file.path !== 'string')
|
|
556
|
+
continue;
|
|
557
|
+
const path = normalizeWorkspacePath(file.path);
|
|
558
|
+
if (path === entryPath)
|
|
559
|
+
continue;
|
|
560
|
+
if (typeof file.content === 'string')
|
|
561
|
+
sources.set(path, file.content);
|
|
562
|
+
else if (file.content instanceof Uint8Array && path.endsWith('.zig')) {
|
|
563
|
+
try {
|
|
564
|
+
sources.set(path, sourceDecoder.decode(file.content));
|
|
565
|
+
}
|
|
566
|
+
catch (cause) {
|
|
567
|
+
throw new Error(`Zig debug source is not valid UTF-8: /workspace/${path}`, {
|
|
568
|
+
cause
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
475
572
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
}
|
|
493
|
-
|
|
573
|
+
sources.set(entryPath, code);
|
|
574
|
+
const flags = [
|
|
575
|
+
'-target',
|
|
576
|
+
'wasm32-wasi',
|
|
577
|
+
'-mcpu=mvp',
|
|
578
|
+
'-O',
|
|
579
|
+
'debug',
|
|
580
|
+
'-fllvm',
|
|
581
|
+
'-fno-libllvm',
|
|
582
|
+
'-fno-lld',
|
|
583
|
+
'-fno-emit-bin',
|
|
584
|
+
'-fno-compiler-rt'
|
|
585
|
+
];
|
|
586
|
+
const bitcode = await emit(['build-exe', entryPath, ...flags, '-femit-llvm-bc=output.bc'], 'output.bc');
|
|
587
|
+
// Zig's IR-only mode has no implicit compiler_rt link. Supply its matching real implementation.
|
|
588
|
+
const compilerRt = await emit(['build-obj', '/lib/compiler_rt.zig', ...flags, '-femit-llvm-bc=compiler_rt.bc'], 'compiler_rt.bc');
|
|
589
|
+
const { compileZigDebugArtifact } = await import('./zigDebug');
|
|
590
|
+
const debug = await compileZigDebugArtifact({
|
|
591
|
+
bitcode: [bitcode, compilerRt],
|
|
592
|
+
sources: [...sources]
|
|
593
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
594
|
+
.map(([path, content]) => ({ path: `/workspace/${path}`, content })),
|
|
595
|
+
zigReceipts: assetIntegrity,
|
|
596
|
+
backend: debugBackend,
|
|
597
|
+
log
|
|
598
|
+
});
|
|
599
|
+
return { bytes: debug.bytes, debug };
|
|
494
600
|
}
|
|
495
601
|
async function runZigArtifact({ artifact, args, stdin, log }) {
|
|
496
602
|
stdinChunkZig = new Uint8Array(0);
|
|
497
603
|
stdinChunkOffsetZig = 0;
|
|
498
604
|
const stdoutDecoder = new TextDecoder();
|
|
499
605
|
const stderrDecoder = new TextDecoder();
|
|
500
|
-
const stdout = new
|
|
606
|
+
const stdout = new ZigStdout((chunk) => {
|
|
501
607
|
const text = stdoutDecoder.decode(chunk, { stream: true });
|
|
502
608
|
if (text)
|
|
503
609
|
postMessage({ output: text });
|
|
504
610
|
});
|
|
505
|
-
const stderr = new
|
|
611
|
+
const stderr = new ZigStdout((chunk) => {
|
|
506
612
|
const text = stderrDecoder.decode(chunk, { stream: true });
|
|
507
613
|
if (text)
|
|
508
614
|
postMessage({ output: text });
|
|
509
615
|
});
|
|
510
|
-
const zigWasi = new WASI(['output.wasm', ...args], ['USER=jungol'], [new ZigStdin(stdin, log), stdout, stderr], { debug: false });
|
|
616
|
+
const zigWasi = new WASI(['output.wasm', ...args], ['USER=jungol'], [new ZigStdin(stdin, log), stdout, stderr, new PreopenDirectory('.', new Map())], { debug: false });
|
|
511
617
|
const instance = instantiateResult(await WebAssembly.instantiate(artifact, {
|
|
512
618
|
wasi_snapshot_preview1: zigWasi.wasiImport,
|
|
513
619
|
wasi_unstable: zigWasi.wasiImport
|
|
@@ -539,7 +645,7 @@ async function runZigArtifact({ artifact, args, stdin, log }) {
|
|
|
539
645
|
}
|
|
540
646
|
}
|
|
541
647
|
self.onmessage = async (event) => {
|
|
542
|
-
const { load, compilerUrl: nextCompilerUrl, stdlibUrl: nextStdlibUrl, integrity: nextIntegrity, maxAssetBytes: nextMaxAssetBytes, buffer, code, prepare, args = [], compileArgs = [], stdin, activePath = 'main.zig', workspaceFiles = [], targetTriple = '
|
|
648
|
+
const { load, compilerUrl: nextCompilerUrl, stdlibUrl: nextStdlibUrl, integrity: nextIntegrity, maxAssetBytes: nextMaxAssetBytes, buffer, code, prepare, args = [], compileArgs = [], debugMode = 'none', debugClangPath, debugClangIntegrity, maxWasmMemoryBytes, stdin, activePath = 'main.zig', workspaceFiles = [], targetTriple = 'wasm32-wasi', log } = event.data;
|
|
543
649
|
try {
|
|
544
650
|
if (load) {
|
|
545
651
|
configureRuntimeAssetCache(event.data.persistentCache ?? {});
|
|
@@ -555,13 +661,26 @@ self.onmessage = async (event) => {
|
|
|
555
661
|
postMessage({ load: true });
|
|
556
662
|
return;
|
|
557
663
|
}
|
|
664
|
+
if (debugMode !== 'none' && debugMode !== 'lldb')
|
|
665
|
+
throw new Error(`Unsupported Zig debug mode: ${String(debugMode)}`);
|
|
666
|
+
let debugBackend;
|
|
667
|
+
if (debugMode === 'lldb') {
|
|
668
|
+
if (targetTriple !== 'wasm32-wasi')
|
|
669
|
+
throw new Error('Zig LLDB debugging requires wasm32-wasi');
|
|
670
|
+
if (compileArgs.length)
|
|
671
|
+
throw new Error('Zig LLDB debugging does not accept compiler argument overrides');
|
|
672
|
+
const { snapshotZigDebugBackend } = await import('./zigDebug');
|
|
673
|
+
debugBackend = snapshotZigDebugBackend(debugClangPath, debugClangIntegrity, runtimeMaxAssetBytes, maxWasmMemoryBytes);
|
|
674
|
+
}
|
|
558
675
|
stdinBufferZig = new Int32Array(buffer);
|
|
559
676
|
const compileCacheKey = JSON.stringify({
|
|
560
677
|
targetTriple,
|
|
561
678
|
activePath,
|
|
562
679
|
code,
|
|
563
680
|
workspaceFiles,
|
|
564
|
-
compileArgs
|
|
681
|
+
compileArgs,
|
|
682
|
+
debugMode,
|
|
683
|
+
debugBackend
|
|
565
684
|
});
|
|
566
685
|
if (!compiledArtifact || compiledCacheKey !== compileCacheKey) {
|
|
567
686
|
compiledArtifact = await compileZig({
|
|
@@ -570,6 +689,7 @@ self.onmessage = async (event) => {
|
|
|
570
689
|
workspaceFiles,
|
|
571
690
|
targetTriple,
|
|
572
691
|
compileArgs,
|
|
692
|
+
debugBackend,
|
|
573
693
|
log
|
|
574
694
|
});
|
|
575
695
|
compiledCacheKey = compileCacheKey;
|
|
@@ -578,8 +698,14 @@ self.onmessage = async (event) => {
|
|
|
578
698
|
postMessage({ results: true });
|
|
579
699
|
return;
|
|
580
700
|
}
|
|
701
|
+
if (debugMode === 'lldb') {
|
|
702
|
+
if (!compiledArtifact.debug)
|
|
703
|
+
throw new Error('Zig compiler did not return an LLDB artifact');
|
|
704
|
+
postMessage({ lldbArtifact: compiledArtifact.debug });
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
581
707
|
await runZigArtifact({
|
|
582
|
-
artifact: compiledArtifact,
|
|
708
|
+
artifact: compiledArtifact.bytes,
|
|
583
709
|
args,
|
|
584
710
|
stdin,
|
|
585
711
|
log
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type RuntimeAssetIntegrityEntry } from '@wasm-idle/core';
|
|
2
|
+
import type { ZigExecutionAssetReceipts } from '../zigAssets';
|
|
3
|
+
export interface ZigDebugBackend {
|
|
4
|
+
path: string;
|
|
5
|
+
integrity: Readonly<Record<string, RuntimeAssetIntegrityEntry>>;
|
|
6
|
+
maxAssetBytes: number;
|
|
7
|
+
maxWasmMemoryBytes?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface ZigLldbArtifact {
|
|
10
|
+
bytes: Uint8Array;
|
|
11
|
+
descriptor: {
|
|
12
|
+
kind: 'dwarf';
|
|
13
|
+
sourceRoot: '/workspace';
|
|
14
|
+
moduleSha256: string;
|
|
15
|
+
files: {
|
|
16
|
+
path: string;
|
|
17
|
+
contentSha256: string;
|
|
18
|
+
}[];
|
|
19
|
+
compiler: Record<string, unknown>;
|
|
20
|
+
};
|
|
21
|
+
sources: {
|
|
22
|
+
path: string;
|
|
23
|
+
content: string;
|
|
24
|
+
contentSha256: string;
|
|
25
|
+
}[];
|
|
26
|
+
}
|
|
27
|
+
export declare function snapshotZigDebugBackend(path: unknown, integrity: unknown, maxAssetBytes: number, maxWasmMemoryBytes?: number): ZigDebugBackend;
|
|
28
|
+
/** Every backend payload is verified before the existing Clang loader sees it. */
|
|
29
|
+
export declare function createZigDebugBackendFetch(backend: ZigDebugBackend): typeof fetch;
|
|
30
|
+
export declare function compileZigDebugArtifact({ bitcode, sources, zigReceipts, backend, log }: {
|
|
31
|
+
bitcode: readonly Uint8Array[];
|
|
32
|
+
sources: {
|
|
33
|
+
path: string;
|
|
34
|
+
content: string;
|
|
35
|
+
}[];
|
|
36
|
+
zigReceipts: ZigExecutionAssetReceipts;
|
|
37
|
+
backend: ZigDebugBackend;
|
|
38
|
+
log: boolean;
|
|
39
|
+
}): Promise<ZigLldbArtifact>;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { verifyRuntimeAssetIntegrity } from '@wasm-idle/core';
|
|
2
|
+
import { decompressGzip } from '@wasm-idle/llvm-core';
|
|
3
|
+
import { fetchRuntimeAssetBytes, resolveRuntimeAssetUrl } from './runtimeAssetFetch';
|
|
4
|
+
export function snapshotZigDebugBackend(path, integrity, maxAssetBytes, maxWasmMemoryBytes) {
|
|
5
|
+
if (typeof path !== 'string' || !path) {
|
|
6
|
+
throw new Error('Zig LLDB debugging requires a Clang runtime asset URL');
|
|
7
|
+
}
|
|
8
|
+
const base = resolveRuntimeAssetUrl(path, 'Zig debug Clang runtime');
|
|
9
|
+
if (base.search)
|
|
10
|
+
throw new Error('Zig debug Clang runtime URL must not include a query');
|
|
11
|
+
if (!base.pathname.endsWith('/'))
|
|
12
|
+
base.pathname += '/';
|
|
13
|
+
if (!integrity || typeof integrity !== 'object' || Array.isArray(integrity)) {
|
|
14
|
+
throw new Error('Zig LLDB debugging requires verified Clang runtime asset receipts');
|
|
15
|
+
}
|
|
16
|
+
const receipts = Object.create(null);
|
|
17
|
+
for (const [name, entry] of Object.entries(integrity)) {
|
|
18
|
+
const receipt = entry;
|
|
19
|
+
if (!receipt ||
|
|
20
|
+
!Number.isSafeInteger(receipt.bytes) ||
|
|
21
|
+
receipt.bytes <= 0 ||
|
|
22
|
+
typeof receipt.sha256 !== 'string' ||
|
|
23
|
+
!/^[a-f0-9]{64}$/u.test(receipt.sha256) ||
|
|
24
|
+
!Number.isSafeInteger(receipt.uncompressedBytes) ||
|
|
25
|
+
receipt.uncompressedBytes <= 0 ||
|
|
26
|
+
typeof receipt.uncompressedSha256 !== 'string' ||
|
|
27
|
+
!/^[a-f0-9]{64}$/u.test(receipt.uncompressedSha256))
|
|
28
|
+
throw new Error(`Invalid Zig debug Clang runtime asset receipt: ${name}`);
|
|
29
|
+
if (new URL(name, base).href !== `${base.href}${name}` ||
|
|
30
|
+
name.includes('..') ||
|
|
31
|
+
/[?#\\]/u.test(name)) {
|
|
32
|
+
throw new Error(`Invalid Zig debug Clang runtime asset name: ${name}`);
|
|
33
|
+
}
|
|
34
|
+
receipts[name] = Object.freeze({
|
|
35
|
+
bytes: receipt.bytes,
|
|
36
|
+
sha256: receipt.sha256,
|
|
37
|
+
uncompressedBytes: receipt.uncompressedBytes,
|
|
38
|
+
uncompressedSha256: receipt.uncompressedSha256
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
if (!receipts['runtime-manifest.v1.json']) {
|
|
42
|
+
throw new Error('Zig LLDB debugging requires a verified Clang runtime manifest');
|
|
43
|
+
}
|
|
44
|
+
return Object.freeze({
|
|
45
|
+
path: base.href,
|
|
46
|
+
integrity: Object.freeze(receipts),
|
|
47
|
+
maxAssetBytes,
|
|
48
|
+
maxWasmMemoryBytes
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function sha256(bytes) {
|
|
52
|
+
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
53
|
+
}
|
|
54
|
+
/** Every backend payload is verified before the existing Clang loader sees it. */
|
|
55
|
+
export function createZigDebugBackendFetch(backend) {
|
|
56
|
+
return async (input, init) => {
|
|
57
|
+
const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
|
|
58
|
+
const name = url.href.startsWith(backend.path) ? url.href.slice(backend.path.length) : '';
|
|
59
|
+
const receipt = Object.hasOwn(backend.integrity, name)
|
|
60
|
+
? backend.integrity[name]
|
|
61
|
+
: undefined;
|
|
62
|
+
if (!receipt)
|
|
63
|
+
throw new Error(`Unpinned Zig debug Clang runtime asset: ${url.href}`);
|
|
64
|
+
const signal = init?.signal || (input instanceof Request ? input.signal : undefined);
|
|
65
|
+
const delivered = await fetchRuntimeAssetBytes({
|
|
66
|
+
url: url.href,
|
|
67
|
+
label: `Zig debug ${name}`,
|
|
68
|
+
expected: receipt,
|
|
69
|
+
maxAssetBytes: backend.maxAssetBytes,
|
|
70
|
+
signal: signal || undefined,
|
|
71
|
+
integrityContext: { asset: name, runtimeId: 'ZIG' }
|
|
72
|
+
});
|
|
73
|
+
const bytes = delivered[0] === 0x1f && delivered[1] === 0x8b
|
|
74
|
+
? await decompressGzip(delivered, url.href, backend.maxAssetBytes)
|
|
75
|
+
: delivered;
|
|
76
|
+
await verifyRuntimeAssetIntegrity({
|
|
77
|
+
asset: name,
|
|
78
|
+
runtimeId: 'ZIG',
|
|
79
|
+
bytes,
|
|
80
|
+
expected: receipt,
|
|
81
|
+
stage: 'uncompressed'
|
|
82
|
+
});
|
|
83
|
+
return new Response(Uint8Array.from(bytes), {
|
|
84
|
+
headers: {
|
|
85
|
+
'Content-Type': name.endsWith('.json')
|
|
86
|
+
? 'application/json'
|
|
87
|
+
: 'application/octet-stream',
|
|
88
|
+
'Content-Length': String(bytes.byteLength)
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export async function compileZigDebugArtifact({ bitcode, sources, zigReceipts, backend, log }) {
|
|
94
|
+
const { BrowserClangRuntime, loadRuntimeManifest, resolveRuntimeManifestUrl } = await import('@wasm-idle/llvm-core/clang');
|
|
95
|
+
const fetchImpl = createZigDebugBackendFetch(backend);
|
|
96
|
+
const manifest = await loadRuntimeManifest(resolveRuntimeManifestUrl(backend.path), fetchImpl, undefined, backend.maxAssetBytes);
|
|
97
|
+
if (!manifest.compiler.provenance)
|
|
98
|
+
throw new Error('Zig debug backend manifest requires Clang compiler provenance');
|
|
99
|
+
if (backend.integrity['bin/c-sysroot.tar.gz']) {
|
|
100
|
+
manifest.compiler.sysroot.profiles = {
|
|
101
|
+
c: { asset: 'bin/c-sysroot.tar.gz' },
|
|
102
|
+
cppAddon: { asset: 'bin/cpp-addon.tar.gz' }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const runtime = new BrowserClangRuntime({
|
|
106
|
+
runtimeBaseUrl: backend.path,
|
|
107
|
+
manifest,
|
|
108
|
+
fetchImpl,
|
|
109
|
+
maxAssetBytes: backend.maxAssetBytes,
|
|
110
|
+
log,
|
|
111
|
+
persistentCache: false,
|
|
112
|
+
stdout: (output) => {
|
|
113
|
+
if (output)
|
|
114
|
+
postMessage({ output });
|
|
115
|
+
},
|
|
116
|
+
stdin: () => '',
|
|
117
|
+
progress: (percent) => postMessage({ progress: { percent: percent * 100, stage: 'zig-debug-backend' } })
|
|
118
|
+
});
|
|
119
|
+
const bytes = await runtime.compileBitcodeArtifact(bitcode, {
|
|
120
|
+
// Match Zig's WASI linker default; its freestanding target uses a smaller stack.
|
|
121
|
+
stackSizeBytes: 16 * 1024 * 1024,
|
|
122
|
+
maxWasmMemoryBytes: backend.maxWasmMemoryBytes
|
|
123
|
+
});
|
|
124
|
+
const module = await WebAssembly.compile(Uint8Array.from(bytes));
|
|
125
|
+
if (!['.debug_info', '.debug_line'].every((name) => WebAssembly.Module.customSections(module, name).some((section) => section.byteLength))) {
|
|
126
|
+
throw new Error('Zig debug backend did not preserve DWARF source information');
|
|
127
|
+
}
|
|
128
|
+
if (WebAssembly.Module.imports(module).some((entry) => entry.module !== 'wasi_snapshot_preview1')) {
|
|
129
|
+
throw new Error('Zig debug backend left an unresolved non-WASI runtime import');
|
|
130
|
+
}
|
|
131
|
+
const sourceFiles = await Promise.all(sources.map(async (file) => ({
|
|
132
|
+
...file,
|
|
133
|
+
contentSha256: await sha256(new TextEncoder().encode(file.content))
|
|
134
|
+
})));
|
|
135
|
+
const compiler = {
|
|
136
|
+
name: 'zig',
|
|
137
|
+
compilerSha256: zigReceipts['zig_small.wasm'].sha256,
|
|
138
|
+
stdlibSha256: zigReceipts['std.tar.gz'].sha256,
|
|
139
|
+
backend: {
|
|
140
|
+
...manifest.compiler.provenance,
|
|
141
|
+
manifestSha256: backend.integrity['runtime-manifest.v1.json'].sha256,
|
|
142
|
+
assets: backend.integrity
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
return {
|
|
146
|
+
bytes,
|
|
147
|
+
descriptor: {
|
|
148
|
+
kind: 'dwarf',
|
|
149
|
+
sourceRoot: '/workspace',
|
|
150
|
+
moduleSha256: await sha256(bytes),
|
|
151
|
+
files: sourceFiles.map(({ path, contentSha256 }) => ({ path, contentSha256 })),
|
|
152
|
+
compiler
|
|
153
|
+
},
|
|
154
|
+
sources: sourceFiles
|
|
155
|
+
};
|
|
156
|
+
}
|