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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
|
mergeInto(LibraryManager.library, {
$FS__deps: ['$ERRNO_CODES', '$ERRNO_MESSAGES', '__setErrNo', '$VFS', '$PATH', '$TTY', '$MEMFS', 'stdin', 'stdout', 'stderr', 'fflush'],
$FS__postset: 'FS.staticInit();' +
'__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: {
root: null,
devices: [null],
streams: [null],
nextInode: 1,
nameTable: null,
currentPath: '/',
initialized: false,
// 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,
ErrnoError: (function() {
function ErrnoError(errno) {
this.errno = errno;
for (var key in ERRNO_CODES) {
if (ERRNO_CODES[key] === errno) {
this.code = key;
break;
}
}
this.message = ERRNO_MESSAGES[errno];
};
ErrnoError.prototype = new Error();
ErrnoError.prototype.constructor = ErrnoError;
return ErrnoError;
}()),
handleFSError: function(e) {
if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + new Error().stack;
return ___setErrNo(e.errno);
},
//
// paths
//
cwd: function() {
return FS.currentPath;
},
lookupPath: function(path, opts) {
path = PATH.resolve(FS.currentPath, path);
opts = opts || { recurse_count: 0 };
if (opts.recurse_count > 8) { // max recursive lookup of 8
throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
}
// split the path
var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
return !!p;
}), false);
// start at the root
var current = FS.root;
var current_path = '/';
for (var i = 0; i < parts.length; i++) {
var islast = (i === parts.length-1);
if (islast && opts.parent) {
// stop resolving
break;
}
current = FS.lookupNode(current, parts[i]);
current_path = PATH.join(current_path, parts[i]);
// jump to the mount's root node if this is a mountpoint
if (FS.isMountpoint(current)) {
current = current.mount.root;
}
// follow symlinks
// by default, lookupPath will not follow a symlink if it is the final path component.
// setting opts.follow = true will override this behavior.
if (!islast || opts.follow) {
var count = 0;
while (FS.isLink(current.mode)) {
var link = FS.readlink(current_path);
current_path = PATH.resolve(PATH.dirname(current_path), link);
var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
current = lookup.node;
if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
}
}
}
}
return { path: current_path, node: current };
},
getPath: function(node) {
var path;
while (true) {
if (FS.isRoot(node)) {
return path ? PATH.join(node.mount.mountpoint, path) : node.mount.mountpoint;
}
path = path ? PATH.join(node.name, path) : node.name;
node = node.parent;
}
},
//
// nodes
//
hashName: function(parentid, name) {
var hash = 0;
for (var i = 0; i < name.length; i++) {
hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
}
return ((parentid + hash) >>> 0) % FS.nameTable.length;
},
hashAddNode: function(node) {
var hash = FS.hashName(node.parent.id, node.name);
node.name_next = FS.nameTable[hash];
FS.nameTable[hash] = node;
},
hashRemoveNode: function(node) {
var hash = FS.hashName(node.parent.id, node.name);
if (FS.nameTable[hash] === node) {
FS.nameTable[hash] = node.name_next;
} else {
var current = FS.nameTable[hash];
while (current) {
if (current.name_next === node) {
current.name_next = node.name_next;
break;
}
current = current.name_next;
}
}
},
lookupNode: function(parent, name) {
var err = FS.mayLookup(parent);
if (err) {
throw new FS.ErrnoError(err);
}
var hash = FS.hashName(parent.id, name);
for (var node = FS.nameTable[hash]; node; node = node.name_next) {
if (node.parent.id === parent.id && node.name === name) {
return node;
}
}
// if we failed to find it in the cache, call into the VFS
return FS.lookup(parent, name);
},
createNode: function(parent, name, mode, rdev) {
var node = {
id: FS.nextInode++,
name: name,
mode: mode,
node_ops: {},
stream_ops: {},
rdev: rdev,
parent: null,
mount: null
};
if (!parent) {
parent = node; // root node sets parent to itself
}
node.parent = parent;
node.mount = parent.mount;
// compatibility
var readMode = {{{ cDefine('S_IRUGO') }}} | {{{ cDefine('S_IXUGO') }}};
var writeMode = {{{ cDefine('S_IWUGO') }}};
// NOTE we must use Object.defineProperties instead of individual calls to
// Object.defineProperty in order to make closure compiler happy
Object.defineProperties(node, {
read: {
get: function() { return (node.mode & readMode) === readMode; },
set: function(val) { val ? node.mode |= readMode : node.mode &= ~readMode; }
},
write: {
get: function() { return (node.mode & writeMode) === writeMode; },
set: function(val) { val ? node.mode |= writeMode : node.mode &= ~writeMode; }
},
isFolder: {
get: function() { return FS.isDir(node.mode); },
},
isDevice: {
get: function() { return FS.isChrdev(node.mode); },
},
});
FS.hashAddNode(node);
return node;
},
destroyNode: function(node) {
FS.hashRemoveNode(node);
},
isRoot: function(node) {
return node === node.parent;
},
isMountpoint: function(node) {
return node.mounted;
},
isFile: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFREG') }}};
},
isDir: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFDIR') }}};
},
isLink: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFLNK') }}};
},
isChrdev: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFCHR') }}};
},
isBlkdev: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFBLK') }}};
},
isFIFO: function(mode) {
return (mode & {{{ cDefine('S_IFMT') }}}) === {{{ cDefine('S_IFIFO') }}};
},
isSocket: function(mode) {
return (mode & {{{ cDefine('S_IFSOCK') }}}) === {{{ cDefine('S_IFSOCK') }}};
},
//
// permissions
//
flagModes: {
'"r"': {{{ cDefine('O_RDONLY') }}},
'"rs"': {{{ cDefine('O_RDONLY') }}} | {{{ cDefine('O_SYNC') }}},
'"r+"': {{{ cDefine('O_RDWR') }}},
'"w"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}},
'"wx"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}} | {{{ cDefine('O_EXCL') }}},
'"xw"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}} | {{{ cDefine('O_EXCL') }}},
'"w+"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}},
'"wx+"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}} | {{{ cDefine('O_EXCL') }}},
'"xw+"': {{{ cDefine('O_TRUNC') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}} | {{{ cDefine('O_EXCL') }}},
'"a"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}},
'"ax"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}} | {{{ cDefine('O_EXCL') }}},
'"xa"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_WRONLY') }}} | {{{ cDefine('O_EXCL') }}},
'"a+"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}},
'"ax+"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}} | {{{ cDefine('O_EXCL') }}},
'"xa+"': {{{ cDefine('O_APPEND') }}} | {{{ cDefine('O_CREAT') }}} | {{{ cDefine('O_RDWR') }}} | {{{ cDefine('O_EXCL') }}}
},
// convert the 'r', 'r+', etc. to it's corresponding set of O_* flags
modeStringToFlags: function(str) {
var flags = FS.flagModes[str];
if (typeof flags === 'undefined') {
throw new Error('Unknown file open mode: ' + str);
}
return flags;
},
// convert O_* bitmask to a string for nodePermissions
flagsToPermissionString: function(flag) {
var accmode = flag & {{{ cDefine('O_ACCMODE') }}};
var perms = ['r', 'w', 'rw'][accmode];
if ((flag & {{{ cDefine('O_TRUNC') }}})) {
perms += 'w';
}
return perms;
},
nodePermissions: function(node, perms) {
if (FS.ignorePermissions) {
return 0;
}
// return 0 if any user, group or owner bits are set.
if (perms.indexOf('r') !== -1 && !(node.mode & {{{ cDefine('S_IRUGO') }}})) {
return ERRNO_CODES.EACCES;
} else if (perms.indexOf('w') !== -1 && !(node.mode & {{{ cDefine('S_IWUGO') }}})) {
return ERRNO_CODES.EACCES;
} else if (perms.indexOf('x') !== -1 && !(node.mode & {{{ cDefine('S_IXUGO') }}})) {
return ERRNO_CODES.EACCES;
}
return 0;
},
mayLookup: function(dir) {
return FS.nodePermissions(dir, 'x');
},
mayCreate: function(dir, name) {
try {
var node = FS.lookupNode(dir, name);
return ERRNO_CODES.EEXIST;
} catch (e) {
}
return FS.nodePermissions(dir, 'wx');
},
mayDelete: function(dir, name, isdir) {
var node;
try {
node = FS.lookupNode(dir, name);
} catch (e) {
return e.errno;
}
var err = FS.nodePermissions(dir, 'wx');
if (err) {
return err;
}
if (isdir) {
if (!FS.isDir(node.mode)) {
return ERRNO_CODES.ENOTDIR;
}
if (FS.isRoot(node) || FS.getPath(node) === FS.currentPath) {
return ERRNO_CODES.EBUSY;
}
} else {
if (FS.isDir(node.mode)) {
return ERRNO_CODES.EISDIR;
}
}
return 0;
},
mayOpen: function(node, flags) {
if (!node) {
return ERRNO_CODES.ENOENT;
}
if (FS.isLink(node.mode)) {
return ERRNO_CODES.ELOOP;
} else if (FS.isDir(node.mode)) {
if ((flags & {{{ cDefine('O_ACCMODE') }}}) !== {{{ cDefine('O_RDONLY')}}} || // opening for write
(flags & {{{ cDefine('O_TRUNC') }}})) {
return ERRNO_CODES.EISDIR;
}
}
return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
},
//
// streams
//
MAX_OPEN_FDS: 4096,
nextfd: function(fd_start, fd_end) {
fd_start = fd_start || 1;
fd_end = fd_end || FS.MAX_OPEN_FDS;
for (var fd = fd_start; fd <= fd_end; fd++) {
if (!FS.streams[fd]) {
return fd;
}
}
throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
},
getStream: function(fd) {
return FS.streams[fd];
},
// TODO parameterize this function such that a stream
// object isn't directly passed in. not possible until
// SOCKFS is completed.
createStream: function(stream, fd_start, fd_end) {
var fd = FS.nextfd(fd_start, fd_end);
stream.fd = fd;
// compatibility
Object.defineProperties(stream, {
object: {
get: function() { return stream.node; },
set: function(val) { stream.node = val; }
},
isRead: {
get: function() { return (stream.flags & {{{ cDefine('O_ACCMODE') }}}) !== {{{ cDefine('O_WRONLY') }}}; }
},
isWrite: {
get: function() { return (stream.flags & {{{ cDefine('O_ACCMODE') }}}) !== {{{ cDefine('O_RDONLY') }}}; }
},
isAppend: {
get: function() { return (stream.flags & {{{ cDefine('O_APPEND') }}}); }
}
});
FS.streams[fd] = stream;
return stream;
},
closeStream: function(fd) {
FS.streams[fd] = null;
},
//
// devices
//
// each character device consists of a device id + stream operations.
// when a character device node is created (e.g. /dev/stdin) it is
// assigned a device id that lets us map back to the actual device.
// by default, each character device stream (e.g. _stdin) uses chrdev_stream_ops.
// however, once opened, the stream's operations are overridden with
// the operations of the device its underlying node maps back to.
chrdev_stream_ops: {
open: function(stream) {
var device = FS.getDevice(stream.node.rdev);
// override node's stream ops with the device's
stream.stream_ops = device.stream_ops;
// forward the open call
if (stream.stream_ops.open) {
stream.stream_ops.open(stream);
}
},
llseek: function() {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
}
},
major: function(dev) {
return ((dev) >> 8);
},
minor: function(dev) {
return ((dev) & 0xff);
},
makedev: function(ma, mi) {
return ((ma) << 8 | (mi));
},
registerDevice: function(dev, ops) {
FS.devices[dev] = { stream_ops: ops };
},
getDevice: function(dev) {
return FS.devices[dev];
},
//
// core
//
mount: function(type, opts, mountpoint) {
var mount = {
type: type,
opts: opts,
mountpoint: mountpoint,
root: null
};
var lookup;
if (mountpoint) {
lookup = FS.lookupPath(mountpoint, { follow: false });
}
// create a root node for the fs
var root = type.mount(mount);
root.mount = mount;
mount.root = root;
// assign the mount info to the mountpoint's node
if (lookup) {
lookup.node.mount = mount;
lookup.node.mounted = true;
// compatibility update FS.root if we mount to /
if (mountpoint === '/') {
FS.root = mount.root;
}
}
return root;
},
lookup: function(parent, name) {
return parent.node_ops.lookup(parent, name);
},
// generic function for all node creation
mknod: function(path, mode, dev) {
var lookup = FS.lookupPath(path, { parent: true });
var parent = lookup.node;
var name = PATH.basename(path);
var err = FS.mayCreate(parent, name);
if (err) {
throw new FS.ErrnoError(err);
}
if (!parent.node_ops.mknod) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
return parent.node_ops.mknod(parent, name, mode, dev);
},
// helpers to create specific types of nodes
create: function(path, mode) {
mode = mode !== undefined ? mode : 0666;
mode &= {{{ cDefine('S_IALLUGO') }}};
mode |= {{{ cDefine('S_IFREG') }}};
return FS.mknod(path, mode, 0);
},
mkdir: function(path, mode) {
mode = mode !== undefined ? mode : 0777;
mode &= {{{ cDefine('S_IRWXUGO') }}} | {{{ cDefine('S_ISVTX') }}};
mode |= {{{ cDefine('S_IFDIR') }}};
return FS.mknod(path, mode, 0);
},
mkdev: function(path, mode, dev) {
if (typeof(dev) === 'undefined') {
dev = mode;
mode = 0666;
}
mode |= {{{ cDefine('S_IFCHR') }}};
return FS.mknod(path, mode, dev);
},
symlink: function(oldpath, newpath) {
var lookup = FS.lookupPath(newpath, { parent: true });
var parent = lookup.node;
var newname = PATH.basename(newpath);
var err = FS.mayCreate(parent, newname);
if (err) {
throw new FS.ErrnoError(err);
}
if (!parent.node_ops.symlink) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
return parent.node_ops.symlink(parent, newname, oldpath);
},
rename: function(old_path, new_path) {
var old_dirname = PATH.dirname(old_path);
var new_dirname = PATH.dirname(new_path);
var old_name = PATH.basename(old_path);
var new_name = PATH.basename(new_path);
// parents must exist
var lookup, old_dir, new_dir;
try {
lookup = FS.lookupPath(old_path, { parent: true });
old_dir = lookup.node;
lookup = FS.lookupPath(new_path, { parent: true });
new_dir = lookup.node;
} catch (e) {
throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
}
// need to be part of the same mount
if (old_dir.mount !== new_dir.mount) {
throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
}
// source must exist
var old_node = FS.lookupNode(old_dir, old_name);
// old path should not be an ancestor of the new path
var relative = PATH.relative(old_path, new_dirname);
if (relative.charAt(0) !== '.') {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
// new path should not be an ancestor of the old path
relative = PATH.relative(new_path, old_dirname);
if (relative.charAt(0) !== '.') {
throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
}
// see if the new path already exists
var new_node;
try {
new_node = FS.lookupNode(new_dir, new_name);
} catch (e) {
// not fatal
}
// early out if nothing needs to change
if (old_node === new_node) {
return;
}
// we'll need to delete the old entry
var isdir = FS.isDir(old_node.mode);
var err = FS.mayDelete(old_dir, old_name, isdir);
if (err) {
throw new FS.ErrnoError(err);
}
// need delete permissions if we'll be overwriting.
// need create permissions if new doesn't already exist.
err = new_node ?
FS.mayDelete(new_dir, new_name, isdir) :
FS.mayCreate(new_dir, new_name);
if (err) {
throw new FS.ErrnoError(err);
}
if (!old_dir.node_ops.rename) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
}
// if we are going to change the parent, check write permissions
if (new_dir !== old_dir) {
err = FS.nodePermissions(old_dir, 'w');
if (err) {
throw new FS.ErrnoError(err);
}
}
// remove the node from the lookup hash
FS.hashRemoveNode(old_node);
// do the underlying fs rename
try {
old_dir.node_ops.rename(old_node, new_dir, new_name);
} catch (e) {
throw e;
} finally {
// add the node back to the hash (in case node_ops.rename
// changed its name)
FS.hashAddNode(old_node);
}
},
rmdir: function(path) {
var lookup = FS.lookupPath(path, { parent: true });
var parent = lookup.node;
var name = PATH.basename(path);
var node = FS.lookupNode(parent, name);
var err = FS.mayDelete(parent, name, true);
if (err) {
throw new FS.ErrnoError(err);
}
if (!parent.node_ops.rmdir) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
if (FS.isMountpoint(node)) {
throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
}
parent.node_ops.rmdir(parent, name);
FS.destroyNode(node);
},
readdir: function(path) {
var lookup = FS.lookupPath(path, { follow: true });
var node = lookup.node;
if (!node.node_ops.readdir) {
throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
}
return node.node_ops.readdir(node);
},
unlink: function(path) {
var lookup = FS.lookupPath(path, { parent: true });
var parent = lookup.node;
var name = PATH.basename(path);
var node = FS.lookupNode(parent, name);
var err = FS.mayDelete(parent, name, false);
if (err) {
// POSIX says unlink should set EPERM, not EISDIR
if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
throw new FS.ErrnoError(err);
}
if (!parent.node_ops.unlink) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
if (FS.isMountpoint(node)) {
throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
}
parent.node_ops.unlink(parent, name);
FS.destroyNode(node);
},
readlink: function(path) {
var lookup = FS.lookupPath(path, { follow: false });
var link = lookup.node;
if (!link.node_ops.readlink) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
return link.node_ops.readlink(link);
},
stat: function(path, dontFollow) {
var lookup = FS.lookupPath(path, { follow: !dontFollow });
var node = lookup.node;
if (!node.node_ops.getattr) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
return node.node_ops.getattr(node);
},
lstat: function(path) {
return FS.stat(path, true);
},
chmod: function(path, mode, dontFollow) {
var node;
if (typeof path === 'string') {
var lookup = FS.lookupPath(path, { follow: !dontFollow });
node = lookup.node;
} else {
node = path;
}
if (!node.node_ops.setattr) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
node.node_ops.setattr(node, {
mode: (mode & {{{ cDefine('S_IALLUGO') }}}) | (node.mode & ~{{{ cDefine('S_IALLUGO') }}}),
timestamp: Date.now()
});
},
lchmod: function(path, mode) {
FS.chmod(path, mode, true);
},
fchmod: function(fd, mode) {
var stream = FS.getStream(fd);
if (!stream) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
FS.chmod(stream.node, mode);
},
chown: function(path, uid, gid, dontFollow) {
var node;
if (typeof path === 'string') {
var lookup = FS.lookupPath(path, { follow: !dontFollow });
node = lookup.node;
} else {
node = path;
}
if (!node.node_ops.setattr) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
node.node_ops.setattr(node, {
timestamp: Date.now()
// we ignore the uid / gid for now
});
},
lchown: function(path, uid, gid) {
FS.chown(path, uid, gid, true);
},
fchown: function(fd, uid, gid) {
var stream = FS.getStream(fd);
if (!stream) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
FS.chown(stream.node, uid, gid);
},
truncate: function(path, len) {
if (len < 0) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
var node;
if (typeof path === 'string') {
var lookup = FS.lookupPath(path, { follow: true });
node = lookup.node;
} else {
node = path;
}
if (!node.node_ops.setattr) {
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
if (FS.isDir(node.mode)) {
throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
}
if (!FS.isFile(node.mode)) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
var err = FS.nodePermissions(node, 'w');
if (err) {
throw new FS.ErrnoError(err);
}
node.node_ops.setattr(node, {
size: len,
timestamp: Date.now()
});
},
ftruncate: function(fd, len) {
var stream = FS.getStream(fd);
if (!stream) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
if ((stream.flags & {{{ cDefine('O_ACCMODE') }}}) === {{{ cDefine('O_RDONLY')}}}) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
FS.truncate(stream.node, len);
},
utime: function(path, atime, mtime) {
var lookup = FS.lookupPath(path, { follow: true });
var node = lookup.node;
node.node_ops.setattr(node, {
timestamp: Math.max(atime, mtime)
});
},
open: function(path, flags, mode, fd_start, fd_end) {
path = PATH.normalize(path);
flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
mode = typeof mode === 'undefined' ? 0666 : mode;
if ((flags & {{{ cDefine('O_CREAT') }}})) {
mode = (mode & {{{ cDefine('S_IALLUGO') }}}) | {{{ cDefine('S_IFREG') }}};
} else {
mode = 0;
}
var node;
try {
var lookup = FS.lookupPath(path, {
follow: !(flags & {{{ cDefine('O_NOFOLLOW') }}})
});
node = lookup.node;
path = lookup.path;
} catch (e) {
// ignore
}
// perhaps we need to create the node
if ((flags & {{{ cDefine('O_CREAT') }}})) {
if (node) {
// if O_CREAT and O_EXCL are set, error out if the node already exists
if ((flags & {{{ cDefine('O_EXCL') }}})) {
throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
}
} else {
// node doesn't exist, try to create it
node = FS.mknod(path, mode, 0);
}
}
if (!node) {
throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
}
// can't truncate a device
if (FS.isChrdev(node.mode)) {
flags &= ~{{{ cDefine('O_TRUNC') }}};
}
// check permissions
var err = FS.mayOpen(node, flags);
if (err) {
throw new FS.ErrnoError(err);
}
// do truncation if necessary
if ((flags & {{{ cDefine('O_TRUNC')}}})) {
FS.truncate(node, 0);
}
// register the stream with the filesystem
var stream = FS.createStream({
path: path,
node: node,
flags: flags,
seekable: true,
position: 0,
stream_ops: node.stream_ops,
// used by the file family libc calls (fopen, fwrite, ferror, etc.)
ungotten: [],
error: false
}, fd_start, fd_end);
// call the new stream's open function
if (stream.stream_ops.open) {
stream.stream_ops.open(stream);
}
return stream;
},
close: function(stream) {
try {
if (stream.stream_ops.close) {
stream.stream_ops.close(stream);
}
} catch (e) {
throw e;
} finally {
FS.closeStream(stream.fd);
}
},
llseek: function(stream, offset, whence) {
if (!stream.seekable || !stream.stream_ops.llseek) {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
}
return stream.stream_ops.llseek(stream, offset, whence);
},
read: function(stream, buffer, offset, length, position) {
if (length < 0 || position < 0) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
if ((stream.flags & {{{ cDefine('O_ACCMODE') }}}) === {{{ cDefine('O_WRONLY')}}}) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
if (FS.isDir(stream.node.mode)) {
throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
}
if (!stream.stream_ops.read) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
var seeking = true;
if (typeof position === 'undefined') {
position = stream.position;
seeking = false;
} else if (!stream.seekable) {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
}
var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
if (!seeking) stream.position += bytesRead;
return bytesRead;
},
write: function(stream, buffer, offset, length, position, canOwn) {
if (length < 0 || position < 0) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
if ((stream.flags & {{{ cDefine('O_ACCMODE') }}}) === {{{ cDefine('O_RDONLY')}}}) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
if (FS.isDir(stream.node.mode)) {
throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
}
if (!stream.stream_ops.write) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
var seeking = true;
if (typeof position === 'undefined') {
position = stream.position;
seeking = false;
} else if (!stream.seekable) {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
}
if (stream.flags & {{{ cDefine('O_APPEND') }}}) {
// seek to the end before writing in append mode
FS.llseek(stream, 0, {{{ cDefine('SEEK_END') }}});
}
var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
if (!seeking) stream.position += bytesWritten;
return bytesWritten;
},
allocate: function(stream, offset, length) {
if (offset < 0 || length <= 0) {
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
}
if ((stream.flags & {{{ cDefine('O_ACCMODE') }}}) === {{{ cDefine('O_RDONLY')}}}) {
throw new FS.ErrnoError(ERRNO_CODES.EBADF);
}
if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
}
if (!stream.stream_ops.allocate) {
throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
}
stream.stream_ops.allocate(stream, offset, length);
},
mmap: function(stream, buffer, offset, length, position, prot, flags) {
// TODO if PROT is PROT_WRITE, make sure we have write access
if ((stream.flags & {{{ cDefine('O_ACCMODE') }}}) === {{{ cDefine('O_WRONLY')}}}) {
throw new FS.ErrnoError(ERRNO_CODES.EACCES);
}
if (!stream.stream_ops.mmap) {
throw new FS.errnoError(ERRNO_CODES.ENODEV);
}
return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
},
ioctl: function(stream, cmd, arg) {
if (!stream.stream_ops.ioctl) {
throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
}
return stream.stream_ops.ioctl(stream, cmd, arg);
},
readFile: function(path, opts) {
opts = opts || {};
opts.flags = opts.flags || 'r';
opts.encoding = opts.encoding || 'binary';
var ret;
var stream = FS.open(path, opts.flags);
var stat = FS.stat(path);
var length = stat.size;
var buf = new Uint8Array(length);
FS.read(stream, buf, 0, length, 0);
if (opts.encoding === 'utf8') {
ret = '';
var utf8 = new Runtime.UTF8Processor();
for (var i = 0; i < length; i++) {
ret += utf8.processCChar(buf[i]);
}
} else if (opts.encoding === 'binary') {
ret = buf;
} else {
throw new Error('Invalid encoding type "' + opts.encoding + '"');
}
FS.close(stream);
return ret;
},
writeFile: function(path, data, opts) {
opts = opts || {};
opts.flags = opts.flags || 'w';
opts.encoding = opts.encoding || 'utf8';
var stream = FS.open(path, opts.flags, opts.mode);
if (opts.encoding === 'utf8') {
var utf8 = new Runtime.UTF8Processor();
var buf = new Uint8Array(utf8.processJSString(data));
FS.write(stream, buf, 0, buf.length, 0);
} else if (opts.encoding === 'binary') {
FS.write(stream, data, 0, data.length, 0);
} else {
throw new Error('Invalid encoding type "' + opts.encoding + '"');
}
FS.close(stream);
},
//
// module-level FS code
// TODO move to pre/postamble
//
createDefaultDirectories: function() {
FS.mkdir('/tmp');
},
createDefaultDevices: function() {
// create /dev
FS.mkdir('/dev');
// setup /dev/null
FS.registerDevice(FS.makedev(1, 3), {
read: function() { return 0; },
write: function() { return 0; }
});
FS.mkdev('/dev/null', FS.makedev(1, 3));
// setup /dev/tty and /dev/tty1
// stderr needs to print output using Module['printErr']
// so we register a second tty just for it.
TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
FS.mkdev('/dev/tty', FS.makedev(5, 0));
FS.mkdev('/dev/tty1', FS.makedev(6, 0));
// we're not going to emulate the actual shm device,
// just create the tmp dirs that reside in it commonly
FS.mkdir('/dev/shm');
FS.mkdir('/dev/shm/tmp');
},
createStandardStreams: function() {
// TODO deprecate the old functionality of a single
// input / output callback and that utilizes FS.createDevice
// and instead require a unique set of stream ops
// by default, we symlink the standard streams to the
// default tty devices. however, if the standard streams
// have been overwritten we create a unique device for
// them instead.
if (Module['stdin']) {
FS.createDevice('/dev', 'stdin', Module['stdin']);
} else {
FS.symlink('/dev/tty', '/dev/stdin');
}
if (Module['stdout']) {
FS.createDevice('/dev', 'stdout', null, Module['stdout']);
} else {
FS.symlink('/dev/tty', '/dev/stdout');
}
if (Module['stderr']) {
FS.createDevice('/dev', 'stderr', null, Module['stderr']);
} else {
FS.symlink('/dev/tty1', '/dev/stderr');
}
// open default streams for the stdin, stdout and stderr devices
var stdin = FS.open('/dev/stdin', 'r');
{{{ makeSetValue(makeGlobalUse('_stdin'), 0, 'stdin.fd', 'void*') }}};
assert(stdin.fd === 1, 'invalid handle for stdin (' + stdin.fd + ')');
var stdout = FS.open('/dev/stdout', 'w');
{{{ makeSetValue(makeGlobalUse('_stdout'), 0, 'stdout.fd', 'void*') }}};
assert(stdout.fd === 2, 'invalid handle for stdout (' + stdout.fd + ')');
var stderr = FS.open('/dev/stderr', 'w');
{{{ makeSetValue(makeGlobalUse('_stderr'), 0, 'stderr.fd', 'void*') }}};
assert(stderr.fd === 3, 'invalid handle for stderr (' + stderr.fd + ')');
},
staticInit: function() {
FS.nameTable = new Array(4096);
FS.root = FS.createNode(null, '/', {{{ cDefine('S_IFDIR') }}} | 0777, 0);
FS.mount(MEMFS, {}, '/');
FS.createDefaultDirectories();
FS.createDefaultDevices();
},
init: function(input, output, error) {
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;
// Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
Module['stdin'] = input || Module['stdin'];
Module['stdout'] = output || Module['stdout'];
Module['stderr'] = error || Module['stderr'];
FS.createStandardStreams();
},
quit: function() {
FS.init.initialized = false;
for (var i = 0; i < FS.streams.length; i++) {
var stream = FS.streams[i];
if (!stream) {
continue;
}
FS.close(stream);
}
},
//
// old v1 compatibility functions
//
getMode: function(canRead, canWrite) {
var mode = 0;
if (canRead) mode |= {{{ cDefine('S_IRUGO') }}} | {{{ cDefine('S_IXUGO') }}};
if (canWrite) mode |= {{{ cDefine('S_IWUGO') }}};
return mode;
},
joinPath: function(parts, forceRelative) {
var path = PATH.join.apply(null, parts);
if (forceRelative && path[0] == '/') path = path.substr(1);
return path;
},
absolutePath: function(relative, base) {
return PATH.resolve(base, relative);
},
standardizePath: function(path) {
return PATH.normalize(path);
},
findObject: function(path, dontResolveLastLink) {
var ret = FS.analyzePath(path, dontResolveLastLink);
if (ret.exists) {
return ret.object;
} else {
___setErrNo(ret.error);
return null;
}
},
analyzePath: function(path, dontResolveLastLink) {
// operate from within the context of the symlink's target
try {
var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
path = lookup.path;
} catch (e) {
}
var ret = {
isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
parentExists: false, parentPath: null, parentObject: null
};
try {
var lookup = FS.lookupPath(path, { parent: true });
ret.parentExists = true;
ret.parentPath = lookup.path;
ret.parentObject = lookup.node;
ret.name = PATH.basename(path);
lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
ret.exists = true;
ret.path = lookup.path;
ret.object = lookup.node;
ret.name = lookup.node.name;
ret.isRoot = lookup.path === '/';
} catch (e) {
ret.error = e.errno;
};
return ret;
},
createFolder: function(parent, name, canRead, canWrite) {
var path = PATH.join(typeof parent === 'string' ? parent : FS.getPath(parent), name);
var mode = FS.getMode(canRead, canWrite);
return FS.mkdir(path, mode);
},
createPath: function(parent, path, canRead, canWrite) {
parent = typeof parent === 'string' ? parent : FS.getPath(parent);
var parts = path.split('/').reverse();
while (parts.length) {
var part = parts.pop();
if (!part) continue;
var current = PATH.join(parent, part);
try {
FS.mkdir(current);
} catch (e) {
// ignore EEXIST
}
parent = current;
}
return current;
},
createFile: function(parent, name, properties, canRead, canWrite) {
var path = PATH.join(typeof parent === 'string' ? parent : FS.getPath(parent), name);
var mode = FS.getMode(canRead, canWrite);
return FS.create(path, mode);
},
createDataFile: function(parent, name, data, canRead, canWrite, canOwn) {
var path = name ? PATH.join(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
var mode = FS.getMode(canRead, canWrite);
var node = FS.create(path, mode);
if (data) {
if (typeof data === 'string') {
var arr = new Array(data.length);
for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
data = arr;
}
// make sure we can write to the file
FS.chmod(path, mode | {{{ cDefine('S_IWUGO') }}});
var stream = FS.open(path, 'w');
FS.write(stream, data, 0, data.length, 0, canOwn);
FS.close(stream);
FS.chmod(path, mode);
}
return node;
},
createDevice: function(parent, name, input, output) {
var path = PATH.join(typeof parent === 'string' ? parent : FS.getPath(parent), name);
var mode = FS.getMode(!!input, !!output);
if (!FS.createDevice.major) FS.createDevice.major = 64;
var dev = FS.makedev(FS.createDevice.major++, 0);
// Create a fake device that a set of stream ops to emulate
// the old behavior.
FS.registerDevice(dev, {
open: function(stream) {
stream.seekable = false;
},
close: function(stream) {
// flush any pending line data
if (output && output.buffer && output.buffer.length) {
output({{{ charCode('\n') }}});
}
},
read: function(stream, buffer, offset, length, pos /* ignored */) {
var bytesRead = 0;
for (var i = 0; i < length; i++) {
var result;
try {
result = input();
} catch (e) {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
}
if (result === undefined && bytesRead === 0) {
throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
}
if (result === null || result === undefined) break;
bytesRead++;
buffer[offset+i] = result;
}
if (bytesRead) {
stream.node.timestamp = Date.now();
}
return bytesRead;
},
write: function(stream, buffer, offset, length, pos) {
for (var i = 0; i < length; i++) {
try {
output(buffer[offset+i]);
} catch (e) {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
}
}
if (length) {
stream.node.timestamp = Date.now();
}
return i;
}
});
return FS.mkdev(path, mode, dev);
},
createLink: function(parent, name, target, canRead, canWrite) {
var path = PATH.join(typeof parent === 'string' ? parent : FS.getPath(parent), name);
return FS.symlink(target, path);
},
// 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;
},
// 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() {
this.lengthKnown = false;
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 % this.chunkSize;
var chunkNum = Math.floor(idx / this.chunkSize);
return this.getter(chunkNum)[chunkOffset];
}
LazyUint8Array.prototype.setDataGetter = function(getter) {
this.getter = getter;
}
LazyUint8Array.prototype.cacheLength = function() {
// 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 = this;
lazyArray.setDataGetter(function(chunkNum) {
var start = chunkNum * chunkSize;
var end = (chunkNum+1) * 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];
});
this._length = datalength;
this._chunkSize = chunkSize;
this.lengthKnown = true;
}
var lazyArray = new LazyUint8Array();
Object.defineProperty(lazyArray, "length", {
get: function() {
if(!this.lengthKnown) {
this.cacheLength();
}
return this._length;
}
});
Object.defineProperty(lazyArray, "chunkSize", {
get: function() {
if(!this.lengthKnown) {
this.cacheLength();
}
return this._chunkSize;
}
});
var properties = { isDevice: false, contents: lazyArray };
} else {
var properties = { isDevice: false, url: url };
}
var node = FS.createFile(parent, name, properties, canRead, canWrite);
// This is a total hack, but I want to get this lazy file code out of the
// core of MEMFS. If we want to keep this lazy file concept I feel it should
// be its own thin LAZYFS proxying calls to MEMFS.
if (properties.contents) {
node.contents = properties.contents;
} else if (properties.url) {
node.contents = null;
node.url = properties.url;
}
// override each stream op with one that tries to force load the lazy file first
var stream_ops = {};
var keys = Object.keys(node.stream_ops);
keys.forEach(function(key) {
var fn = node.stream_ops[key];
stream_ops[key] = function() {
if (!FS.forceLoadFile(node)) {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
}
return fn.apply(null, arguments);
};
});
// use a custom read function
stream_ops.read = function(stream, buffer, offset, length, position) {
if (!FS.forceLoadFile(node)) {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
}
var contents = stream.node.contents;
var size = Math.min(contents.length - position, length);
if (contents.slice) { // normal array
for (var i = 0; i < size; i++) {
buffer[offset + i] = contents[position + i];
}
} else {
for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
buffer[offset + i] = contents.get(position + i);
}
}
return size;
};
node.stream_ops = stream_ops;
return node;
},
// 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, canOwn) {
Browser.init();
// TODO we should allow people to just pass in a complete filename instead
// of parent and name being that we just join them anyways
var fullname = name ? PATH.resolve(PATH.join(parent, name)) : parent;
function processData(byteArray) {
function finish(byteArray) {
if (!dontCreateFile) {
FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
}
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);
}
},
//
// persistence
//
indexedDB: function() {
return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
},
DB_NAME: function() {
return 'EM_FS_' + window.location.pathname;
},
DB_VERSION: 20,
DB_STORE_NAME: 'FILE_DATA',
// asynchronously saves a list of files to an IndexedDB. The DB will be created if not already existing.
saveFilesToDB: function(paths, onload, onerror) {
onload = onload || function(){};
onerror = onerror || function(){};
var indexedDB = FS.indexedDB();
try {
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
} catch (e) {
return onerror(e);
}
openRequest.onupgradeneeded = function() {
console.log('creating db');
var db = openRequest.result;
db.createObjectStore(FS.DB_STORE_NAME);
};
openRequest.onsuccess = function() {
var db = openRequest.result;
var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
var files = transaction.objectStore(FS.DB_STORE_NAME);
var ok = 0, fail = 0, total = paths.length;
function finish() {
if (fail == 0) onload(); else onerror();
}
paths.forEach(function(path) {
var putRequest = files.put(FS.analyzePath(path).object.contents, path);
putRequest.onsuccess = function() { ok++; if (ok + fail == total) finish() };
putRequest.onerror = function() { fail++; if (ok + fail == total) finish() };
});
transaction.onerror = onerror;
};
openRequest.onerror = onerror;
},
// asychronously loads a file from IndexedDB.
loadFilesFromDB: function(paths, onload, onerror) {
onload = onload || function(){};
onerror = onerror || function(){};
var indexedDB = FS.indexedDB();
try {
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
} catch (e) {
return onerror(e);
}
openRequest.onupgradeneeded = onerror; // no database to load from
openRequest.onsuccess = function() {
var db = openRequest.result;
try {
var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
} catch(e) {
onerror(e);
return;
}
var files = transaction.objectStore(FS.DB_STORE_NAME);
var ok = 0, fail = 0, total = paths.length;
function finish() {
if (fail == 0) onload(); else onerror();
}
paths.forEach(function(path) {
var getRequest = files.get(path);
getRequest.onsuccess = function() {
if (FS.analyzePath(path).exists) {
FS.unlink(path);
}
FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
ok++;
if (ok + fail == total) finish();
};
getRequest.onerror = function() { fail++; if (ok + fail == total) finish() };
});
transaction.onerror = onerror;
};
openRequest.onerror = onerror;
}
}
});
|