-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheasywasi.js
1300 lines (1078 loc) · 37.3 KB
/
easywasi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as defs from './defs.js'
export { defs }
export class WASIProcExit extends Error {
constructor (code) {
super(`Exit with code ${code}`)
this.code = code
}
}
// FS interface that is used here. Implement your own, if you want, or use zenfs or node fs!
export class FSDummy {
appendFileSync (path, data, options = {}) {
throw new Error('appendFileSync not implemented. This is a dummy fs.')
}
fsyncSync (fd) {
throw new Error('fsyncSync not implemented. This is a dummy fs.')
}
linkSync (existingPath, newPath) {
throw new Error('linkSync not implemented. This is a dummy fs.')
}
mkdirSync (path, options = {}) {
throw new Error('mkdirSync not implemented. This is a dummy fs.')
}
readdirSync (path, options = {}) {
throw new Error('readdirSync not implemented. This is a dummy fs.')
}
readFileSync (path, options = {}) {
throw new Error('readFileSync not implemented. This is a dummy fs.')
}
readlinkSync (path, options = {}) {
throw new Error('readlinkSync not implemented. This is a dummy fs.')
}
renameSync (oldPath, newPath) {
throw new Error('renameSync not implemented. This is a dummy fs.')
}
rmdirSync (path, options = {}) {
throw new Error('rmdirSync not implemented. This is a dummy fs.')
}
setFlagsSync (path, flags) {
throw new Error('setFlagsSync not implemented. This is a dummy fs.')
}
statSync (path, options = {}) {
throw new Error('statSync not implemented. This is a dummy fs.')
}
symlinkSync (target, path, type = 'file') {
throw new Error('symlinkSync not implemented. This is a dummy fs.')
}
truncateSync (path, len = 0) {
throw new Error('truncateSync not implemented. This is a dummy fs.')
}
unlinkSync (path) {
throw new Error('unlinkSync not implemented. This is a dummy fs.')
}
utimesSync (path, atime, mtime) {
throw new Error('utimesSync not implemented. This is a dummy fs.')
}
writeFileSync (path, data, options = {}) {
throw new Error('writeFileSync not implemented. This is a dummy fs.')
}
}
export class WasiPreview1 {
constructor (options = {}) {
this.args = options?.args || []
this.env = options?.env || {}
this.fs = options?.fs || new FSDummy()
this.debug = !!options?.debug
// Initialize file descriptors with stdin(0), stdout(1), stderr(2), /
// fd is first number
this.fds = new Map([
[0, { type: 'stdio' }], // stdin
[1, { type: 'stdio' }], // stdout
[2, { type: 'stdio' }], // stderr
[3, { type: 'directory', preopenPath: '/' }] // root directory
])
this.nextFd = this.fds.size
this.textDecoder = new TextDecoder()
this.textEncoder = new TextEncoder()
// Bind all WASI functions to maintain correct 'this' context
const doBind = (...names) => {
for (const name of names) {
if (this.debug) {
const orig = this[name].bind(this)
this[name] = (...a) => {
console.log(name, a)
return orig(...a)
}
} else {
this[name] = this[name].bind(this)
}
}
}
doBind(
'args_get',
'args_sizes_get',
'environ_get',
'environ_sizes_get',
'clock_res_get',
'clock_time_get',
'fd_close',
'fd_seek',
'fd_write',
'fd_read',
'fd_fdstat_get',
'fd_fdstat_set_flags',
'fd_filestat_get',
'fd_prestat_get',
'fd_prestat_dir_name',
'path_open',
'path_filestat_get',
'proc_exit',
'fd_advise',
'fd_allocate',
'fd_datasync',
'fd_filestat_set_size',
'fd_filestat_set_times',
'fd_pread',
'fd_pwrite',
'fd_readdir',
'fd_renumber',
'fd_sync',
'fd_tell',
'path_create_directory',
'path_filestat_set_times',
'path_link',
'path_readlink',
'path_remove_directory',
'path_rename',
'path_symlink',
'path_unlink_file',
'poll_oneoff',
'sock_accept',
'sock_recv',
'sock_send',
'sock_shutdown',
'random_get',
'sched_yield'
)
}
// Helper methods
// this binds the wasm to this WASI implementation
setup (wasm) {
this.wasm = wasm
}
// this binds the wasm to this WASI implementation
// and calls it's main()'
start (wasm) {
this.setup(wasm)
try {
if (instance.exports._initialize) {
instance.exports._initialize()
}
if (wasm._start) {
wasm._start()
}
return 0
} catch (e) {
if (e instanceof WASIProcExit) {
return e.code
}
throw e
}
}
allocateFd (fileHandle, type = 'file') {
const fd = this.nextFd++
const descriptor = { type, handle: fileHandle, fd }
this.fds.set(fd, descriptor)
return fd
}
// Standard input (for fd_read)
stdin () {
return new Uint8Array()
}
// Standard output handling (for fd_write)
stdout (buffer) {
const text = this.textDecoder.decode(buffer).replace(/\n$/g, '')
if (text) console.log(text)
}
// Standard error handling (for fd_write)
stderr (buffer) {
const text = this.textDecoder.decode(buffer).replace(/\n$/g, '')
if (text) console.error(text)
}
// Args functions
args_get (argvP, argvBufP) {
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
for (const arg of this.args) {
view.setUint32(argvP, argvBufP, true)
argvP += 4
const encoded = this.textEncoder.encode(arg)
mem.set(encoded, argvBufP)
mem[argvBufP + encoded.length] = 0 // null terminator
argvBufP += encoded.length + 1
}
return defs.ERRNO_SUCCESS
}
args_sizes_get (argcPtr, argvBufSizePtr) {
const view = new DataView(this.wasm.memory.buffer)
view.setUint32(argcPtr, this.args.length, true)
const bufSize = this.args.reduce((acc, arg) => acc + arg.length + 1, 0)
view.setUint32(argvBufSizePtr, bufSize, true)
return defs.ERRNO_SUCCESS
}
// Environment functions
environ_get (environP, environBufP) {
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
for (const [key, value] of Object.entries(this.env)) {
view.setUint32(environP, environBufP, true)
environP += 4
const entry = `${key}=${value}\0`
const encoded = this.textEncoder.encode(entry)
mem.set(encoded, environBufP)
environBufP += encoded.length
}
return defs.ERRNO_SUCCESS
}
environ_sizes_get (environCountPtr, environBufSizePtr) {
const view = new DataView(this.wasm.memory.buffer)
const count = Object.keys(this.env).length
view.setUint32(environCountPtr, count, true)
const bufSize = Object.entries(this.env).reduce((acc, [k, v]) => acc + k.length + v.length + 2, 0)
view.setUint32(environBufSizePtr, bufSize, true)
return defs.ERRNO_SUCCESS
}
// Clock functions
clock_res_get (id, resPtr) {
const view = new DataView(this.wasm.memory.buffer)
let resolution
switch (id) {
case defs.CLOCKID_REALTIME:
resolution = 1_000_000n // 1ms in nanoseconds
break
case defs.CLOCKID_MONOTONIC:
resolution = 1_000n // 1μs in nanoseconds
break
default:
return defs.ERRNO_INVAL
}
view.setBigUint64(resPtr, resolution, true)
return defs.ERRNO_SUCCESS
}
fd_filestat_get(fd, filestatPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
try {
let stats
if (fileDesc.type === 'stdio') {
// For stdio, return minimal stats
stats = {
dev: 0n,
ino: 0n,
filetype: defs.FILETYPE_CHARACTER_DEVICE,
nlink: 1n,
size: 0n,
atim: 0n,
mtim: 0n,
ctim: 0n
}
} else if (fileDesc.type === 'file' || fileDesc.type === 'directory') {
// Get actual file stats
const fsStats = this.fs.statSync(fileDesc.handle.path)
// Determine file type
let filetype = defs.FILETYPE_UNKNOWN
if (fsStats.isFile()) filetype = defs.FILETYPE_REGULAR_FILE
else if (fsStats.isDirectory()) filetype = defs.FILETYPE_DIRECTORY
else if (fsStats.isSymbolicLink()) filetype = defs.FILETYPE_SYMBOLIC_LINK
else if (fsStats.isCharacterDevice()) filetype = defs.FILETYPE_CHARACTER_DEVICE
else if (fsStats.isBlockDevice()) filetype = defs.FILETYPE_BLOCK_DEVICE
else if (fsStats.isFIFO()) filetype = defs.FILETYPE_SOCKET_STREAM
stats = {
dev: BigInt(fsStats.dev || 0),
ino: BigInt(fsStats.ino || 0),
filetype,
nlink: BigInt(fsStats.nlink || 1),
size: BigInt(fsStats.size || 0),
atim: BigInt(fsStats.atimeMs * 1_000_000), // Convert to nanoseconds
mtim: BigInt(fsStats.mtimeMs * 1_000_000),
ctim: BigInt(fsStats.ctimeMs * 1_000_000)
}
} else {
return defs.ERRNO_BADF
}
// Write filestat struct to memory
const view = new DataView(this.wasm.memory.buffer)
// device ID - u64
view.setBigUint64(filestatPtr, stats.dev, true)
// inode - u64
view.setBigUint64(filestatPtr + 8, stats.ino, true)
// filetype - u8
view.setUint8(filestatPtr + 16, stats.filetype)
// nlink - u64
view.setBigUint64(filestatPtr + 24, stats.nlink, true)
// size - u64
view.setBigUint64(filestatPtr + 32, stats.size, true)
// atime - u64
view.setBigUint64(filestatPtr + 40, stats.atim, true)
// mtime - u64
view.setBigUint64(filestatPtr + 48, stats.mtim, true)
// ctime - u64
view.setBigUint64(filestatPtr + 56, stats.ctim, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
clock_time_get (id, precision, timePtr) {
const view = new DataView(this.wasm.memory.buffer)
let time
switch (id) {
case defs.CLOCKID_REALTIME: {
const ms = Date.now()
time = BigInt(ms) * 1_000_000n
break
}
case defs.CLOCKID_MONOTONIC: {
const ns = BigInt(Math.round(performance.now() * 1_000_000))
time = ns
break
}
default:
return defs.ERRNO_INVAL
}
view.setBigUint64(timePtr, time, true)
return defs.ERRNO_SUCCESS
}
fd_close (fd) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
this.fds.delete(fd)
return defs.ERRNO_SUCCESS
}
fd_seek (fd, offset, whence, newOffsetPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type === 'stdio') return defs.ERRNO_SPIPE
let stats = null
let newPosition = 0
const noffset = Number(offset)
try {
stats = this.fs.statSync(fileDesc.handle.path)
} catch (e) {
return defs.ERRNO_IO
}
switch (whence) {
case defs.WHENCE_SET:
newPosition = noffset
break
case defs.WHENCE_CUR:
newPosition = Number(fileDesc.handle.position) + noffset
break
case defs.WHENCE_END:
newPosition = Number(stats.size) + noffset
break
default:
return defs.ERRNO_INVAL
}
// Update position
fileDesc.handle.position = newPosition
const view = new DataView(this.wasm.memory.buffer)
view.setBigUint64(newOffsetPtr, BigInt(newPosition), true)
return defs.ERRNO_SUCCESS
}
fd_write (fd, iovs, iovsLen, nwrittenPtr) {
let written = 0
const chunks = []
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
// Gather all the chunks from the vectors
for (let i = 0; i < iovsLen; i++) {
const ptr = iovs + i * 8
const buf = view.getUint32(ptr, true)
const bufLen = view.getUint32(ptr + 4, true)
chunks.push(new Uint8Array(mem.buffer, buf, bufLen))
written += bufLen
}
// Concatenate chunks if needed
let buffer
if (chunks.length === 1) {
buffer = chunks[0]
} else {
buffer = new Uint8Array(written)
let offset = 0
for (const chunk of chunks) {
buffer.set(chunk, offset)
offset += chunk.length
}
}
// Handle standard streams
if (fd === 1) {
this.stdout(buffer)
} else if (fd === 2) {
this.stderr(buffer)
} else {
const fileDesc = this.fds.get(fd)
if (!fileDesc) {
return defs.ERRNO_BADF
}
fileDesc.handle.position += written
try {
// Write using ZenFS path-based API
this.fs.writeFileSync(fileDesc.handle.path, buffer)
} catch (e) {
return defs.ERRNO_IO
}
}
view.setUint32(nwrittenPtr, written, true)
return defs.ERRNO_SUCCESS
}
fd_read (fd, iovs, iovsLen, nreadPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
let totalRead = 0
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
try {
let content
if (fd === 0) {
content = this.stdin()
} else {
content = this.fs.readFileSync(fileDesc.handle.path)
}
for (let i = 0; i < iovsLen; i++) {
const ptr = iovs + i * 8
const buf = view.getUint32(ptr, true)
const bufLen = view.getUint32(ptr + 4, true)
const start = fileDesc.handle.position
const end = Math.min(start + bufLen, content.length)
const bytesToRead = end - start
if (bytesToRead <= 0) break
mem.set(new Uint8Array(content.slice(start, end)), buf)
totalRead += bytesToRead
fileDesc.handle.position += bytesToRead
if (bytesToRead < bufLen) break
}
view.setUint32(nreadPtr, totalRead, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
path_open (dirfd, dirflags, path, pathLen, oflags, fsRightsBase, fsRightsInheriting, fdflags, fdPtr) {
const fileDesc = this.fds.get(dirfd)
if (!fileDesc) return defs.ERRNO_BADF
const mem = new Uint8Array(this.wasm.memory.buffer)
const pathBuffer = mem.slice(path, path + pathLen)
const pathString = this.textDecoder.decode(pathBuffer)
try {
// Resolve path relative to the directory fd
let resolvedPath = pathString
if (fileDesc.preopenPath) {
if (pathString.startsWith('/')) {
resolvedPath = pathString.slice(1)
}
resolvedPath = fileDesc.preopenPath + (fileDesc.preopenPath.endsWith('/') ? '' : '/') + resolvedPath
}
// Verify file exists
this.fs.statSync(resolvedPath)
// Store path and initial position in handle
const fd = this.allocateFd({ path: resolvedPath, position: 0 }, 'file')
const view = new DataView(this.wasm.memory.buffer)
view.setUint32(fdPtr, fd, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_NOENT
}
}
proc_exit (code) {
throw new WASIProcExit(code)
}
fd_fdstat_get (fd, statPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
const view = new DataView(this.wasm.memory.buffer)
// filetype - u8
let filetype
switch (fileDesc.type) {
case 'stdio':
filetype = defs.FILETYPE_CHARACTER_DEVICE
break
case 'directory':
filetype = defs.FILETYPE_DIRECTORY
break
case 'file':
filetype = defs.FILETYPE_REGULAR_FILE
break
default:
filetype = defs.FILETYPE_UNKNOWN
}
view.setUint8(statPtr, filetype)
// fdflags - u16
// For now, we'll assume basic flags
let fdflags = 0
if (fileDesc.append) fdflags |= defs.FDFLAGS_APPEND
view.setUint16(statPtr + 2, fdflags, true)
// fs_rights_base - u64
// Set basic rights depending on file type
let fsRightsBase = 0n
if (fileDesc.type === 'file') {
fsRightsBase = defs.RIGHTS_FD_READ | defs.RIGHTS_FD_WRITE | defs.RIGHTS_FD_SEEK | defs.RIGHTS_FD_TELL | defs.RIGHTS_FD_FILESTAT_GET
} else if (fileDesc.type === 'directory') {
fsRightsBase = defs.RIGHTS_PATH_OPEN | defs.RIGHTS_FD_READDIR | defs.RIGHTS_PATH_CREATE_DIRECTORY | defs.RIGHTS_PATH_UNLINK_FILE | defs.RIGHTS_PATH_REMOVE_DIRECTORY
}
const bf = BigInt(fsRightsBase)
view.setBigUint64(statPtr + 8, bf, true)
// fs_rights_inheriting - u64
// Child files/directories inherit the same rights
view.setBigUint64(statPtr + 16, bf, true)
return defs.ERRNO_SUCCESS
}
fd_fdstat_set_flags (fd, flags) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
// Check if flags are valid
const validFlags = defs.FDFLAGS_APPEND | defs.FDFLAGS_DSYNC | defs.FDFLAGS_NONBLOCK | defs.FDFLAGS_RSYNC | defs.FDFLAGS_SYNC
if (flags & ~validFlags) {
return defs.ERRNO_INVAL // Invalid flags specified
}
// For stdio handles, we can't set flags
if (fileDesc.type === 'stdio') {
return defs.ERRNO_NOTSUP
}
try {
// Update internal file descriptor state
fileDesc.append = Boolean(flags & defs.FDFLAGS_APPEND)
// Try to apply flags to the underlying file system
// Note: Many flags might not be supported by the underlying fs
if (fileDesc.handle && typeof this.fs.setFlagsSync === 'function') {
this.fs.setFlagsSync(fileDesc.handle, flags)
}
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_prestat_get (fd, prestatPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
// Only directory file descriptors have prestats
if (fileDesc.type !== 'directory') {
return defs.ERRNO_BADF
}
// Ensure we have a preopened path for this fd
if (!fileDesc.preopenPath) {
return defs.ERRNO_BADF
}
const view = new DataView(this.wasm.memory.buffer)
// Write prestat struct:
// struct prestat {
// u8 type; // offset 0
// u64 length; // offset 8 (with padding)
// }
// Set type to PREOPENTYPE_DIR (0)
view.setUint8(prestatPtr, defs.PREOPENTYPE_DIR)
// Get the length of the preopened directory path
const pathLength = fileDesc.preopenPath.length
view.setUint32(prestatPtr + 4, pathLength, true)
return defs.ERRNO_SUCCESS
}
fd_prestat_dir_name (fd, pathPtr, pathLen) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
// Only directory file descriptors have prestats
if (fileDesc.type !== 'directory') {
return defs.ERRNO_BADF
}
// Ensure we have a preopened path for this fd
if (!fileDesc.preopenPath) {
return defs.ERRNO_BADF
}
// Check if the provided buffer is large enough
if (pathLen < fileDesc.preopenPath.length) {
return defs.ERRNO_NAMETOOLONG
}
// Write the path to memory
const mem = new Uint8Array(this.wasm.memory.buffer)
const pathBytes = this.textEncoder.encode(fileDesc.preopenPath)
mem.set(pathBytes, pathPtr)
return defs.ERRNO_SUCCESS
}
path_filestat_get (fd, flags, pathPtr, pathLen, filestatPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
// Read the path from memory
const mem = new Uint8Array(this.wasm.memory.buffer)
const pathBytes = new Uint8Array(mem.buffer, pathPtr, pathLen)
const pathString = this.textDecoder.decode(pathBytes)
try {
// Resolve path relative to the directory fd
let resolvedPath = pathString
if (fileDesc.preopenPath) {
// If path starts with '/', make it relative to preopenPath
if (pathString.startsWith('/')) {
resolvedPath = pathString.slice(1) // Remove leading '/'
}
// Combine preopenPath with the relative path
resolvedPath = fileDesc.preopenPath + (fileDesc.preopenPath.endsWith('/') ? '' : '/') + resolvedPath
}
// Get stats from filesystem
const stats = this.fs.statSync(resolvedPath, {
followSymlinks: (flags & defs.LOOKUPFLAGS_SYMLINK_FOLLOW) !== 0
})
const view = new DataView(this.wasm.memory.buffer)
// Write filestat struct:
// struct filestat {
// dev: u64, // Device ID
// ino: u64, // Inode number
// filetype: u8, // File type
// nlink: u64, // Number of hard links
// size: u64, // File size
// atim: u64, // Access time
// mtim: u64, // Modification time
// ctim: u64 // Change time
// }
// Device ID
view.setBigUint64(filestatPtr, BigInt(stats.dev || 0), true)
// Inode
view.setBigUint64(filestatPtr + 8, BigInt(stats.ino || 0), true)
// Filetype
let filetype = defs.FILETYPE_UNKNOWN
if (stats.isFile()) filetype = defs.FILETYPE_REGULAR_FILE
else if (stats.isDirectory()) filetype = defs.FILETYPE_DIRECTORY
else if (stats.isSymbolicLink()) filetype = defs.FILETYPE_SYMBOLIC_LINK
else if (stats.isCharacterDevice()) filetype = defs.FILETYPE_CHARACTER_DEVICE
else if (stats.isBlockDevice()) filetype = defs.FILETYPE_BLOCK_DEVICE
else if (stats.isFIFO()) filetype = defs.FILETYPE_SOCKET_STREAM
view.setUint8(filestatPtr + 16, filetype)
// Number of hard links
view.setBigUint64(filestatPtr + 24, BigInt(stats.nlink || 1), true)
// File size
view.setBigUint64(filestatPtr + 32, BigInt(stats.size || 0), true)
// Access time (in nanoseconds)
view.setBigUint64(filestatPtr + 40, BigInt(stats.atimeMs * 1_000_000), true)
// Modification time (in nanoseconds)
view.setBigUint64(filestatPtr + 48, BigInt(stats.mtimeMs * 1_000_000), true)
// Change time (in nanoseconds)
view.setBigUint64(filestatPtr + 56, BigInt(stats.ctimeMs * 1_000_000), true)
return defs.ERRNO_SUCCESS
} catch (e) {
if (e.code === 'ENOENT') return defs.ERRNO_NOENT
if (e.code === 'EACCES') return defs.ERRNO_ACCES
return defs.ERRNO_IO
}
}
// File/Directory Operations
fd_advise (fd, offset, len, advice) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
// Most filesystems don't actually implement advisory hints,
// so we'll just return success
return defs.ERRNO_SUCCESS
}
fd_allocate (fd, offset, len) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
// Attempt to extend the file to the specified size
const stats = this.fs.statSync(fileDesc.handle.path)
const newSize = Number(offset) + Number(len)
if (newSize > stats.size) {
// Create a buffer of zeros to extend the file
const zeros = new Uint8Array(newSize - stats.size)
this.fs.appendFileSync(fileDesc.handle.path, zeros)
}
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_datasync (fd) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
// Most JavaScript filesystem implementations handle syncing automatically
// If your fs implementation has a specific sync method, call it here
if (typeof this.fs.fsyncSync === 'function') {
this.fs.fsyncSync(fileDesc.handle.path)
}
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_filestat_set_size (fd, size) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
this.fs.truncateSync(fileDesc.handle.path, Number(size))
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_filestat_set_times (fd, atim, mtim, fst_flags) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
const times = {
atime: Number(atim) / 1_000_000_000,
mtime: Number(mtim) / 1_000_000_000
}
this.fs.utimesSync(fileDesc.handle.path, times.atime, times.mtime)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_pread (fd, iovs, iovsLen, offset, nreadPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
const content = this.fs.readFileSync(fileDesc.handle.path)
let totalRead = 0
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
const position = Number(offset)
for (let i = 0; i < iovsLen; i++) {
const ptr = iovs + i * 8
const buf = view.getUint32(ptr, true)
const bufLen = view.getUint32(ptr + 4, true)
const start = position + totalRead
const end = Math.min(start + bufLen, content.length)
const bytesToRead = end - start
if (bytesToRead <= 0) break
mem.set(new Uint8Array(content.slice(start, end)), buf)
totalRead += bytesToRead
if (bytesToRead < bufLen) break
}
view.setUint32(nreadPtr, totalRead, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_pwrite (fd, iovs, iovsLen, offset, nwrittenPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'file') return defs.ERRNO_BADF
try {
let written = 0
const chunks = []
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
for (let i = 0; i < iovsLen; i++) {
const ptr = iovs + i * 8
const buf = view.getUint32(ptr, true)
const bufLen = view.getUint32(ptr + 4, true)
chunks.push(new Uint8Array(mem.buffer, buf, bufLen))
written += bufLen
}
let buffer
if (chunks.length === 1) {
buffer = chunks[0]
} else {
buffer = new Uint8Array(written)
let offset = 0
for (const chunk of chunks) {
buffer.set(chunk, offset)
offset += chunk.length
}
}
// Read existing file content
const content = this.fs.readFileSync(fileDesc.handle.path)
const newContent = new Uint8Array(Math.max(Number(offset) + buffer.length, content.length))
// Copy existing content
newContent.set(content)
// Write new data at specified offset
newContent.set(buffer, Number(offset))
// Write back to file
this.fs.writeFileSync(fileDesc.handle.path, newContent)
view.setUint32(nwrittenPtr, written, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_readdir (fd, buf, bufLen, cookie, bufusedPtr) {
const fileDesc = this.fds.get(fd)
if (!fileDesc) return defs.ERRNO_BADF
if (fileDesc.type !== 'directory') return defs.ERRNO_NOTDIR
try {
const entries = this.fs.readdirSync(fileDesc.handle.path, {
withFileTypes: true
})
const view = new DataView(this.wasm.memory.buffer)
const mem = new Uint8Array(this.wasm.memory.buffer)
let offset = 0
let entriesWritten = 0
// Skip entries according to cookie
const startIndex = Number(cookie)
for (let i = startIndex; i < entries.length; i++) {
const entry = entries[i]
const name = entry.name
const nameBytes = this.textEncoder.encode(name)
// dirent structure size: 24 bytes + name length
const direntSize = 24 + nameBytes.length
if (offset + direntSize > bufLen) {
break
}
// Write dirent structure
view.setBigUint64(buf + offset, BigInt(i + 1), true) // d_next
view.setBigUint64(buf + offset + 8, 0n, true) // d_ino
view.setUint32(buf + offset + 16, nameBytes.length, true) // d_namlen
// d_type
let filetype = defs.FILETYPE_UNKNOWN
if (entry.isFile()) filetype = defs.FILETYPE_REGULAR_FILE
else if (entry.isDirectory()) filetype = defs.FILETYPE_DIRECTORY
view.setUint8(buf + offset + 20, filetype)
// Write name
mem.set(nameBytes, buf + offset + 24)
offset += direntSize
entriesWritten++
}
view.setUint32(bufusedPtr, offset, true)
return defs.ERRNO_SUCCESS
} catch (e) {
return defs.ERRNO_IO
}
}
fd_renumber (from, to) {
const fromDesc = this.fds.get(from)
if (!fromDesc) return defs.ERRNO_BADF
// Close existing 'to' fd if it exists
this.fds.delete(to)
// Move the fd
this.fds.set(to, fromDesc)
this.fds.delete(from)
return defs.ERRNO_SUCCESS
}