-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
library.js
4908 lines (4708 loc) · 173 KB
/
library.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
// An implementation of a libc for the web. Basically, implementations of
// the various standard C libraries, that can be called from compiled code,
// and work using the actual JavaScript environment.
//
// We search the Library object when there is an external function. If the
// entry in the Library is a function, we insert it. If it is a string, we
// do another lookup in the library (a simple way to write a function once,
// if it can be called by different names). We also allow dependencies,
// using __deps. Initialization code to be run after allocating all
// global constants can be defined by __postset.
//
// Note that the full function name will be '_' + the name in the Library
// object. For convenience, the short name appears here. Note that if you add a
// new function with an '_', it will not be found.
LibraryManager.library = {
// ==========================================================================
// File system base.
// ==========================================================================
stdin: 0,
stdout: 0,
stderr: 0,
$FS__deps: ['$ERRNO_CODES', '__setErrNo', 'stdin', 'stdout', 'stderr'],
$FS__postset: 'FS.init();',
$FS: {
// The main file system tree. All the contents are inside this.
root: {
read: true,
write: false,
isFolder: true,
isDevice: false,
timestamp: Date.now(),
inodeNumber: 1,
contents: {}
},
// The path to the current folder.
currentPath: '/',
// The inode to assign to the next created object.
nextInode: 2,
// Currently opened file or directory streams. Padded with null so the zero
// index is unused, as the indices are used as pointers. This is not split
// into separate fileStreams and folderStreams lists because the pointers
// must be interchangeable, e.g. when used in fdopen().
streams: [null],
// Whether we are currently ignoring permissions. Useful when preparing the
// filesystem and creating files inside read-only folders.
ignorePermissions: true,
// Converts any path to an absolute path. Resolves embedded "." and ".."
// parts.
absolutePath: function(relative, base) {
if (typeof relative !== 'string') return null;
if (base === undefined) base = FS.currentPath;
if (relative && relative[0] == '/') base = '';
var full = base + '/' + relative;
var parts = full.split('/').reverse();
var absolute = [''];
while (parts.length) {
var part = parts.pop();
if (part == '' || part == '.') {
// Nothing.
} else if (part == '..') {
if (absolute.length > 1) absolute.pop();
} else {
absolute.push(part);
}
}
return absolute.length == 1 ? '/' : absolute.join('/');
},
// Analyzes a relative or absolute path returning a description, containing:
// isRoot: Whether the path points to the root.
// exists: Whether the object at the path exists.
// error: If !exists, this will contain the errno code of the cause.
// name: The base name of the object (null if !parentExists).
// path: The absolute path to the object, with all links resolved.
// object: The filesystem record of the object referenced by the path.
// parentExists: Whether the parent of the object exist and is a folder.
// parentPath: The absolute path to the parent folder.
// parentObject: The filesystem record of the parent folder.
analyzePath: function(path, dontResolveLastLink, linksVisited) {
var ret = {
isRoot: false,
exists: false,
error: 0,
name: null,
path: null,
object: null,
parentExists: false,
parentPath: null,
parentObject: null
};
path = FS.absolutePath(path);
if (path == '/') {
ret.isRoot = true;
ret.exists = ret.parentExists = true;
ret.name = '/';
ret.path = ret.parentPath = '/';
ret.object = ret.parentObject = FS.root;
} else if (path !== null) {
linksVisited = linksVisited || 0;
path = path.slice(1).split('/');
var current = FS.root;
var traversed = [''];
while (path.length) {
if (path.length == 1 && current.isFolder) {
ret.parentExists = true;
ret.parentPath = traversed.length == 1 ? '/' : traversed.join('/');
ret.parentObject = current;
ret.name = path[0];
}
var target = path.shift();
if (!current.isFolder) {
ret.error = ERRNO_CODES.ENOTDIR;
break;
} else if (!current.read) {
ret.error = ERRNO_CODES.EACCES;
break;
} else if (!current.contents.hasOwnProperty(target)) {
ret.error = ERRNO_CODES.ENOENT;
break;
}
current = current.contents[target];
if (current.link && !(dontResolveLastLink && path.length == 0)) {
if (linksVisited > 40) { // Usual Linux SYMLOOP_MAX.
ret.error = ERRNO_CODES.ELOOP;
break;
}
var link = FS.absolutePath(current.link, traversed.join('/'));
return FS.analyzePath([link].concat(path).join('/'),
dontResolveLastLink, linksVisited + 1);
}
traversed.push(target);
if (path.length == 0) {
ret.exists = true;
ret.path = traversed.join('/');
ret.object = current;
}
}
return ret;
}
return ret;
},
// Finds the file system object at a given path. If dontResolveLastLink is
// set to true and the object is a symbolic link, it will be returned as is
// instead of being resolved. Links embedded in the path as still resolved.
findObject: function(path, dontResolveLastLink) {
var ret = FS.analyzePath(path, dontResolveLastLink);
if (ret.exists) {
return ret.object;
} else {
___setErrNo(ret.error);
return null;
}
},
// Creates a file system record: file, link, device or folder.
createObject: function(parent, name, properties, canRead, canWrite) {
if (!parent) parent = '/';
if (typeof parent === 'string') parent = FS.findObject(parent);
if (!parent) {
___setErrNo(ERRNO_CODES.EACCES);
throw new Error('Parent path must exist.');
}
if (!parent.isFolder) {
___setErrNo(ERRNO_CODES.ENOTDIR);
throw new Error('Parent must be a folder.');
}
if (!parent.write && !FS.ignorePermissions) {
___setErrNo(ERRNO_CODES.EACCES);
throw new Error('Parent folder must be writeable.');
}
if (!name || name == '.' || name == '..') {
___setErrNo(ERRNO_CODES.ENOENT);
throw new Error('Name must not be empty.');
}
if (parent.contents.hasOwnProperty(name)) {
___setErrNo(ERRNO_CODES.EEXIST);
throw new Error("Can't overwrite object.");
}
parent.contents[name] = {
read: canRead === undefined ? true : canRead,
write: canWrite === undefined ? false : canWrite,
timestamp: Date.now(),
inodeNumber: FS.nextInode++
};
for (var key in properties) {
if (properties.hasOwnProperty(key)) {
parent.contents[name][key] = properties[key];
}
}
return parent.contents[name];
},
// Creates a folder.
createFolder: function(parent, name, canRead, canWrite) {
var properties = {isFolder: true, isDevice: false, contents: {}};
return FS.createObject(parent, name, properties, canRead, canWrite);
},
// Creates a a folder and all its missing parents.
createPath: function(parent, path, canRead, canWrite) {
var current = FS.findObject(parent);
if (current === null) throw new Error('Invalid parent.');
path = path.split('/').reverse();
while (path.length) {
var part = path.pop();
if (!part) continue;
if (!current.contents.hasOwnProperty(part)) {
FS.createFolder(current, part, canRead, canWrite);
}
current = current.contents[part];
}
return current;
},
// Creates a file record, given specific properties.
createFile: function(parent, name, properties, canRead, canWrite) {
properties.isFolder = false;
return FS.createObject(parent, name, properties, canRead, canWrite);
},
// Creates a file record from existing data.
createDataFile: function(parent, name, data, canRead, canWrite) {
if (typeof data === 'string') {
var dataArray = [];
for (var i = 0; i < data.length; i++) dataArray.push(data.charCodeAt(i));
data = dataArray;
}
var properties = {isDevice: false, contents: data};
return FS.createFile(parent, name, properties, canRead, canWrite);
},
// Creates a file record for lazy-loading from a URL.
createLazyFile: function(parent, name, url, canRead, canWrite) {
var properties = {isDevice: false, url: url};
return FS.createFile(parent, name, properties, canRead, canWrite);
},
// Creates a link to a sepcific local path.
createLink: function(parent, name, target, canRead, canWrite) {
var properties = {isDevice: false, link: target};
return FS.createFile(parent, name, properties, canRead, canWrite);
},
// Creates a character device with input and output callbacks:
// input: Takes no parameters, returns a byte value or null if no data is
// currently available.
// output: Takes a byte value; doesn't return anything. Can also be passed
// null to perform a flush of any cached data.
createDevice: function(parent, name, input, output) {
if (!(input || output)) {
throw new Error('A device must have at least one callback defined.');
}
var ops = {isDevice: true, input: input, output: output};
return FS.createFile(parent, name, ops, Boolean(input), Boolean(output));
},
// Makes sure a file's contents are loaded. Returns whether the file has
// been loaded successfully. No-op for files that have been loaded already.
forceLoadFile: function(obj) {
if (obj.isDevice || obj.isFolder || obj.link ||
'contents' in obj) return true;
var success = true;
if (typeof XMLHttpRequest !== 'undefined') {
// Browser.
// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
var xhr = new XMLHttpRequest();
xhr.open('GET', obj.url, false);
xhr.responseType = 'arraybuffer'; // hint to the browser that we want binary data
xhr.overrideMimeType('text/plain; charset=x-user-defined'); // another hint
xhr.send(null);
if (xhr.status != 200 && xhr.status != 0) success = false;
if (xhr.response !== undefined) {
obj.contents = new Uint8Array(xhr.response || []);
} else {
obj.contents = intArrayFromString(xhr.responseText || '', true);
}
} else if (typeof read !== 'undefined') {
// Command-line.
try {
// WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
// read() will try to parse UTF8.
obj.contents = intArrayFromString(read(obj.url), true);
} catch (e) {
success = false;
}
} else {
throw new Error('Cannot load without read() or XMLHttpRequest.');
}
if (!success) ___setErrNo(ERRNO_CODES.EIO);
return success;
},
// Initializes the filesystems with stdin/stdout/stderr devices, given
// optional handlers.
init: function(input, output, error) {
// Make sure we initialize only once.
if (FS.init.initialized) return;
else FS.init.initialized = true;
// Default handlers.
if (!input) input = function() {
if (!input.cache || !input.cache.length) {
var result;
if (window && typeof window.prompt == 'function') {
// Browser.
result = window.prompt('Input: ');
} else if (typeof readline == 'function') {
// Command line.
result = readline();
}
if (!result) return null;
input.cache = intArrayFromString(result + '\n', true);
}
return input.cache.shift();
};
if (!output) output = function(val) {
if (!output.printer) {
if (typeof print == 'function') {
// Either console or custom print function defined.
output.printer = print;
} else if (console && typeof console.log == 'function') {
// Browser-like environment with a console.
output.printer = console.log;
} else {
// Fallback to a harmless no-op.
output.printer = function() {};
}
}
if (!output.buffer) output.buffer = [];
if (val === null || val === '\n'.charCodeAt(0)) {
output.printer(output.buffer.join(''));
output.buffer = [];
} else {
output.buffer.push(String.fromCharCode(val));
}
};
if (!error) error = output;
// Create the temporary folder.
FS.createFolder('/', 'tmp', true, true);
// Create the I/O devices.
var devFolder = FS.createFolder('/', 'dev', true, false);
var stdin = FS.createDevice(devFolder, 'stdin', input);
var stdout = FS.createDevice(devFolder, 'stdout', null, output);
var stderr = FS.createDevice(devFolder, 'stderr', null, error);
FS.createDevice(devFolder, 'tty', input, output);
// Create default streams.
FS.streams[1] = {
path: '/dev/stdin',
object: stdin,
position: 0,
isRead: true,
isWrite: false,
isAppend: false,
error: false,
eof: false,
ungotten: []
};
FS.streams[2] = {
path: '/dev/stdout',
object: stdout,
position: 0,
isRead: false,
isWrite: true,
isAppend: false,
error: false,
eof: false,
ungotten: []
};
FS.streams[3] = {
path: '/dev/stderr',
object: stderr,
position: 0,
isRead: false,
isWrite: true,
isAppend: false,
error: false,
eof: false,
ungotten: []
};
_stdin = allocate([1], 'void*', ALLOC_STATIC);
_stdout = allocate([2], 'void*', ALLOC_STATIC);
_stderr = allocate([3], 'void*', ALLOC_STATIC);
// Once initialized, permissions start having effect.
FS.ignorePermissions = false;
}
},
// ==========================================================================
// dirent.h
// ==========================================================================
__dirent_struct_layout: Runtime.generateStructInfo(null, '%struct.dirent'),
opendir__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', '__dirent_struct_layout'],
opendir: function(dirname) {
// DIR *opendir(const char *dirname);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/opendir.html
// NOTE: Calculating absolute path redundantly since we need to associate it
// with the opened stream.
var path = FS.absolutePath(Pointer_stringify(dirname));
if (path === null) {
___setErrNo(ERRNO_CODES.ENOENT);
return 0;
}
var target = FS.findObject(path);
if (target === null) return 0;
if (!target.isFolder) {
___setErrNo(ERRNO_CODES.ENOTDIR);
return 0;
} else if (!target.read) {
___setErrNo(ERRNO_CODES.EACCES);
return 0;
}
var id = FS.streams.length;
var contents = [];
for (var key in target.contents) contents.push(key);
FS.streams[id] = {
path: path,
object: target,
// An index into contents. Special values: -2 is ".", -1 is "..".
position: -2,
isRead: true,
isWrite: false,
isAppend: false,
error: false,
eof: false,
ungotten: [],
// Folder-specific properties:
// Remember the contents at the time of opening in an array, so we can
// seek between them relying on a single order.
contents: contents,
// Each stream has its own area for readdir() returns.
currentEntry: _malloc(___dirent_struct_layout.__size__)
};
return id;
},
closedir__deps: ['$FS', '__setErrNo', '$ERRNO_CODES'],
closedir: function(dirp) {
// int closedir(DIR *dirp);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/closedir.html
if (!FS.streams[dirp] || !FS.streams[dirp].object.isFolder) {
return ___setErrNo(ERRNO_CODES.EBADF);
} else {
_free(FS.streams[dirp].currentEntry);
delete FS.streams[dirp];
return 0;
}
},
telldir__deps: ['$FS', '__setErrNo', '$ERRNO_CODES'],
telldir: function(dirp) {
// long int telldir(DIR *dirp);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/telldir.html
if (!FS.streams[dirp] || !FS.streams[dirp].object.isFolder) {
return ___setErrNo(ERRNO_CODES.EBADF);
} else {
return FS.streams[dirp].position;
}
},
seekdir__deps: ['$FS', '__setErrNo', '$ERRNO_CODES'],
seekdir: function(dirp, loc) {
// void seekdir(DIR *dirp, long int loc);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/seekdir.html
if (!FS.streams[dirp] || !FS.streams[dirp].object.isFolder) {
___setErrNo(ERRNO_CODES.EBADF);
} else {
var entries = 0;
for (var key in FS.streams[dirp].contents) entries++;
if (loc >= entries) {
___setErrNo(ERRNO_CODES.EINVAL);
} else {
FS.streams[dirp].position = loc;
}
}
},
rewinddir__deps: ['seekdir'],
rewinddir: function(dirp) {
// void rewinddir(DIR *dirp);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/rewinddir.html
_seekdir(dirp, -2);
},
readdir_r__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', '__dirent_struct_layout'],
readdir_r: function(dirp, entry, result) {
// int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/readdir_r.html
if (!FS.streams[dirp] || !FS.streams[dirp].object.isFolder) {
return ___setErrNo(ERRNO_CODES.EBADF);
}
var stream = FS.streams[dirp];
var loc = stream.position;
var entries = 0;
for (var key in stream.contents) entries++;
if (loc < -2 || loc >= entries) {
{{{ makeSetValue('result', '0', '0', 'i8*') }}}
} else {
var name, inode;
if (loc === -2) {
name = '.';
inode = 1; // Really undefined.
} else if (loc === -1) {
name = '..';
inode = 1; // Really undefined.
} else {
name = stream.contents[loc];
inode = stream.object.contents[name].inodeNumber;
}
stream.position++;
var offsets = ___dirent_struct_layout;
{{{ makeSetValue('entry', 'offsets.d_ino', 'inode', 'i32') }}}
{{{ makeSetValue('entry', 'offsets.d_off', 'stream.position', 'i32') }}}
{{{ makeSetValue('entry', 'offsets.d_reclen', 'name.length + 1', 'i32') }}}
for (var i = 0; i < name.length; i++) {
{{{ makeSetValue('entry + offsets.d_name', 'i', 'name.charCodeAt(i)', 'i8') }}}
}
{{{ makeSetValue('entry + offsets.d_name', 'i', '0', 'i8') }}}
var type = stream.object.isDevice ? 2 // DT_CHR, character device.
: stream.object.isFolder ? 4 // DT_DIR, directory.
: stream.object.link !== undefined ? 10 // DT_LNK, symbolic link.
: 8; // DT_REG, regular file.
{{{ makeSetValue('entry', 'offsets.d_type', 'type', 'i8') }}}
{{{ makeSetValue('result', '0', 'entry', 'i8*') }}}
}
return 0;
},
readdir__deps: ['readdir_r', '__setErrNo', '$ERRNO_CODES'],
readdir: function(dirp) {
// struct dirent *readdir(DIR *dirp);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/readdir_r.html
if (!FS.streams[dirp] || !FS.streams[dirp].object.isFolder) {
___setErrNo(ERRNO_CODES.EBADF);
return 0;
} else {
if (!_readdir.result) _readdir.result = _malloc(4);
_readdir_r(dirp, FS.streams[dirp].currentEntry, _readdir.result);
if ({{{ makeGetValue(0, '_readdir.result', 'i8*') }}} === 0) {
return 0;
} else {
return FS.streams[dirp].currentEntry;
}
}
},
__01readdir64_: 'readdir',
// TODO: Check if we need to link any other aliases.
// ==========================================================================
// utime.h
// ==========================================================================
__utimbuf_struct_layout: Runtime.generateStructInfo(null, '%struct.utimbuf'),
utime__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', '__utimbuf_struct_layout'],
utime: function(path, times) {
// int utime(const char *path, const struct utimbuf *times);
// http://pubs.opengroup.org/onlinepubs/009695399/basedefs/utime.h.html
var time;
if (times) {
// NOTE: We don't keep track of access timestamps.
var offset = ___utimbuf_struct_layout.modtime;
time = {{{ makeGetValue('times', 'offset', 'i32') }}}
time *= 1000;
} else {
time = Date.now();
}
var file = FS.findObject(Pointer_stringify(path));
if (file === null) return -1;
if (!file.write) {
___setErrNo(ERRNO_CODES.EPERM);
return -1;
}
file.timestamp = time;
return 0;
},
// ==========================================================================
// libgen.h
// ==========================================================================
__libgenSplitName: function(path) {
if (path === 0 || {{{ makeGetValue('path', 0, 'i8') }}} === 0) {
// Null or empty results in '.'.
var me = ___libgenSplitName;
if (!me.ret) {
me.ret = allocate(['.'.charCodeAt(0), 0], 'i8', ALLOC_NORMAL);
}
return [me.ret, -1];
} else {
var slash = '/'.charCodeAt(0);
var allSlashes = true;
var slashPositions = [];
for (var i = 0; {{{ makeGetValue('path', 'i', 'i8') }}} !== 0; i++) {
if ({{{ makeGetValue('path', 'i', 'i8') }}} === slash) {
slashPositions.push(i);
} else {
allSlashes = false;
}
}
var length = i;
if (allSlashes) {
// All slashes result in a single slash.
{{{ makeSetValue('path', '1', '0', 'i8') }}}
return [path, -1];
} else {
// Strip trailing slashes.
while (slashPositions.length &&
slashPositions[slashPositions.length - 1] == length - 1) {
{{{ makeSetValue('path', 'slashPositions.pop(i)', '0', 'i8') }}}
length--;
}
return [path, slashPositions.pop()];
}
}
},
basename__deps: ['__libgenSplitName'],
basename: function(path) {
// char *basename(char *path);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/basename.html
var result = ___libgenSplitName(path);
return result[0] + result[1] + 1;
},
__xpg_basename: 'basename',
dirname__deps: ['__libgenSplitName'],
dirname: function(path) {
// char *dirname(char *path);
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/dirname.html
var result = ___libgenSplitName(path);
if (result[1] == 0) {
{{{ makeSetValue('result[0]', 1, '0', 'i8') }}}
} else if (result[1] !== -1) {
{{{ makeSetValue('result[0]', 'result[1]', '0', 'i8') }}}
}
return result[0];
},
// ==========================================================================
// sys/stat.h
// ==========================================================================
__stat_struct_layout: Runtime.generateStructInfo(null, '%struct.stat'),
stat__deps: ['$FS', '__stat_struct_layout'],
stat: function(path, buf, dontResolveLastLink) {
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/stat.html
// int stat(const char *path, struct stat *buf);
// NOTE: dontResolveLastLink is a shortcut for lstat(). It should never be
// used in client code.
var obj = FS.findObject(Pointer_stringify(path), dontResolveLastLink);
if (obj === null || !FS.forceLoadFile(obj)) return -1;
var offsets = ___stat_struct_layout;
// Constants.
{{{ makeSetValue('buf', 'offsets.st_nlink', '1', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_uid', '0', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_gid', '0', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_blksize', '4096', 'i32') }}}
// Variables.
{{{ makeSetValue('buf', 'offsets.st_ino', 'obj.inodeNumber', 'i32') }}}
var time = Math.floor(obj.timestamp / 1000);
if (offsets.st_atime === undefined) {
offsets.st_atime = offsets.st_atim.tv_sec;
offsets.st_mtime = offsets.st_mtim.tv_sec;
offsets.st_ctime = offsets.st_ctim.tv_sec;
var nanosec = (obj.timestamp % 1000) * 1000;
{{{ makeSetValue('buf', 'offsets.st_atim.tv_nsec', 'nanosec', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_mtim.tv_nsec', 'nanosec', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_ctim.tv_nsec', 'nanosec', 'i32') }}}
}
{{{ makeSetValue('buf', 'offsets.st_atime', 'time', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_mtime', 'time', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_ctime', 'time', 'i32') }}}
var mode = 0;
var size = 0;
var blocks = 0;
var dev = 0;
var rdev = 0;
if (obj.isDevice) {
// Device numbers reuse inode numbers.
dev = rdev = obj.inodeNumber;
size = blocks = 0;
mode = 0x2000; // S_IFCHR.
} else {
dev = 1;
rdev = 0;
// NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
// but this is not required by the standard.
if (obj.isFolder) {
size = 4096;
blocks = 1;
mode = 0x4000; // S_IFDIR.
} else {
var data = obj.contents || obj.link;
size = data.length;
blocks = Math.ceil(data.length / 4096);
mode = obj.link === undefined ? 0x8000 : 0xA000; // S_IFREG, S_IFLNK.
}
}
{{{ makeSetValue('buf', 'offsets.st_dev', 'dev', 'i64') }}}
{{{ makeSetValue('buf', 'offsets.st_rdev', 'rdev', 'i64') }}}
// NOTE: These two may be i64, depending on compilation options.
{{{ makeSetValue('buf', 'offsets.st_size', 'size', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.st_blocks', 'blocks', 'i32') }}}
if (obj.read) mode |= 0x16D; // S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH.
if (obj.write) mode |= 0x92; // S_IWUSR | S_IWGRP | S_IWOTH.
{{{ makeSetValue('buf', 'offsets.st_mode', 'mode', 'i32') }}}
return 0;
},
lstat__deps: ['stat'],
lstat: function(path, buf) {
// int lstat(const char *path, struct stat *buf);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/lstat.html
return _stat(path, buf, true);
},
fstat__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', 'stat'],
fstat: function(fildes, buf) {
// int fstat(int fildes, struct stat *buf);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/fstat.html
if (!FS.streams[fildes]) {
___setErrNo(ERRNO_CODES.EBADF);
return -1;
} else {
var pathArray = intArrayFromString(FS.streams[fildes].path);
var pathPtr = allocate(pathArray, 'i8', ALLOC_NORMAL);
var result = _stat(pathPtr, buf);
_free(pathPtr);
return result;
}
},
mknod__deps: ['$FS', '__setErrNo', '$ERRNO_CODES'],
mknod: function(path, mode, dev) {
// int mknod(const char *path, mode_t mode, dev_t dev);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/mknod.html
if (dev !== 0 || !(mode & 0xC000)) { // S_IFREG | S_IFDIR.
// Can't create devices or pipes through mknod().
___setErrNo(ERRNO_CODES.EINVAL);
return -1;
} else {
var properties = {contents: [], isFolder: Boolean(mode & 0x4000)}; // S_IFDIR.
path = FS.analyzePath(Pointer_stringify(path));
try {
FS.createObject(path.parentObject, path.name, properties,
mode & 0x100, mode & 0x80); // S_IRUSR, S_IWUSR.
return 0;
} catch (e) {
return -1;
}
}
},
mkdir__deps: ['mknod'],
mkdir: function(path, mode) {
// int mkdir(const char *path, mode_t mode);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/mkdir.html
return _mknod(path, 0x4000 | (mode & 0x180), 0); // S_IFDIR, S_IRUSR | S_IWUSR.
},
mkfifo__deps: ['__setErrNo', '$ERRNO_CODES'],
mkfifo: function(path, mode) {
// int mkfifo(const char *path, mode_t mode);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/mkfifo.html
// NOTE: We support running only a single process, and named pipes require
// blocking, which we can't provide. The error code is not very
// accurate, but it's the closest among those allowed in the standard
// and unlikely to result in retries.
___setErrNo(ERRNO_CODES.EROFS);
return -1;
},
chmod__deps: ['$FS'],
chmod: function(path, mode) {
// int chmod(const char *path, mode_t mode);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/chmod.html
var obj = FS.findObject(Pointer_stringify(path));
if (obj === null) return -1;
obj.read = mode & 0x100; // S_IRUSR.
obj.write = mode & 0x80; // S_IWUSR.
obj.timestamp = Date.now();
return 0;
},
fchmod__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', 'chmod'],
fchmod: function(fildes, mode) {
// int fchmod(int fildes, mode_t mode);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/fchmod.html
if (!FS.streams[fildes]) {
___setErrNo(ERRNO_CODES.EBADF);
return -1;
} else {
var pathArray = intArrayFromString(FS.streams[fildes].path);
var pathPtr = allocate(pathArray, 'i8', ALLOC_NORMAL);
var result = _chmod(pathPtr, mode);
_free(pathPtr);
return result;
}
},
umask__deps: ['$FS'],
umask: function(newMask) {
// mode_t umask(mode_t cmask);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/umask.html
// NOTE: This value isn't actually used for anything.
if (_umask.cmask === undefined) _umask.cmask = 0x1FF; // S_IRWXU | S_IRWXG | S_IRWXO.
var oldMask = _umask.cmask;
_umask.cmask = newMask;
return oldMask;
},
__01fstat64_: 'fstat',
__01stat64_: 'stat',
__01lstat64_: 'lstat',
// TODO: Check if other aliases are needed.
// ==========================================================================
// sys/statvfs.h
// ==========================================================================
__statvfs_struct_layout: Runtime.generateStructInfo(null, '%struct.statvfs'),
statvfs__deps: ['$FS', '__statvfs_struct_layout'],
statvfs: function(path, buf) {
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/stat.html
// int statvfs(const char *restrict path, struct statvfs *restrict buf);
var offsets = ___statvfs_struct_layout;
// NOTE: None of the constants here are true. We're just returning safe and
// sane values.
{{{ makeSetValue('buf', 'offsets.f_bsize', '4096', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_frsize', '4096', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_blocks', '1000000', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_bfree', '500000', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_bavail', '500000', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_files', 'FS.nextInode', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_ffree', '1000000', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_favail', '1000000', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_fsid', '42', 'i32') }}}
{{{ makeSetValue('buf', 'offsets.f_flag', '2', 'i32') }}} // ST_NOSUID
{{{ makeSetValue('buf', 'offsets.f_namemax', '255', 'i32') }}}
return 0;
},
fstatvfs__deps: ['statvfs'],
fstatvfs: function(fildes, buf) {
// int fstatvfs(int fildes, struct statvfs *buf);
// http://pubs.opengroup.org/onlinepubs/009604499/functions/statvfs.html
return _statvfs(0, buf);
},
__01statvfs64_: 'statvfs',
__01fstatvfs64_: 'fstatvfs',
// ==========================================================================
// fcntl.h
// ==========================================================================
__flock_struct_layout: Runtime.generateStructInfo(null, '%struct.flock'),
open__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', '__dirent_struct_layout'],
open: function(path, oflag, mode) {
// int open(const char *path, int oflag, ...);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/open.html
// NOTE: This implementation tries to mimic glibc rather that strictly
// following the POSIX standard.
// Simplify flags.
var accessMode = oflag & 0x3; // O_ACCMODE.
var isWrite = accessMode != 0x0; // O_RDONLY.
var isRead = accessMode != 0x1; // O_WRONLY.
var isCreate = Boolean(oflag & 0x40); // O_CREAT.
var isExistCheck = Boolean(oflag & 0x80); // O_EXCL.
var isTruncate = Boolean(oflag & 0x200); // O_TRUNC.
var isAppend = Boolean(oflag & 0x400); // O_APPEND.
// Verify path.
var origPath = path;
path = FS.analyzePath(Pointer_stringify(path));
if (!path.parentExists) {
___setErrNo(path.error);
return -1;
}
var target = path.object || null;
// Verify the file exists, create if needed and allowed.
if (target) {
if (isCreate && isExistCheck) {
___setErrNo(ERRNO_CODES.EEXIST);
return -1;
}
if ((isWrite || isCreate || isTruncate) && target.isFolder) {
___setErrNo(ERRNO_CODES.EISDIR);
return -1;
}
if (isRead && !target.read || isWrite && !target.write) {
___setErrNo(ERRNO_CODES.EACCES);
return -1;
}
if (isTruncate && !target.isDevice) {
target.contents = [];
} else {
if (!FS.forceLoadFile(target)) {
___setErrNo(ERRNO_CODES.EIO);
return -1;
}
}
} else {
if (!isCreate) {
___setErrNo(ERRNO_CODES.ENOENT);
return -1;
}
if (!path.parentObject.write) {
___setErrNo(ERRNO_CODES.EACCES);
return -1;
}
target = FS.createDataFile(path.parentObject, path.name, [],
mode & 0x100, mode & 0x80); // S_IRUSR, S_IWUSR.
}
// Actually create an open stream.
var id = FS.streams.length;
if (target.isFolder) {
var entryBuffer = 0;
if (___dirent_struct_layout) {
entryBuffer = _malloc(___dirent_struct_layout.__size__);
}
var contents = [];
for (var key in target.contents) contents.push(key);
FS.streams[id] = {
path: path.path,
object: target,
// An index into contents. Special values: -2 is ".", -1 is "..".
position: -2,
isRead: true,
isWrite: false,
isAppend: false,
error: false,
eof: false,
ungotten: [],
// Folder-specific properties:
// Remember the contents at the time of opening in an array, so we can
// seek between them relying on a single order.
contents: contents,
// Each stream has its own area for readdir() returns.
currentEntry: entryBuffer
};
} else {
FS.streams[id] = {
path: path.path,
object: target,
position: 0,
isRead: isRead,
isWrite: isWrite,
isAppend: isAppend,
error: false,
eof: false,
ungotten: []
};
}
return id;
},
creat__deps: ['open'],
creat: function(path, mode) {
// int creat(const char *path, mode_t mode);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/creat.html
return _open(path, 0x241, mode); // O_WRONLY | O_CREAT | O_TRUNC.
},
fcntl__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', '__flock_struct_layout'],
fcntl: function(fildes, cmd, arg) {
// int fcntl(int fildes, int cmd, ...);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/fcntl.html
if (!(fildes in FS.streams)) {
___setErrNo(ERRNO_CODES.EBADF);
return -1;
}
var stream = FS.streams[fildes];
switch (cmd) {
case 0: // F_DUPFD.
if (arg < 0) {
___setErrNo(ERRNO_CODES.EINVAL);
return -1;
}
var newStream = {};
for (var member in stream) {
newStream[member] = stream[member];
}
if (arg in FS.streams) arg = FS.streams.length;
FS.streams[arg] = newStream;
return arg;
case 1: // F_GETFD.
case 2: // F_SETFD.
return 0; // FD_CLOEXEC makes no sense for a single process.
case 3: // F_GETFL.
var flags = 0;
if (stream.isRead && stream.isWrite) flags = 0x2; // O_RDWR.
else if (!stream.isRead && stream.isWrite) flags = 0x1; // O_WRONLY.
else if (stream.isRead && !stream.isWrite) flags = 0x0; // O_RDONLY.
if (stream.isAppend) flags |= 0x400; // O_APPEND.
// Synchronization and blocking flags are irrelevant to us.
return flags;
case 4: // F_SETFL.
stream.isAppend = Boolean(arg | 0x400); // O_APPEND.
// Synchronization and blocking flags are irrelevant to us.
return 0;
case 5: // F_GETLK.
var offset = ___flock_struct_layout.l_type;
// We're always unlocked.
{{{ makeSetValue('arg', 'offset', '2', 'i16') }}} // F_UNLCK.
return 0;
case 6: // F_SETLK.
case 7: // F_SETLKW.
// Pretend that the locking is successful.
return 0;
case 8: // F_SETOWN.
case 9: // F_GETOWN.
// These are for sockets. We don't have them implemented (yet?).
___setErrNo(ERRNO_CODES.EINVAL);
return -1;