-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathlibrary.js
7128 lines (6771 loc) · 246 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
//"use strict";
// 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,
_impure_ptr: 0,
$FS__deps: ['$ERRNO_CODES', '__setErrNo', 'stdin', 'stdout', 'stderr', '_impure_ptr'],
$FS__postset: '__ATINIT__.unshift({ func: function() { if (!Module["noFSInit"] && !FS.init.initialized) FS.init() } });' +
'__ATMAIN__.push({ func: function() { FS.ignorePermissions = false } });' +
'__ATEXIT__.push({ func: function() { FS.quit() } });' +
// export some names through closure
'Module["FS_createFolder"] = FS.createFolder;' +
'Module["FS_createPath"] = FS.createPath;' +
'Module["FS_createDataFile"] = FS.createDataFile;' +
'Module["FS_createPreloadedFile"] = FS.createPreloadedFile;' +
'Module["FS_createLazyFile"] = FS.createLazyFile;' +
'Module["FS_createLink"] = FS.createLink;' +
'Module["FS_createDevice"] = FS.createDevice;',
$FS: {
// 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 is kept as a dense array. It may contain |null| to fill in
// holes, however.
streams: [null],
#if ASSERTIONS
checkStreams: function() {
for (var i in FS.streams) assert(i >= 0 && i < FS.streams.length); // no keys not in dense span
for (var i = 0; i < FS.streams.length; i++) assert(typeof FS.streams[i] == 'object'); // no non-null holes in dense span
},
#endif
// Whether we are currently ignoring permissions. Useful when preparing the
// filesystem and creating files inside read-only folders.
// This is set to false when the runtime is initialized, allowing you
// to modify the filesystem freely before run() is called.
ignorePermissions: true,
joinPath: function(parts, forceRelative) {
var ret = parts[0];
for (var i = 1; i < parts.length; i++) {
if (ret[ret.length-1] != '/') ret += '/';
ret += parts[i];
}
if (forceRelative && ret[0] == '/') ret = ret.substr(1);
return ret;
},
// 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
};
#if FS_LOG
var inputPath = path;
function log() {
Module['print']('FS.analyzePath("' + inputPath + '", ' +
dontResolveLastLink + ', ' +
linksVisited + ') => {' +
'isRoot: ' + ret.isRoot + ', ' +
'exists: ' + ret.exists + ', ' +
'error: ' + ret.error + ', ' +
'name: "' + ret.name + '", ' +
'path: "' + ret.path + '", ' +
'object: ' + ret.object + ', ' +
'parentExists: ' + ret.parentExists + ', ' +
'parentPath: "' + ret.parentPath + '", ' +
'parentObject: ' + ret.parentObject + '}');
}
#endif
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('/'));
ret = FS.analyzePath([link].concat(path).join('/'),
dontResolveLastLink, linksVisited + 1);
#if FS_LOG
log();
#endif
return ret;
}
traversed.push(target);
if (path.length == 0) {
ret.exists = true;
ret.path = traversed.join('/');
ret.object = current;
}
}
}
#if FS_LOG
log();
#endif
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 are still resolved.
findObject: function(path, dontResolveLastLink) {
FS.ensureRoot();
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 FS_LOG
Module['print']('FS.createObject("' + parent + '", ' +
'"' + name + '", ' +
JSON.stringify(properties) + ', ' +
canRead + ', ' +
canWrite + ')');
#endif
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 = new Array(data.length);
for (var i = 0, len = data.length; i < len; ++i) dataArray[i] = data.charCodeAt(i);
data = dataArray;
}
var properties = {
isDevice: false,
contents: data.subarray ? data.subarray(0) : data // as an optimization, create a new array wrapper (not buffer) here, to help JS engines understand this object
};
return FS.createFile(parent, name, properties, canRead, canWrite);
},
// Creates a file record for lazy-loading from a URL. XXX This requires a synchronous
// XHR, which is not possible in browsers except in a web worker! Use preloading,
// either --preload-file in emcc or FS.createPreloadedFile
createLazyFile: function(parent, name, url, canRead, canWrite) {
if (typeof XMLHttpRequest !== 'undefined') {
if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
// Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
var LazyUint8Array = function(chunkSize, length) {
this.length = length;
this.chunkSize = chunkSize;
this.chunks = []; // Loaded chunks. Index is the chunk number
}
LazyUint8Array.prototype.get = function(idx) {
if (idx > this.length-1 || idx < 0) {
return undefined;
}
var chunkOffset = idx % chunkSize;
var chunkNum = Math.floor(idx / chunkSize);
return this.getter(chunkNum)[chunkOffset];
}
LazyUint8Array.prototype.setDataGetter = function(getter) {
this.getter = getter;
}
// Find length
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url, false);
xhr.send(null);
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
var datalength = Number(xhr.getResponseHeader("Content-length"));
var header;
var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
#if SMALL_XHR_CHUNKS
var chunkSize = 1024; // Chunk size in bytes
#else
var chunkSize = 1024*1024; // Chunk size in bytes
#endif
if (!hasByteServing) chunkSize = datalength;
// Function to get a range from the remote URL.
var doXHR = (function(from, to) {
if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
// Some hints to the browser that we want binary data.
if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
xhr.send(null);
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
if (xhr.response !== undefined) {
return new Uint8Array(xhr.response || []);
} else {
return intArrayFromString(xhr.responseText || '', true);
}
});
var lazyArray = new LazyUint8Array(chunkSize, datalength);
lazyArray.setDataGetter(function(chunkNum) {
var start = chunkNum * lazyArray.chunkSize;
var end = (chunkNum+1) * lazyArray.chunkSize - 1; // including this byte
end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
lazyArray.chunks[chunkNum] = doXHR(start, end);
}
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
return lazyArray.chunks[chunkNum];
});
var properties = { isDevice: false, contents: lazyArray };
} else {
var properties = { isDevice: false, url: url };
}
return FS.createFile(parent, name, properties, canRead, canWrite);
},
// Preloads a file asynchronously. You can call this before run, for example in
// preRun. run will be delayed until this file arrives and is set up.
// If you call it after run(), you may want to pause the main loop until it
// completes, if so, you can use the onload parameter to be notified when
// that happens.
// In addition to normally creating the file, we also asynchronously preload
// the browser-friendly versions of it: For an image, we preload an Image
// element and for an audio, and Audio. These are necessary for SDL_Image
// and _Mixer to find the files in preloadedImages/Audios.
// You can also call this with a typed array instead of a url. It will then
// do preloading for the Image/Audio part, as if the typed array were the
// result of an XHR that you did manually.
createPreloadedFile: function(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile) {
Browser.ensureObjects();
var fullname = FS.joinPath([parent, name], true);
function processData(byteArray) {
function finish(byteArray) {
if (!dontCreateFile) {
FS.createDataFile(parent, name, byteArray, canRead, canWrite);
}
if (onload) onload();
removeRunDependency('cp ' + fullname);
}
var handled = false;
Module['preloadPlugins'].forEach(function(plugin) {
if (handled) return;
if (plugin['canHandle'](fullname)) {
plugin['handle'](byteArray, fullname, finish, function() {
if (onerror) onerror();
removeRunDependency('cp ' + fullname);
});
handled = true;
}
});
if (!handled) finish(byteArray);
}
addRunDependency('cp ' + fullname);
if (typeof url == 'string') {
Browser.asyncLoad(url, function(byteArray) {
processData(byteArray);
}, onerror);
} else {
processData(url);
}
},
// 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 || obj.contents) return true;
var success = true;
if (typeof XMLHttpRequest !== 'undefined') {
throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");
} else if (Module['read']) {
// 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(Module['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;
},
ensureRoot: function() {
if (FS.root) return;
// The main file system tree. All the contents are inside this.
FS.root = {
read: true,
write: true,
isFolder: true,
isDevice: false,
timestamp: Date.now(),
inodeNumber: 1,
contents: {}
};
},
// Initializes the filesystems with stdin/stdout/stderr devices, given
// optional handlers.
init: function(input, output, error) {
// Make sure we initialize only once.
assert(!FS.init.initialized, 'FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)');
FS.init.initialized = true;
FS.ensureRoot();
// Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
input = input || Module['stdin'];
output = output || Module['stdout'];
error = error || Module['stderr'];
// Default handlers.
var stdinOverridden = true, stdoutOverridden = true, stderrOverridden = true;
if (!input) {
stdinOverridden = false;
input = function() {
if (!input.cache || !input.cache.length) {
var result;
if (typeof window != 'undefined' &&
typeof window.prompt == 'function') {
// Browser.
result = window.prompt('Input: ');
if (result === null) result = String.fromCharCode(0); // cancel ==> EOF
} else if (typeof readline == 'function') {
// Command line.
result = readline();
}
if (!result) result = '';
input.cache = intArrayFromString(result + '\n', true);
}
return input.cache.shift();
};
}
var utf8 = new Runtime.UTF8Processor();
function simpleOutput(val) {
if (val === null || val === '\n'.charCodeAt(0)) {
output.printer(output.buffer.join(''));
output.buffer = [];
} else {
output.buffer.push(utf8.processCChar(val));
}
}
if (!output) {
stdoutOverridden = false;
output = simpleOutput;
}
if (!output.printer) output.printer = Module['print'];
if (!output.buffer) output.buffer = [];
if (!error) {
stderrOverridden = false;
error = simpleOutput;
}
if (!error.printer) error.printer = Module['print'];
if (!error.buffer) error.buffer = [];
// Create the temporary folder, if not already created
try {
FS.createFolder('/', 'tmp', true, true);
} catch(e) {}
// Create the I/O devices.
var devFolder = FS.createFolder('/', 'dev', true, true);
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,
isTerminal: !stdinOverridden,
error: false,
eof: false,
ungotten: []
};
FS.streams[2] = {
path: '/dev/stdout',
object: stdout,
position: 0,
isRead: false,
isWrite: true,
isAppend: false,
isTerminal: !stdoutOverridden,
error: false,
eof: false,
ungotten: []
};
FS.streams[3] = {
path: '/dev/stderr',
object: stderr,
position: 0,
isRead: false,
isWrite: true,
isAppend: false,
isTerminal: !stderrOverridden,
error: false,
eof: false,
ungotten: []
};
// Allocate these on the stack (and never free, we are called from ATINIT or earlier), to keep their locations low
_stdin = allocate([1], 'void*', ALLOC_STACK);
_stdout = allocate([2], 'void*', ALLOC_STACK);
_stderr = allocate([3], 'void*', ALLOC_STACK);
// Other system paths
FS.createPath('/', 'dev/shm/tmp', true, true); // temp files
// Newlib initialization
for (var i = FS.streams.length; i < Math.max(_stdin, _stdout, _stderr) + {{{ QUANTUM_SIZE }}}; i++) {
FS.streams[i] = null; // Make sure to keep FS.streams dense
}
FS.streams[_stdin] = FS.streams[1];
FS.streams[_stdout] = FS.streams[2];
FS.streams[_stderr] = FS.streams[3];
#if ASSERTIONS
FS.checkStreams();
assert(FS.streams.length < 1024); // at this early stage, we should not have a large set of file descriptors - just a few
#endif
__impure_ptr = allocate([ allocate(
{{{ Runtime.QUANTUM_SIZE === 4 ? '[0, 0, 0, 0, _stdin, 0, 0, 0, _stdout, 0, 0, 0, _stderr, 0, 0, 0]' : '[0, _stdin, _stdout, _stderr]' }}},
'void*', ALLOC_STATIC) ], 'void*', ALLOC_STATIC);
},
quit: function() {
if (!FS.init.initialized) return;
// Flush any partially-printed lines in stdout and stderr. Careful, they may have been closed
if (FS.streams[2] && FS.streams[2].object.output.buffer.length > 0) FS.streams[2].object.output('\n'.charCodeAt(0));
if (FS.streams[3] && FS.streams[3].object.output.buffer.length > 0) FS.streams[3].object.output('\n'.charCodeAt(0));
},
// Standardizes a path. Useful for making comparisons of pathnames work in a consistent manner.
// For example, ./file and file are really the same, so this function will remove ./
standardizePath: function(path) {
if (path.substr(0, 2) == './') path = path.substr(2);
return path;
},
deleteFile: function(path) {
path = FS.analyzePath(path);
if (!path.parentExists || !path.exists) {
throw 'Invalid path ' + path;
}
delete path.parentObject.contents[path.name];
}
},
// ==========================================================================
// dirent.h
// ==========================================================================
__dirent_struct_layout: Runtime.generateStructInfo(['d_ino', 'd_name', 'd_off', 'd_reclen', 'd_type'], '%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; // Keep dense
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__)
};
#if ASSERTIONS
FS.checkStreams();
#endif
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);
FS.streams[dirp] = null;
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, type;
if (loc === -2) {
name = '.';
inode = 1; // Really undefined.
type = 4; //DT_DIR
} else if (loc === -1) {
name = '..';
inode = 1; // Really undefined.
type = 4; //DT_DIR
} else {
var object;
name = stream.contents[loc];
object = stream.object.contents[name];
inode = object.inodeNumber;
type = object.isDevice ? 2 // DT_CHR, character device.
: object.isFolder ? 4 // DT_DIR, directory.
: object.link !== undefined ? 10 // DT_LNK, symbolic link.
: 8; // DT_REG, regular file.
}
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') }}}
{{{ 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(['actime', 'modtime'], '%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([
'st_dev',
'st_ino',
'st_mode',
'st_nlink',
'st_uid',
'st_gid',
'st_rdev',
'st_size',
'st_atime',
'st_spare1',
'st_mtime',
'st_spare2',
'st_ctime',
'st_spare3',
'st_blksize',
'st_blocks',
'st_spare4'], '%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', 'i32') }}};
{{{ makeSetValue('buf', 'offsets.st_rdev', 'rdev', 'i32') }}};
{{{ 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);
return _stat(allocate(pathArray, 'i8', ALLOC_STACK), buf);
}
},
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'],