-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathlibrary.js
More file actions
2714 lines (2468 loc) · 86.6 KB
/
library.js
File metadata and controls
2714 lines (2468 loc) · 86.6 KB
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.
// ==========================================================================
$FS__deps: ['$ERRNO_CODES', '__setErrNo'],
$FS: {
// The main file system tree. All the contents are inside this.
root: {
read: true,
write: false,
isFolder: true,
timestamp: new Date(),
inodeNumber: 1,
contents: {}
},
// The path to the current folder.
currentPath: '/',
// The inode to assign to the next created object.
nextInode: 2,
// The file creation mask used by the program.
cmask: 022,
// 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: false,
// Converts any path to an absolute path. Resolves embedded "." and ".."
// parts.
absolutePath: function(relative, base) {
// TODO: Check if slash escaping should be taken into account.
if (base === undefined) base = FS.currentPath;
else if (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) return null;
absolute.pop();
} else {
absolute.push(part);
}
}
return absolute.join('/');
},
// 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 linksVisited = 0;
path = FS.absolutePath(path);
if (path === null) {
___setErrNo(ERRNO_CODES.ENOENT);
return null;
}
path = path.split('/').reverse();
path.pop();
var current = FS.root;
while (path.length) {
var target = path.pop();
if (!current.isFolder) {
___setErrNo(ERRNO_CODES.ENOTDIR);
return null;
} else if (!current.read) {
___setErrNo(ERRNO_CODES.EACCES);
return null;
} else if (!current.contents.hasOwnProperty(target)) {
___setErrNo(ERRNO_CODES.ENOENT);
return null;
}
current = current.contents[target];
if (current.link && !(dontResolveLastLink && path.length == 0)) {
current = FS.findObject(current.link, dontResolveLastLink);
if (++linksVisited > 40) { // Usual Linux SYMLOOP_MAX.
___setErrNo(ERRNO_CODES.ELOOP);
return null;
}
}
}
return current;
},
// 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: new Date(),
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, 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; i++) dataArray.push(data.charCodeAt(i));
data = dataArray;
}
return FS.createFile(parent, name, {contents: data}, canRead, canWrite);
},
// Creates a file record for lazy-loading from a URL.
createLazyFile: function(parent, name, url, canRead, canWrite) {
return FS.createFile(parent, name, {url: url}, canRead, canWrite);
},
// Creates a link to a sepcific local path.
createLink: function(parent, name, target, canRead, canWrite) {
return FS.createFile(parent, name, {link: target}, canRead, canWrite);
},
// Creates a device with read and write callbacks.
createDevice: function(parent, name, read, write) {
var ops = {read: read, write: write};
return FS.createFile(parent, name, ops, Boolean(read), Boolean(write));
},
// 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.contents !== undefined) 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.overrideMimeType('text/plain; charset=x-user-defined'); // Binary.
xhr.send(null);
if (xhr.status != 200 && xhr.status != 0) success = false;
obj.contents = intArrayFromString(xhr.responseText || '');
} else if (typeof read !== 'undefined') {
// Command-line.
try {
obj.contents = intArrayFromString(read(obj.url));
} catch (e) {
success = false;
}
} else {
throw new Error('Cannot load without read() or XMLHttpRequest.');
}
if (!success) ___setErrNo(ERRNO_CODES.EIO);
return success;
}
},
// ==========================================================================
// dirent.h
// ==========================================================================
__dirent_struct_layout: Runtime.generateStructInfo(
['d_ino', 'd_off', 'd_reclen', 'd_type', 'd_name'],
'%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 null;
}
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] = {
isFolder: true,
path: path,
object: target,
// Remember the contents at the time of opening in an array, so we can
// seek between them relying on a single order.
contents: contents,
// An index into contents. Special values: -2 is ".", -1 is "..".
position: -2,
// 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].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].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].isFolder) {
___setErrNo(ERRNO_CODES.EBADF);
} else if (loc >= FS.streams[dirp].contents.length) {
___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].isFolder) {
return ___setErrNo(ERRNO_CODES.EBADF);
}
var stream = FS.streams[dirp];
var loc = stream.position;
if (loc < -2 || loc >= FS.streams[dirp].contents.length) {
{{{ 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++;
{{{ makeSetValue('entry', '___dirent_struct_layout.d_ino', 'inode', 'i32') }}}
{{{ makeSetValue('entry', '___dirent_struct_layout.d_off', 'stream.position', 'i32') }}}
{{{ makeSetValue('entry', '___dirent_struct_layout.d_reclen', 'name.length + 1', 'i32') }}}
for (var i = 0; i < name.length; i++) {
{{{ makeSetValue('entry', '___dirent_struct_layout.d_name + i', 'name.charCodeAt(i)', 'i8') }}}
}
{{{ makeSetValue('entry', '___dirent_struct_layout.d_name + i', '0', 'i8') }}}
var type = stream.isFolder ? 4 // DT_DIR, directory.
: stream.contents !== undefined ? 8 // DT_REG, regular file.
: stream.link !== undefined ? 10 // DT_LNK, symbolic link.
: 2 // DT_CHR, character device.
{{{ makeSetValue('entry', '___dirent_struct_layout.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].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;
}
}
},
// TODO: Check if we need to link any 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.
time = {{{ makeGetValue('times', '___utimbuf_struct_layout.modtime', 'i32') }}}
time = new Date(time * 1000);
} else {
time = new Date();
}
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_STATIC);
}
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];
},
// ==========================================================================
_scanString: function() {
// Supports %x, %4x, %d.%d, %s
var str = Pointer_stringify(arguments[0]);
var stri = 0;
var fmt = Pointer_stringify(arguments[1]);
var fmti = 0;
var args = Array.prototype.slice.call(arguments, 2);
var argsi = 0;
var fields = 0;
while (fmti < fmt.length) {
if (fmt[fmti] === '%') {
fmti++;
var max_ = parseInt(fmt[fmti]);
if (!isNaN(max_)) fmti++;
var type = fmt[fmti];
fmti++;
var curr = 0;
while ((curr < max_ || isNaN(max_)) && stri+curr < str.length) {
if ((type === 'd' && parseInt(str[stri+curr]) >= 0) ||
(type === 'x' && parseInt(str[stri+curr].replace(/[a-fA-F]/, 5)) >= 0) ||
(type === 's')) {
curr++;
} else {
break;
}
}
if (curr === 0) return 0; // failure
var text = str.substr(stri, curr);
stri += curr;
switch (type) {
case 'd': {
{{{ makeSetValue('args[argsi]', '0', 'parseInt(text)', 'i32') }}}
break;
}
case 'x': {
{{{ makeSetValue('args[argsi]', '0', 'eval("0x" + text)', 'i32') }}}
break;
}
case 's': {
var array = intArrayFromString(text);
for (var j = 0; j < array.length; j++) {
{{{ makeSetValue('args[argsi]', 'j', 'array[j]', 'i8') }}}
}
break;
}
}
argsi++;
fields++;
} else { // not '%'
if (fmt[fmti] === str[stri]) {
fmti++;
stri++;
} else {
break;
}
}
}
return { fields: fields, bytes: stri };
},
sscanf__deps: ['_scanString'],
sscanf: function() {
return __scanString.apply(null, arguments).fields;
},
_formatString__deps: ['$STDIO', 'isdigit'],
_formatString: function() {
var cStyle = false;
var textIndex = arguments[0];
var argIndex = 1;
if (textIndex < 0) {
cStyle = true;
textIndex = -textIndex;
argIndex = arguments[1];
} else {
var _arguments = arguments;
}
function getNextArg(isFloat, size) {
var ret;
if (!cStyle) {
ret = _arguments[argIndex];
argIndex++;
} else {
if (isFloat) {
ret = {{{ makeGetValue(0, 'argIndex', 'double') }}};
} else {
ret = {{{ makeGetValue(0, 'argIndex', 'i32') }}};
}
argIndex += {{{ QUANTUM_SIZE === 1 ? 1 : 'Math.max(4, size || 0)' }}};
}
return +ret; // +: boolean=>int
}
var ret = [];
var curr, next, currArg;
while(1) {
var startTextIndex = textIndex;
curr = {{{ makeGetValue(0, 'textIndex', 'i8') }}};
if (curr === 0) break;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
if (curr == '%'.charCodeAt(0)) {
// Handle flags.
var flagAlwaysSigned = false;
var flagLeftAlign = false;
var flagAlternative = false;
var flagZeroPad = false;
flagsLoop: while (1) {
switch (next) {
case '+'.charCodeAt(0):
flagAlwaysSigned = true;
break;
case '-'.charCodeAt(0):
flagLeftAlign = true;
break;
case '#'.charCodeAt(0):
flagAlternative = true;
break;
case '0'.charCodeAt(0):
if (flagZeroPad) {
break flagsLoop;
} else {
flagZeroPad = true;
break;
}
default:
break flagsLoop;
}
textIndex++;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
}
// Handle width.
var width = 0;
if (next == '*'.charCodeAt(0)) {
width = getNextArg();
textIndex++;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
} else {
while (_isdigit(next)) {
width = width * 10 + (next - '0'.charCodeAt(0));
textIndex++;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
}
}
// Handle precision.
var precisionSet = false;
if (next == '.'.charCodeAt(0)) {
var precision = 0;
precisionSet = true;
textIndex++;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
if (next == '*'.charCodeAt(0)) {
precision = getNextArg();
textIndex++;
} else {
while(1) {
var precisionChr = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
if (!_isdigit(precisionChr)) break;
precision = precision * 10 + (precisionChr - '0'.charCodeAt(0));
textIndex++;
}
}
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
} else {
var precision = 6; // Standard default.
}
// Handle integer sizes. WARNING: These assume a 32-bit architecture!
var argSize;
switch (String.fromCharCode(next)) {
case 'h':
var nextNext = {{{ makeGetValue(0, 'textIndex+2', 'i8') }}};
if (nextNext == 'h'.charCodeAt(0)) {
textIndex++;
argSize = 1; // char
} else {
argSize = 2; // short
}
break;
case 'l':
var nextNext = {{{ makeGetValue(0, 'textIndex+2', 'i8') }}};
if (nextNext == 'l'.charCodeAt(0)) {
textIndex++;
argSize = 8; // long long
} else {
argSize = 4; // long
}
break;
case 'L': // long long
case 'q': // int64_t
case 'j': // intmax_t
argSize = 8;
break;
case 'z': // size_t
case 't': // ptrdiff_t
case 'I': // signed ptrdiff_t or unsigned size_t
argSize = 4;
break;
default:
argSize = undefined;
}
if (argSize !== undefined) textIndex++;
next = {{{ makeGetValue(0, 'textIndex+1', 'i8') }}};
// Handle type specifier.
if (['d', 'i', 'u', 'o', 'x', 'X', 'p'].indexOf(String.fromCharCode(next)) != -1) {
// Integer.
var signed = next == 'd'.charCodeAt(0) || next == 'i'.charCodeAt(0);
var currArg = getNextArg(false, argSize);
// Truncate to requested size.
argSize = argSize || 4;
if (argSize <= 4) {
var limit = Math.pow(256, argSize) - 1;
currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
}
// Format the number.
var currAbsArg = Math.abs(currArg);
var argText;
var prefix = '';
if (next == 'd'.charCodeAt(0) || next == 'i'.charCodeAt(0)) {
argText = currAbsArg.toString(10);
} else if (next == 'u'.charCodeAt(0)) {
argText = unSign(currArg, 8 * argSize).toString(10);
currArg = Math.abs(currArg);
} else if (next == 'o'.charCodeAt(0)) {
argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
} else if (next == 'x'.charCodeAt(0) || next == 'X'.charCodeAt(0)) {
prefix = flagAlternative ? '0x' : '';
if (currArg < 0) {
// Represent negative numbers in hex as 2's complement.
currArg = -currArg;
argText = (currAbsArg - 1).toString(16);
var buffer = [];
for (var i = 0; i < argText.length; i++) {
buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
}
argText = buffer.join('');
while (argText.length < argSize * 2) argText = 'f' + argText;
} else {
argText = currAbsArg.toString(16);
}
if (next == 'X'.charCodeAt(0)) {
prefix = prefix.toUpperCase();
argText = argText.toUpperCase();
}
} else if (next == 'p'.charCodeAt(0)) {
prefix = '0x';
argText = currAbsArg.toString(16);
}
if (precisionSet) {
while (argText.length < precision) {
argText = '0' + argText;
}
}
// Add sign.
if (currArg < 0) {
prefix = '-' + prefix;
} else if (flagAlwaysSigned) {
prefix = '+' + prefix;
}
// Add padding.
while (prefix.length + argText.length < width) {
if (flagLeftAlign) {
argText += ' ';
} else {
if (flagZeroPad) {
argText = '0' + argText;
} else {
prefix = ' ' + prefix;
}
}
}
// Insert the result into the buffer.
argText = prefix + argText;
argText.split('').forEach(function(chr) {
ret.push(chr.charCodeAt(0));
});
} else if (['f', 'F', 'e', 'E', 'g', 'G'].indexOf(String.fromCharCode(next)) != -1) {
// Float.
var currArg = getNextArg(true, argSize);
var argText;
if (isNaN(currArg)) {
argText = 'nan';
flagZeroPad = false;
} else if (!isFinite(currArg)) {
argText = (currArg < 0 ? '-' : '') + 'inf';
flagZeroPad = false;
} else {
var isGeneral = false;
var effectivePrecision = Math.min(precision, 20);
// Convert g/G to f/F or e/E, as per:
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
if (next == 'g'.charCodeAt(0) || next == 'G'.charCodeAt(0)) {
isGeneral = true;
precision = precision || 1;
var exponent = parseInt(currArg.toExponential(effectivePrecision).split('e')[1], 10);
if (precision > exponent && exponent >= -4) {
next = ((next == 'g'.charCodeAt(0)) ? 'f' : 'F').charCodeAt(0);
precision -= exponent + 1;
} else {
next = ((next == 'g'.charCodeAt(0)) ? 'e' : 'E').charCodeAt(0);
precision--;
}
effectivePrecision = Math.min(precision, 20);
}
if (next == 'e'.charCodeAt(0) || next == 'E'.charCodeAt(0)) {
argText = currArg.toExponential(effectivePrecision);
// Make sure the exponent has at least 2 digits.
if (/[eE][-+]\d$/.test(argText)) {
argText = argText.slice(0, -1) + '0' + argText.slice(-1);
}
} else if (next == 'f'.charCodeAt(0) || next == 'F'.charCodeAt(0)) {
argText = currArg.toFixed(effectivePrecision);
}
var parts = argText.split('e');
if (isGeneral && !flagAlternative) {
// Discard trailing zeros and periods.
while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
(parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.')) {
parts[0] = parts[0].slice(0, -1);
}
} else {
// Make sure we have a period in alternative mode.
if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
// Zero pad until required precision.
while (precision > effectivePrecision++) parts[0] += '0';
}
argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
// Capitalize 'E' if needed.
if (next == 'E'.charCodeAt(0)) argText = argText.toUpperCase();
// Add sign.
if (flagAlwaysSigned && currArg >= 0) {
argText = '+' + argText;
}
}
// Add padding.
while (argText.length < width) {
if (flagLeftAlign) {
argText += ' ';
} else {
if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
argText = argText[0] + '0' + argText.slice(1);
} else {
argText = (flagZeroPad ? '0' : ' ') + argText;
}
}
}
// Adjust case.
if (next < 'a'.charCodeAt(0)) argText = argText.toUpperCase();
// Insert the result into the buffer.
argText.split('').forEach(function(chr) {
ret.push(chr.charCodeAt(0));
});
} else if (next == 's'.charCodeAt(0)) {
// String.
var copiedString = String_copy(getNextArg());
if (precisionSet && copiedString.length > precision) {
copiedString = copiedString.slice(0, precision);
}
if (!flagLeftAlign) {
while (copiedString.length < width--) {
ret.push(' '.charCodeAt(0));
}
}
ret = ret.concat(copiedString);
if (flagLeftAlign) {
while (copiedString.length < width--) {
ret.push(' '.charCodeAt(0));
}
}
} else if (next == 'c'.charCodeAt(0)) {
// Character.
if (flagLeftAlign) ret.push(getNextArg());
while (--width > 0) {
ret.push(' '.charCodeAt(0));
}
if (!flagLeftAlign) ret.push(getNextArg());
} else if (next == 'n'.charCodeAt(0)) {
// Write the length written so far to the next parameter.
{{{ makeSetValue('getNextArg()', '0', 'ret.length', 'i32') }}}
} else if (next == '%'.charCodeAt(0)) {
// Literal percent sign.
ret.push(curr);
} else {
// Unknown specifiers remain untouched.
for (var i = startTextIndex; i < textIndex + 2; i++) {
ret.push({{{ makeGetValue(0, 'i', 'i8') }}});
}
}
textIndex += 2;
// TODO: Support a/A (hex float) and m (last error) specifiers.
// TODO: Support %1${specifier} for arg selection.
} else {
ret.push(curr);
textIndex += 1;
}
}
return allocate(ret.concat(0), 'i8', ALLOC_STACK); // NB: Stored on the stack
//var len = ret.length+1;
//var ret = allocate(ret.concat(0), 0, ALLOC_STACK); // NB: Stored on the stack
//STACKTOP -= len; // XXX horrible hack. we rewind the stack, to 'undo' the alloc we just did.
// // the point is that this works if nothing else allocs on the stack before
// // the string is read, which should be true - it is very transient, see the *printf* functions below.
//return ret;
},
printf__deps: ['_formatString'],
printf: function() {
__print__(Pointer_stringify(__formatString.apply(null, arguments)));
},
sprintf__deps: ['strcpy', '_formatString'],
sprintf: function() {
var str = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
_strcpy(str, __formatString.apply(null, args)); // not terribly efficient
},
snprintf__deps: ['strncpy', '_formatString'],
snprintf: function() {
var str = arguments[0];
var num = arguments[1];
var args = Array.prototype.slice.call(arguments, 2);
_strncpy(str, __formatString.apply(null, args), num); // not terribly efficient
},
puts: function(p) {
__print__(Pointer_stringify(p) + '\n');
},
putc: 'fputc',
_IO_putc: 'fputc',
putchar: function(p) {
__print__(String.fromCharCode(p));
},
_ZNSo3putEc: 'putchar',
_ZNSo5flushEv: function() {
__print__('\n');
},
vsprintf__deps: ['strcpy', '_formatString'],
vsprintf: function(dst, src, ptr) {
_strcpy(dst, __formatString(-src, ptr));
},
vsnprintf__deps: ['_formatString'],
vsnprintf: function(dst, num, src, ptr) {
var text = __formatString(-src, ptr); // |-|src tells formatstring to use C-style params (typically they are from varargs)
var i;
for (i = 0; i < num; i++) {
{{{ makeCopyValues('dst+i', 'text+i', 1, 'i8') }}}
if ({{{ makeGetValue('dst', 'i', 'i8') }}} == 0) break;
}
return i; // Actually, should return how many *would* have been written, if the |num| had not stopped us.
},
fileno: function(file) {
return file;
},
isatty: function(file) {
return 0; // TODO
},
clearerr: function(stream) {
},
flockfile: function(file) {
},
funlockfile: function(file) {
},
// ==========================================================================
// stdio.h - file functions
// ==========================================================================
stdin: 0,
stdout: 0,
stderr: 0,
$STDIO__postset: 'STDIO.init()',
$STDIO__deps: ['stdin', 'stdout', 'stderr'],
$STDIO: {
streams: {},
filenames: {},
counter: 1,
SEEK_SET: 0, /* Beginning of file. */
SEEK_CUR: 1, /* Current position. */
SEEK_END: 2, /* End of file. */
init: function() {
_stdin = allocate([0], 'void*', ALLOC_STATIC);
{{{ makeSetValue('_stdin', '0', "STDIO.prepare('<<stdin>>', null, null, true)", 'i32') }}};
if (Module.stdin) {
// Make sure stdin returns a newline
var orig = Module.stdin;
Module.stdin = function stdinFixed(prompt) {
var ret = orig(prompt);
if (ret[ret.length-1] !== '\n') ret = ret + '\n';
return ret;
}
} else {
Module.stdin = function stdin(prompt) {
return window.prompt(prompt) || '';
};
}
_stdout = allocate([0], 'void*', ALLOC_STATIC);
{{{ makeSetValue('_stdout', '0', "STDIO.prepare('<<stdout>>', null, true)", 'i32') }}};
_stderr = allocate([0], 'void*', ALLOC_STATIC);
{{{ makeSetValue('_stderr', '0', "STDIO.prepare('<<stderr>>', null, true)", 'i32') }}};
},
cleanFilename: function(filename) {
return filename.replace('./', '');
},
prepare: function(filename, data, print_, interactiveInput) {
filename = STDIO.cleanFilename(filename);
var stream = STDIO.counter++;
STDIO.streams[stream] = {
filename: filename,
data: data ? data : [],
position: 0,
eof: 0,
error: 0,
interactiveInput: interactiveInput, // true for stdin - on the web, we allow interactive input
print: print_ // true for stdout and stderr - we print when receiving data for them
};
STDIO.filenames[filename] = stream;
return stream;