Debian Codegraph @

wasm/browser/src/filesystem/wasi.js

raw
1 import { encoder, decoder } from "../utils/text-encoders.js";
2 import * as constants from "./constants.js";
3
4 const { normalizePath } = goog.require("goog.string.path");
5
6 /** @define {boolean} */
7 const DEBUG_WASI = goog.define("DEBUG_WASI", false);
8
9 function assertLeadingSlash(path) {
10 return /^\//g.test(path) ? path : `/${path}`;
11 }
12
13 function removeLeadingSlash(path) {
14 return path.replace(/^\//g, "");
15 }
16
17 function shouldOpenReader(rights) {
18 return (
19 (rights & (constants.WASI_RIGHT_FD_READ | constants.WASI_RIGHT_FD_READDIR)) !==
20 goog.global.BigInt(0)
21 );
22 }
23
24 function performanceNowPoly() {
25 if (typeof performance === "undefined" || typeof performance.now === "undefined") {
26 const nowOffset = Date.now();
27 return Date.now() - nowOffset;
28 } else {
29 return performance.now();
30 }
31 }
32
33 function concatUint8Arrays(arrays) {
34 // sum of individual array lengths
35 const totalLength = arrays.reduce((accumulator, value) => accumulator + value.length, 0);
36
37 if (arrays.length === 0) return;
38
39 const result = new Uint8Array(totalLength);
40
41 // for each array - copy it over result
42 // next array is copied right after the previous one
43 let length = 0;
44 for (const array of arrays) {
45 result.set(array, length);
46 length += array.length;
47 }
48
49 return result;
50 }
51
52 export const WASI = function ({ preopens }) {
53 this.fd = Array.from({ length: 4 });
54
55 this.fd[0] = { fd: 0, path: "/dev/stdin", seekPos: goog.global.BigInt(0), buffers: [] };
56 this.fd[1] = { fd: 1, path: "/dev/stdout", seekPos: goog.global.BigInt(0), buffers: [] };
57 this.fd[2] = { fd: 2, path: "/dev/stderr", seekPos: goog.global.BigInt(0), buffers: [] };
58 this.fd[3] = { fd: 3, path: "/", seekPos: goog.global.BigInt(0), buffers: [] };
59
60 this.getMemory = this.getMemory.bind(this);
61 this.CPUTIME_START = 0;
62 };
63
64 /**
65 * @function
66 * @param {!WebAssembly.Instance} instance
67 */
68 WASI.prototype.start = function (instance) {
69 this.CPUTIME_START = performanceNowPoly();
70 const exports = instance.exports;
71 exports._start();
72 };
73
74 /**
75 * @function
76 * @param {!WebAssembly.Module} instance
77 */
78 WASI.prototype.getImports = function (module) {
79 const options = {};
80 const neededImports = WebAssembly.Module.imports(module);
81
82 for (const neededImport of neededImports) {
83 if (neededImport.kind === "function" && neededImport.module.startsWith("wasi_")) {
84 if (typeof options[neededImport.module] !== "object") {
85 options[neededImport.module] = {};
86 }
87 options[neededImport.module][neededImport.name] = this[neededImport.name].bind(this);
88 }
89 }
90
91 return options;
92 };
93
94 /**
95 * @function
96 * @param {!WebAssembly.Memory} memory
97 */
98 WASI.prototype.setMemory = function (memory) {
99 this.memory = memory;
100 };
101
102 /**
103 * @function
104 * @return {DataView}
105 */
106 WASI.prototype.getMemory = function () {
107 if (!this.view || !this.view.buffer || !this.view.buffer.byteLength) {
108 this.view = new DataView(this.memory.buffer);
109 }
110 return this.view;
111 };
112
113 WASI.prototype.msToNs = function (ms) {
114 const msInt = Math.trunc(ms);
115 const decimal = goog.global.BigInt(Math.round((ms - msInt) * 1000000));
116 const ns = goog.global.BigInt(msInt) * goog.global.BigInt(1000000);
117 return ns + decimal;
118 };
119
120 WASI.prototype.now = function (clockId) {
121 switch (clockId) {
122 case constants.WASI_CLOCK_MONOTONIC:
123 // case constants.WASI_CLOCK_REALTIME:
124 return Math.floor(performanceNowPoly());
125 case constants.WASI_CLOCK_REALTIME:
126 return this.msToNs(Date.now());
127 case constants.WASI_CLOCK_PROCESS_CPUTIME_ID:
128 case constants.WASI_CLOCK_THREAD_CPUTIME_ID:
129 // return bindings.hrtime(CPUTIME_START)
130 return Math.floor(performanceNowPoly() - this.CPUTIME_START);
131 default:
132 return 0;
133 }
134 };
135
136 WASI.prototype.args_get = function (argv, argvBuf) {
137 if (DEBUG_WASI) {
138 console.log("args_get", argv, argvBuf, constants);
139 }
140 return constants.WASI_ESUCCESS;
141 };
142 WASI.prototype.args_sizes_get = function (argc, argvBufSize) {
143 if (DEBUG_WASI) {
144 console.log("args_sizes_get", argc, argvBufSize, arguments);
145 }
146 return constants.WASI_ESUCCESS;
147 };
148 WASI.prototype.clock_res_get = function (clockId, resolution) {
149 if (DEBUG_WASI) {
150 console.log("args_get", clockId, resolution, arguments);
151 }
152 return constants.WASI_ESUCCESS;
153 };
154 WASI.prototype.clock_time_get = function (clockId, precision, time) {
155 if (DEBUG_WASI) {
156 console.log("clock_time_get", clockId, precision, time, arguments);
157 }
158 const memory = this.getMemory();
159 const nextTime = this.now(clockId);
160 memory.setBigUint64(time, goog.global.BigInt(nextTime), true);
161 return constants.WASI_ESUCCESS;
162 };
163 WASI.prototype.environ_get = function (environ, environBuf) {
164 if (DEBUG_WASI) {
165 console.log("environ_get", environ, environBuf, arguments);
166 }
167 return constants.WASI_ESUCCESS;
168 };
169 WASI.prototype.environ_sizes_get = function (environCount, environBufSize) {
170 if (DEBUG_WASI) {
171 console.log("environ_sizes_get", environCount, environBufSize, arguments);
172 }
173 return constants.WASI_ESUCCESS;
174 };
175 WASI.prototype.fd_advise = function (fd, offset, length_, advice) {
176 if (DEBUG_WASI) {
177 console.log("fd_advise", fd, offset, length_, advice, arguments);
178 }
179 return constants.WASI_ENOSYS;
180 };
181 WASI.prototype.fd_allocate = function (fd, offset, length_) {
182 if (DEBUG_WASI) {
183 console.log("fd_allocate", fd, offset, length_, arguments);
184 }
185 return constants.WASI_ENOSYS;
186 };
187 WASI.prototype.fd_close = function (fd) {
188 if (DEBUG_WASI) {
189 console.log("fd_close", fd, arguments);
190 }
191
192 return constants.WASI_ESUCCESS;
193 };
194 WASI.prototype.fd_datasync = function (fd) {
195 if (DEBUG_WASI) {
196 console.log("fd_datasync", fd, arguments);
197 }
198 return constants.WASI_ESUCCESS;
199 };
200
201 // always write access in browser scope
202 WASI.prototype.fd_fdstat_get = function (fd, bufPtr) {
203 if (DEBUG_WASI) {
204 console.log("fd_fdstat_get", fd, bufPtr, arguments);
205 }
206
207 const memory = this.getMemory();
208
209 memory.setUint8(bufPtr + 4, constants.WASI_FILETYPE_REGULAR_FILE);
210 memory.setUint16(bufPtr + 2, 0, true);
211 memory.setUint16(bufPtr + 4, 0, true);
212 memory.setBigUint64(bufPtr + 8, goog.global.BigInt(constants.RIGHTS_REGULAR_FILE_BASE), true);
213 memory.setBigUint64(
214 bufPtr + 8 + 8,
215 goog.global.BigInt(constants.RIGHTS_REGULAR_FILE_INHERITING),
216 true,
217 );
218
219 return constants.WASI_ESUCCESS;
220 };
221
222 WASI.prototype.fd_fdstat_set_flags = function (fd, flags) {
223 if (DEBUG_WASI) {
224 console.log("fd_fdstat_set_flags", fd, flags, arguments);
225 }
226 return constants.WASI_ENOSYS;
227 };
228 WASI.prototype.fd_fdstat_set_rights = function (fd, fsRightsBase, fsRightsInheriting) {
229 if (DEBUG_WASI) {
230 console.log("fd_fdstat_set_rights", fd, fsRightsBase, fsRightsInheriting, arguments);
231 }
232 return constants.WASI_ESUCCESS;
233 };
234
235 WASI.prototype.fd_filestat_get = function (fd, bufPtr) {
236 if (DEBUG_WASI) {
237 console.log("fd_filestat_get", fd, bufPtr, arguments);
238 }
239 let filesize = 0;
240
241 if (this.fd[fd]) {
242 filesize = this.fd[fd].buffers.reduce(function (accumulator, uintArray) {
243 return accumulator + uintArray?.byteLength ? uintArray?.byteLength : 0;
244 }, 0);
245 }
246
247 const memory = this.getMemory();
248 memory.setBigUint64(bufPtr, goog.global.BigInt(fd), true);
249 bufPtr += 8;
250 memory.setBigUint64(bufPtr, goog.global.BigInt(fd), true);
251 bufPtr += 8;
252 memory.setUint8(bufPtr, constants.WASI_FILETYPE_REGULAR_FILE);
253 bufPtr += 8;
254 memory.setBigUint64(bufPtr, goog.global.BigInt(1), true);
255 bufPtr += 8;
256 memory.setBigUint64(bufPtr, goog.global.BigInt(filesize), true);
257 bufPtr += 8;
258 memory.setBigUint64(bufPtr, this.msToNs(this.CPUTIME_START), true);
259 bufPtr += 8;
260 memory.setBigUint64(bufPtr, this.msToNs(this.CPUTIME_START), true);
261 bufPtr += 8;
262 memory.setBigUint64(bufPtr, this.msToNs(this.CPUTIME_START), true);
263
264 return constants.WASI_ESUCCESS;
265 };
266
267 WASI.prototype.fd_filestat_set_size = function (fd, newSize) {
268 if (DEBUG_WASI) {
269 console.log("fd_filestat_set_size", fd, newSize, arguments);
270 }
271 return constants.WASI_ESUCCESS;
272 };
273
274 WASI.prototype.fd_filestat_set_times = function (fd, stAtim, stMtim, filestatFags) {
275 if (DEBUG_WASI) {
276 console.log("fd_filestat_set_times", fd, stAtim, stMtim, filestatFags, arguments);
277 }
278 return constants.WASI_ESUCCESS;
279 };
280
281 WASI.prototype.fd_pread = function (fd, iovs, iovsLength, offset, nread) {
282 if (DEBUG_WASI) {
283 console.log("fd_pread", fd, iovs, iovsLength, offset, nread, arguments);
284 }
285 return constants.WASI_ESUCCESS;
286 };
287
288 WASI.prototype.fd_prestat_dir_name = function (fd, pathPtr, pathLength) {
289 if (DEBUG_WASI) {
290 console.log("fd_prestat_dir_name", fd, pathPtr, pathLength, this.fd[fd]);
291 }
292 if (!this.fd[fd] && !this.fd[fd - 1]) {
293 return constants.WASI_EBADF;
294 }
295
296 const { path: directoryName } = this.fd[fd];
297
298 const memory = this.getMemory();
299
300 const directoryNameBuffer = encoder.encode(directoryName);
301 new Uint8Array(memory.buffer).set(directoryNameBuffer, pathPtr);
302
303 return constants.WASI_ESUCCESS;
304 };
305
306 WASI.prototype.fd_prestat_get = function (fd, bufPtr) {
307 if (DEBUG_WASI) {
308 console.log("fd_prestat_get", fd, bufPtr, this.fd[fd]);
309 }
310 if (!this.fd[fd]) {
311 return constants.WASI_EBADF;
312 }
313 const { path: directoryName } = this.fd[fd];
314 const memory = this.getMemory();
315
316 const directoryNameBuffer = encoder.encode(directoryName);
317 memory.setUint8(bufPtr, constants.WASI_PREOPENTYPE_DIR);
318 memory.setUint32(bufPtr + 4, directoryNameBuffer.byteLength, true);
319 return constants.WASI_ESUCCESS;
320 };
321
322 WASI.prototype.fd_pwrite = function (fd, iovs, iovsLength, offset, nwritten) {
323 console.log("fd_pwrite", fd, iovs, iovsLength, offset, nwritten, arguments);
324 return constants.WASI_ESUCCESS;
325 };
326
327 WASI.prototype.fd_read = function (fd, iovs, iovsLength, nread) {
328 if (DEBUG_WASI) {
329 console.log("fd_read", fd, iovs, iovsLength, nread, arguments);
330 }
331 const buffers = this.fd[fd] && this.fd[fd].buffers;
332 const totalBuffersLength = buffers.reduce((accumulator, b) => accumulator + b.length, 0);
333 const memory = this.getMemory();
334
335 if (!buffers || buffers.length === 0) {
336 console.error("Reading non existent file", fd, this.fd[fd]);
337 return;
338 }
339
340 let read = Number(this.fd[fd].seekPos);
341
342 let thisRead = 0;
343 let reduced = false;
344
345 if (read >= totalBuffersLength) {
346 return -1; // EOF
347 }
348
349 for (let index = 0; index < iovsLength; index++) {
350 const ptr = iovs + index * 8;
351 const buf = memory.getUint32(ptr, true);
352 const bufLength = memory.getUint32(ptr + 4, true);
353
354 if (!reduced) {
355 thisRead += bufLength;
356 Array.from({ length: bufLength }, (_, index) => index).reduce(
357 (accumulator, currentRead) => {
358 if (reduced) {
359 return accumulator;
360 }
361 const [chunkIndex, chunkOffset] = accumulator;
362 let currentChunkIndex = 0;
363 let currentChunkOffset = 0;
364
365 let found = false;
366 let leadup = 0;
367
368 let currentBufferChunkLength = buffers[currentChunkIndex]
369 ? buffers[currentChunkIndex].byteLength
370 : 0;
371
372 if (currentRead === 0) {
373 while (!found) {
374 currentBufferChunkLength = buffers[currentChunkIndex]
375 ? buffers[currentChunkIndex].byteLength
376 : 0;
377 if (leadup <= read && currentBufferChunkLength + leadup > read) {
378 found = true;
379 currentChunkOffset = read - leadup;
380 } else {
381 leadup += currentBufferChunkLength;
382 currentChunkIndex += 1;
383 }
384 }
385 } else {
386 currentChunkIndex = chunkIndex;
387 currentChunkOffset = chunkOffset;
388 }
389
390 if (buffers[currentChunkIndex]) {
391 memory.setUint8(buf + currentRead, buffers[currentChunkIndex][currentChunkOffset]);
392
393 if (currentChunkOffset + 1 >= buffers[currentChunkIndex].byteLength) {
394 currentChunkIndex = chunkIndex + 1;
395 currentChunkOffset = 0;
396 } else {
397 currentChunkOffset += 1;
398 }
399 } else {
400 memory.setUint8(buf + currentRead, "\0");
401 read += currentRead;
402 reduced = true;
403 }
404
405 return [currentChunkIndex, currentChunkOffset];
406 },
407 [0, 0],
408 );
409 if (!reduced) {
410 read += bufLength;
411 }
412 }
413 }
414
415 this.fd[fd].seekPos = goog.global.BigInt(read);
416 memory.setUint32(nread, thisRead, true);
417
418 return constants.WASI_ESUCCESS;
419 };
420
421 WASI.prototype.fd_readdir = function (fd, bufPtr, bufLength, cookie, bufusedPtr) {
422 if (DEBUG_WASI) {
423 console.log("fd_readdir", fd, bufPtr, bufLength, cookie, bufusedPtr, arguments);
424 }
425 return constants.WASI_ESUCCESS;
426 };
427
428 WASI.prototype.fd_renumber = function (from, to) {
429 if (DEBUG_WASI) {
430 console.log("fd_renumber", from, to, arguments);
431 }
432 return constants.WASI_ESUCCESS;
433 };
434 WASI.prototype.fd_seek = function (fd, offset, whence, newOffsetPtr) {
435 if (DEBUG_WASI) {
436 console.log("fd_seek", fd, offset, whence, newOffsetPtr, arguments);
437 }
438 const memory = this.getMemory();
439
440 switch (whence) {
441 case constants.WASI_WHENCE_CUR: {
442 this.fd[fd].seekPos =
443 (this.fd[fd].seekPos ? this.fd[fd].seekPos : goog.global.BigInt(0)) +
444 goog.global.BigInt(offset);
445 break;
446 }
447 case constants.WASI_WHENCE_END: {
448 const currentLength = this.fd[fd].writer
449 ? goog.global.BigInt(this.fd[fd].writer.length)
450 : goog.global.BigInt(0);
451 this.fd[fd].seekPos = currentLength + BigInt(offset);
452 break;
453 }
454
455 case constants.WASI_WHENCE_SET: {
456 this.fd[fd].seekPos = BigInt(offset);
457 break;
458 }
459 }
460
461 memory.setBigUint64(newOffsetPtr, this.fd[fd].seekPos, true);
462
463 return constants.WASI_ESUCCESS;
464 };
465 WASI.prototype.fd_sync = function (fd) {
466 if (DEBUG_WASI) {
467 console.log("fd_sync", fd, arguments);
468 }
469 return constants.WASI_ESUCCESS;
470 };
471 WASI.prototype.fd_tell = function (fd, offsetPtr) {
472 if (DEBUG_WASI) {
473 console.log("fd_tell", fd, offsetPtr, arguments);
474 }
475 const memory = this.getMemory();
476
477 if (!this.fd[fd].seekPos) {
478 this.fd[fd].seekPos = goog.global.BigInt(0);
479 }
480
481 memory.setBigUint64(offsetPtr, this.fd[fd].seekPos, true);
482
483 return constants.WASI_ESUCCESS;
484 };
485
486 WASI.prototype.fd_write = function (fd, iovs, iovsLength, nwritten) {
487 if (DEBUG_WASI) {
488 console.log("fd_write", { fd, iovs, iovsLength, nwritten });
489 }
490
491 let append = false;
492 const memory = this.getMemory();
493 this.fd[fd].buffers = this.fd[fd].buffers || [];
494
495 // append-only, if starting new write from beginning
496 if (this.fd[fd].seekPos === goog.global.BigInt(0) && this.fd[fd].buffers.length > 0) {
497 append = true;
498 }
499 let written = 0;
500
501 for (let index = 0; index < iovsLength; index++) {
502 const ptr = iovs + index * 8;
503 const buf = memory.getUint32(ptr, true);
504 const bufLength = memory.getUint32(ptr + 4, true);
505 written += bufLength;
506 const chunk = new Uint8Array(memory.buffer, buf, bufLength);
507 if (append) {
508 this.fd[fd].buffers.unshift(chunk.slice(0, bufLength));
509 } else {
510 this.fd[fd].buffers.push(chunk.slice(0, bufLength));
511 }
512 }
513
514 this.fd[fd].seekPos += goog.global.BigInt(written);
515
516 memory.setUint32(nwritten, written, true);
517
518 if ([1, 2].includes(fd)) {
519 console.log(decoder.decode(concatUint8Arrays(this.fd[fd].buffers)));
520 }
521
522 return constants.WASI_ESUCCESS;
523 };
524
525 WASI.prototype.path_create_directory = function (fd, pathPtr, pathLength) {
526 if (DEBUG_WASI) {
527 console.log("path_create_directory", fd, pathPtr, pathLength, arguments);
528 }
529 return constants.WASI_ESUCCESS;
530 };
531
532 WASI.prototype.path_filestat_get = function (fd, flags, pathPtr, pathLength, bufPtr) {
533 if (DEBUG_WASI) {
534 console.log("path_filestat_get", fd, flags, pathPtr, pathLength, bufPtr, arguments);
535 }
536 return constants.WASI_ESUCCESS;
537 };
538 WASI.prototype.path_filestat_set_times = function (
539 fd,
540 dirflags,
541 pathPtr,
542 pathLength,
543 stAtim,
544 stMtim,
545 fstflags,
546 ) {
547 if (DEBUG_WASI) {
548 console.log(
549 "path_filestat_set_times",
550 fd,
551 dirflags,
552 pathPtr,
553 pathLength,
554 stAtim,
555 stMtim,
556 fstflags,
557 arguments,
558 );
559 }
560 return constants.WASI_ESUCCESS;
561 };
562 WASI.prototype.path_link = function (
563 oldFd,
564 oldFlags,
565 oldPath,
566 oldPathLength,
567 newFd,
568 newPath,
569 newPathLength,
570 ) {
571 if (DEBUG_WASI) {
572 console.log(
573 "path_link",
574 oldFd,
575 oldFlags,
576 oldPath,
577 oldPathLength,
578 newFd,
579 newPath,
580 newPathLength,
581 arguments,
582 );
583 }
584 return constants.WASI_ESUCCESS;
585 };
586
587 WASI.prototype.path_open = function (
588 dirfd,
589 dirflags,
590 pathPtr,
591 pathLength,
592 oflags,
593 fsRightsBase,
594 fsRightsInheriting,
595 fsFlags,
596 fd,
597 ) {
598 if (DEBUG_WASI) {
599 console.log(
600 "path_open",
601 dirfd,
602 dirflags,
603 pathPtr,
604 pathLength,
605 oflags,
606 fsRightsBase,
607 fsRightsInheriting,
608 fsFlags,
609 fd,
610 arguments,
611 );
612 }
613 const memory = this.getMemory();
614 const directoryPath = (this.fd[dirfd] || { path: "/" }).path;
615 const pathOpenBytes = new Uint8Array(memory.buffer, pathPtr, pathLength);
616 const pathOpenString = decoder.decode(pathOpenBytes);
617 const pathOpen = assertLeadingSlash(
618 goog.string.path.normalizePath(
619 goog.string.path.join(dirfd === 3 ? "" : directoryPath, pathOpenString),
620 ),
621 );
622
623 if (DEBUG_WASI) {
624 console.log(";; opening path", pathOpen, "withREader", shouldOpenReader(fsRightsBase));
625 }
626
627 if (pathOpen.startsWith("/..") || pathOpen === "/._" || pathOpen === "/.AppleDouble") {
628 return constants.WASI_EBADF;
629 }
630
631 const alreadyExists = Object.values(this.fd).find(
632 (entry) => entry.path === pathOpen && Array.isArray(entry.buffers),
633 );
634 let actualFd;
635
636 if (alreadyExists) {
637 actualFd = alreadyExists.fd;
638 } else {
639 actualFd = this.fd.length;
640 this.fd[actualFd] = { fd: actualFd };
641 }
642
643 let fileType = "file";
644
645 this.fd[actualFd] = {
646 ...this.fd[actualFd],
647 path: pathOpen,
648 type: fileType,
649 seekPos: goog.global.BigInt(0),
650 buffers: alreadyExists ? this.fd[actualFd].buffers : [],
651 };
652
653 if ((oflags & constants.WASI_O_DIRECTORY) !== 0) {
654 fileType = "dir";
655 }
656
657 if (shouldOpenReader(fsRightsBase) && DEBUG_WASI) {
658 console.log("should open a read handle for", pathOpen);
659 }
660
661 memory.setUint32(fd, actualFd, true);
662
663 return constants.WASI_ESUCCESS;
664 };
665
666 WASI.prototype.path_readlink = function (fd, pathPtr, pathLength, buf, bufLength, bufused) {
667 if (DEBUG_WASI) {
668 console.log("path_readlink", fd, pathPtr, pathLength, buf, bufLength, bufused, arguments);
669 }
670 return constants.WASI_ESUCCESS;
671 };
672 WASI.prototype.path_remove_directory = function (fd, pathPtr, pathLength) {
673 if (DEBUG_WASI) {
674 console.log("path_remove_directory", fd, pathPtr, pathLength);
675 }
676 return constants.WASI_ESUCCESS;
677 };
678 WASI.prototype.path_rename = function (
679 oldFd,
680 oldPath,
681 oldPathLength,
682 newFd,
683 newPath,
684 newPathLength,
685 ) {
686 if (DEBUG_WASI) {
687 console.log(
688 "path_rename",
689 oldFd,
690 oldPath,
691 oldPathLength,
692 newFd,
693 newPath,
694 newPathLength,
695 arguments,
696 );
697 }
698 return constants.WASI_ESUCCESS;
699 };
700 WASI.prototype.path_symlink = function (oldPath, oldPathLength, fd, newPath, newPathLength) {
701 if (DEBUG_WASI) {
702 console.log("path_symlink", oldPath, oldPathLength, fd, newPath, newPathLength, arguments);
703 }
704 return constants.WASI_ESUCCESS;
705 };
706
707 WASI.prototype.path_unlink_file = function (fd, pathPtr, pathLength) {
708 if (fd > 3 && DEBUG_WASI) {
709 console.log("path_unlink_file", fd, pathPtr, pathLength, arguments);
710 }
711 // actual file removal goes here
712
713 return constants.WASI_ESUCCESS;
714 };
715
716 WASI.prototype.poll_oneoff = function (sin, sout, nsubscriptions, nevents) {
717 if (DEBUG_WASI) {
718 console.log("poll_oneoff", sin, sout, nsubscriptions, nevents, arguments);
719 }
720 return constants.WASI_ESUCCESS;
721 };
722 WASI.prototype.proc_exit = function (rval) {
723 if (DEBUG_WASI) {
724 console.log("proc_exit", rval, arguments);
725 }
726 return constants.WASI_ESUCCESS;
727 };
728 WASI.prototype.proc_raise = function (sig) {
729 if (DEBUG_WASI) {
730 console.log("proc_raise", sig, arguments);
731 }
732 return constants.WASI_ESUCCESS;
733 };
734 WASI.prototype.random_get = function (bufPtr, bufLength) {
735 if (DEBUG_WASI) {
736 console.log("random_get", bufPtr, bufLength);
737 }
738 return constants.WASI_ESUCCESS;
739 };
740 WASI.prototype.sched_yield = function () {
741 if (DEBUG_WASI) {
742 console.log("sched_yield", arguments);
743 }
744 return constants.WASI_ESUCCESS;
745 };
746 WASI.prototype.sock_recv = function () {
747 if (DEBUG_WASI) {
748 console.log("sock_recv", arguments);
749 }
750 return constants.WASI_ENOSYS;
751 };
752 WASI.prototype.sock_send = function () {
753 if (DEBUG_WASI) {
754 console.log("sock_send", arguments);
755 }
756 return constants.WASI_ENOSYS;
757 };
758 WASI.prototype.sock_shutdown = function () {
759 if (DEBUG_WASI) {
760 console.log("sock_shutdown", arguments);
761 }
762 return constants.WASI_ENOSYS;
763 };
764
765 // helpers
766
767 WASI.prototype.findBuffers = function (filePath /* string */) {
768 const maybeFd = Object.values(this.fd).find(({ path }) => path === filePath);
769 return maybeFd && maybeFd.buffers;
770 };
771
772 // fs api
773
774 WASI.prototype.readdir = function (dirname /* string */) {
775 const prefixPath = (assertLeadingSlash(normalizePath(dirname)) + "/").replace("//", "/");
776 const files = [];
777 Object.values(this.fd).forEach(({ path }) => {
778 // console.log({
779 // path,
780 // prefixPath,
781 // replaced: path.replace(prefixPath, ""),
782 // isTrue: !/\//g.test(path.replace(prefixPath, "")),
783 // });
784 return !/\//g.test(path.replace(prefixPath, "")) && files.push(path);
785 });
786 return files.map((p) => removeLeadingSlash(p.replace(prefixPath, ""))).filter((p) => !!p);
787 };
788
789 WASI.prototype.writeFile = function (fname /* string */, data /* Uint8Array */) {
790 const filePath = assertLeadingSlash(normalizePath(fname));
791
792 const nextFd = Object.keys(this.fd).length;
793 const maybeOldFd = Object.values(this.fd).find(({ path }) => path === filePath);
794
795 this.fd[nextFd] = {
796 fd: nextFd,
797 path: filePath,
798 seekPos: goog.global.BigInt(0),
799 buffers: [data],
800 };
801
802 if (maybeOldFd) {
803 delete this.fd[maybeOldFd];
804 }
805 };
806
807 WASI.prototype.appendFile = function (fname /* string */, data /* Uint8Array */) {
808 const filePath = assertLeadingSlash(normalizePath(fname));
809
810 const buffers = this.findBuffers(filePath);
811
812 if (!buffers) {
813 console.error(`Can't append to non-existing file ${fname}`);
814 } else {
815 buffers.push(data);
816 }
817 };
818
819 WASI.prototype.readFile = function (fname /* string */) {
820 const filePath = assertLeadingSlash(normalizePath(fname));
821
822 const buffers = this.findBuffers(filePath);
823
824 if (buffers) {
825 return concatUint8Arrays(buffers);
826 }
827 };
828
829 WASI.prototype.readStdOut = function () {
830 const maybeFd = Object.values(this.fd[0]);
831 const buffers = (maybeFd && maybeFd.buffers) || [];
832 return concatUint8Arrays(buffers);
833 };
834
835 WASI.prototype.unlink = function (fname /* string */) {
836 const filePath = assertLeadingSlash(normalizePath(fname));
837 const maybeFd = Object.values(this.fd).find(({ path }) => path === filePath);
838
839 if (maybeFd) {
840 delete this.fd[maybeFd];
841 } else {
842 console.error(`While trying to unlink ${filePath}, path not found`);
843 }
844 };
845
846 WASI.prototype.mkdir = function (dirname /* string */) {
847 const cleanPath = assertLeadingSlash(normalizePath(dirname));
848 const files = [];
849 Object.values(this.fd).forEach(({ path }) => {
850 return path.startsWith(cleanPath) && files.push(path);
851 });
852
853 const alreadyExist = files.length > 0;
854 if (alreadyExist) {
855 console.warn(`mkdir: path ${dirname} already exists`);
856 } else {
857 const nextFd = Object.keys(this.fd).length;
858 this.fd[nextFd] = {
859 fd: nextFd,
860 path: cleanPath,
861 };
862 }
863 };