-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathlibrary.js
5253 lines (4811 loc) · 200 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
/**
* @license
* Copyright 2010 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
//"use strict";
// An implementation of basic necessary libraries for the web. This integrates
// with a compiled libc and with the rest of the JS runtime.
//
// 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.
// Memory allocated during startup, in postsets, should only be static
// (using makeStaticAlloc)
LibraryManager.library = {
#if !WASM_BACKEND
__dso_handle: '{{{ makeStaticAlloc(1) }}}',
#endif
// ==========================================================================
// getTempRet0/setTempRet0: scratch space handling i64 return
// ==========================================================================
getTempRet0__sig: 'i',
getTempRet0: function() {
return {{{ makeGetTempRet0() }}};
},
setTempRet0__sig: 'vi',
setTempRet0: function($i) {
{{{ makeSetTempRet0('$i') }}};
},
// ==========================================================================
// JavaScript <-> C string interop
// ==========================================================================
$stringToNewUTF8: function(jsString) {
var length = lengthBytesUTF8(jsString)+1;
var cString = _malloc(length);
stringToUTF8(jsString, cString, length);
return cString;
},
// ==========================================================================
// utime.h
// ==========================================================================
utime__deps: ['$FS', '__setErrNo'],
utime__proxy: 'sync',
utime__sig: 'iii',
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 = {{{ C_STRUCTS.utimbuf.modtime }}};
time = {{{ makeGetValue('times', 'offset', 'i32') }}};
time *= 1000;
} else {
time = Date.now();
}
path = UTF8ToString(path);
try {
FS.utime(path, time, time);
return 0;
} catch (e) {
FS.handleFSError(e);
return -1;
}
},
utimes__deps: ['$FS', '__setErrNo'],
utimes__proxy: 'sync',
utimes__sig: 'iii',
utimes: function(path, times) {
var time;
if (times) {
var offset = {{{ C_STRUCTS.timeval.__size__ }}} + {{{ C_STRUCTS.timeval.tv_sec }}};
time = {{{ makeGetValue('times', 'offset', 'i32') }}} * 1000;
offset = {{{ C_STRUCTS.timeval.__size__ }}} + {{{ C_STRUCTS.timeval.tv_usec }}};
time += {{{ makeGetValue('times', 'offset', 'i32') }}} / 1000;
} else {
time = Date.now();
}
path = UTF8ToString(path);
try {
FS.utime(path, time, time);
return 0;
} catch (e) {
FS.handleFSError(e);
return -1;
}
},
// ==========================================================================
// sys/file.h
// ==========================================================================
flock: function(fd, operation) {
// int flock(int fd, int operation);
// Pretend to succeed
return 0;
},
chroot__deps: ['__setErrNo'],
chroot__proxy: 'sync',
chroot__sig: 'ii',
chroot: function(path) {
// int chroot(const char *path);
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/chroot.html
___setErrNo({{{ cDefine('EACCES') }}});
return -1;
},
fpathconf__deps: ['__setErrNo'],
fpathconf__proxy: 'sync',
fpathconf__sig: 'iii',
fpathconf: function(fildes, name) {
// long fpathconf(int fildes, int name);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/encrypt.html
// NOTE: The first parameter is ignored, so pathconf == fpathconf.
// The constants here aren't real values. Just mimicking glibc.
switch (name) {
case {{{ cDefine('_PC_LINK_MAX') }}}:
return 32000;
case {{{ cDefine('_PC_MAX_CANON') }}}:
case {{{ cDefine('_PC_MAX_INPUT') }}}:
case {{{ cDefine('_PC_NAME_MAX') }}}:
return 255;
case {{{ cDefine('_PC_PATH_MAX') }}}:
case {{{ cDefine('_PC_PIPE_BUF') }}}:
case {{{ cDefine('_PC_REC_MIN_XFER_SIZE') }}}:
case {{{ cDefine('_PC_REC_XFER_ALIGN') }}}:
case {{{ cDefine('_PC_ALLOC_SIZE_MIN') }}}:
return 4096;
case {{{ cDefine('_PC_CHOWN_RESTRICTED') }}}:
case {{{ cDefine('_PC_NO_TRUNC') }}}:
case {{{ cDefine('_PC_2_SYMLINKS') }}}:
return 1;
case {{{ cDefine('_PC_VDISABLE') }}}:
return 0;
case {{{ cDefine('_PC_SYNC_IO') }}}:
case {{{ cDefine('_PC_ASYNC_IO') }}}:
case {{{ cDefine('_PC_PRIO_IO') }}}:
case {{{ cDefine('_PC_SOCK_MAXBUF') }}}:
case {{{ cDefine('_PC_REC_INCR_XFER_SIZE') }}}:
case {{{ cDefine('_PC_REC_MAX_XFER_SIZE') }}}:
case {{{ cDefine('_PC_SYMLINK_MAX') }}}:
return -1;
case {{{ cDefine('_PC_FILESIZEBITS') }}}:
return 64;
}
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
},
pathconf: 'fpathconf',
confstr__deps: ['__setErrNo', '$ENV'],
confstr__proxy: 'sync',
confstr__sig: 'iiii',
confstr: function(name, buf, len) {
// size_t confstr(int name, char *buf, size_t len);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/confstr.html
var value;
switch (name) {
case {{{ cDefine('_CS_PATH') }}}:
value = ENV['PATH'] || '/';
break;
case {{{ cDefine('_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS') }}}:
// Mimicking glibc.
value = 'POSIX_V6_ILP32_OFF32\nPOSIX_V6_ILP32_OFFBIG';
break;
case {{{ cDefine('_CS_GNU_LIBC_VERSION') }}}:
// This JS implementation was tested against this glibc version.
value = 'glibc 2.14';
break;
case {{{ cDefine('_CS_GNU_LIBPTHREAD_VERSION') }}}:
// We don't support pthreads.
value = '';
break;
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_LIBS') }}}:
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_LIBS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_CFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_LDFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_LIBS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_LIBS') }}}:
value = '';
break;
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_CFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_LDFLAGS') }}}:
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS') }}}:
value = '-m32';
break;
case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS') }}}:
value = '-m32 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64';
break;
default:
___setErrNo({{{ cDefine('EINVAL') }}});
return 0;
}
if (len == 0 || buf == 0) {
return value.length + 1;
} else {
var length = Math.min(len, value.length);
for (var i = 0; i < length; i++) {
{{{ makeSetValue('buf', 'i', 'value.charCodeAt(i)', 'i8') }}};
}
if (len > length) {{{ makeSetValue('buf', 'i++', '0', 'i8') }}};
return i;
}
},
execl__deps: ['__setErrNo'],
execl__sig: 'iiii',
execl: function(path, arg0, varArgs) {
// int execl(const char *path, const char *arg0, ... /*, (char *)0 */);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
// We don't support executing external code.
___setErrNo({{{ cDefine('ENOEXEC') }}});
return -1;
},
execle: 'execl',
execlp: 'execl',
execv: 'execl',
execve: 'execl',
execvp: 'execl',
__execvpe: 'execl',
fexecve: 'execl',
exit__sig: 'vi',
exit: function(status) {
#if MINIMAL_RUNTIME
throw 'exit(' + status + ')';
#else
// void _exit(int status);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html
exit(status);
#endif
},
_exit__sig: 'vi',
_exit: 'exit',
_Exit__sig: 'vi',
_Exit: 'exit',
#if MINIMAL_RUNTIME
$exit: function(status) {
throw 'exit(' + status + ')';
},
#endif
fork__deps: ['__setErrNo'],
fork__sig: 'i',
fork: function() {
// pid_t fork(void);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/fork.html
// We don't support multiple processes.
___setErrNo({{{ cDefine('EAGAIN') }}});
return -1;
},
vfork: 'fork',
posix_spawn: 'fork',
posix_spawnp: 'fork',
setgroups__deps: ['__setErrNo', 'sysconf'],
setgroups: function(ngroups, gidset) {
// int setgroups(int ngroups, const gid_t *gidset);
// https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/setgroups.2.html
if (ngroups < 1 || ngroups > _sysconf({{{ cDefine('_SC_NGROUPS_MAX') }}})) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
} else {
// We have just one process/user/group, so it makes no sense to set groups.
___setErrNo({{{ cDefine('EPERM') }}});
return -1;
}
},
sysconf__deps: ['__setErrNo'],
sysconf__proxy: 'sync',
sysconf__sig: 'ii',
sysconf: function(name) {
// long sysconf(int name);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/sysconf.html
switch(name) {
case {{{ cDefine('_SC_PAGE_SIZE') }}}: return {{{ POSIX_PAGE_SIZE }}};
case {{{ cDefine('_SC_PHYS_PAGES') }}}:
#if ALLOW_MEMORY_GROWTH
#if MAXIMUM_MEMORY == -1 // no maximum set, assume the best
var maxHeapSize = 4*1024*1024*1024;
#else
var maxHeapSize = {{{ MAXIMUM_MEMORY }}};
#endif
#else // no growth
var maxHeapSize = HEAPU8.length;
#endif
return maxHeapSize / {{{ POSIX_PAGE_SIZE }}};
case {{{ cDefine('_SC_ADVISORY_INFO') }}}:
case {{{ cDefine('_SC_BARRIERS') }}}:
case {{{ cDefine('_SC_ASYNCHRONOUS_IO') }}}:
case {{{ cDefine('_SC_CLOCK_SELECTION') }}}:
case {{{ cDefine('_SC_CPUTIME') }}}:
case {{{ cDefine('_SC_FSYNC') }}}:
case {{{ cDefine('_SC_IPV6') }}}:
case {{{ cDefine('_SC_MAPPED_FILES') }}}:
case {{{ cDefine('_SC_MEMLOCK') }}}:
case {{{ cDefine('_SC_MEMLOCK_RANGE') }}}:
case {{{ cDefine('_SC_MEMORY_PROTECTION') }}}:
case {{{ cDefine('_SC_MESSAGE_PASSING') }}}:
case {{{ cDefine('_SC_MONOTONIC_CLOCK') }}}:
case {{{ cDefine('_SC_PRIORITIZED_IO') }}}:
case {{{ cDefine('_SC_PRIORITY_SCHEDULING') }}}:
case {{{ cDefine('_SC_RAW_SOCKETS') }}}:
case {{{ cDefine('_SC_READER_WRITER_LOCKS') }}}:
case {{{ cDefine('_SC_REALTIME_SIGNALS') }}}:
case {{{ cDefine('_SC_SEMAPHORES') }}}:
case {{{ cDefine('_SC_SHARED_MEMORY_OBJECTS') }}}:
case {{{ cDefine('_SC_SPAWN') }}}:
case {{{ cDefine('_SC_SPIN_LOCKS') }}}:
case {{{ cDefine('_SC_SYNCHRONIZED_IO') }}}:
case {{{ cDefine('_SC_THREAD_ATTR_STACKADDR') }}}:
case {{{ cDefine('_SC_THREAD_ATTR_STACKSIZE') }}}:
case {{{ cDefine('_SC_THREAD_CPUTIME') }}}:
case {{{ cDefine('_SC_THREAD_PRIO_INHERIT') }}}:
case {{{ cDefine('_SC_THREAD_PRIO_PROTECT') }}}:
case {{{ cDefine('_SC_THREAD_PROCESS_SHARED') }}}:
case {{{ cDefine('_SC_THREAD_SAFE_FUNCTIONS') }}}:
case {{{ cDefine('_SC_THREADS') }}}:
case {{{ cDefine('_SC_TIMEOUTS') }}}:
case {{{ cDefine('_SC_TIMERS') }}}:
case {{{ cDefine('_SC_VERSION') }}}:
case {{{ cDefine('_SC_2_C_BIND') }}}:
case {{{ cDefine('_SC_2_C_DEV') }}}:
case {{{ cDefine('_SC_2_CHAR_TERM') }}}:
case {{{ cDefine('_SC_2_LOCALEDEF') }}}:
case {{{ cDefine('_SC_2_SW_DEV') }}}:
case {{{ cDefine('_SC_2_VERSION') }}}:
case {{{ cDefine('_SC_THREAD_PRIORITY_SCHEDULING') }}}:
return 200809;
case {{{ cDefine('_SC_MQ_OPEN_MAX') }}}:
case {{{ cDefine('_SC_XOPEN_STREAMS') }}}:
case {{{ cDefine('_SC_XBS5_LP64_OFF64') }}}:
case {{{ cDefine('_SC_XBS5_LPBIG_OFFBIG') }}}:
case {{{ cDefine('_SC_AIO_LISTIO_MAX') }}}:
case {{{ cDefine('_SC_AIO_MAX') }}}:
case {{{ cDefine('_SC_SPORADIC_SERVER') }}}:
case {{{ cDefine('_SC_THREAD_SPORADIC_SERVER') }}}:
case {{{ cDefine('_SC_TRACE') }}}:
case {{{ cDefine('_SC_TRACE_EVENT_FILTER') }}}:
case {{{ cDefine('_SC_TRACE_EVENT_NAME_MAX') }}}:
case {{{ cDefine('_SC_TRACE_INHERIT') }}}:
case {{{ cDefine('_SC_TRACE_LOG') }}}:
case {{{ cDefine('_SC_TRACE_NAME_MAX') }}}:
case {{{ cDefine('_SC_TRACE_SYS_MAX') }}}:
case {{{ cDefine('_SC_TRACE_USER_EVENT_MAX') }}}:
case {{{ cDefine('_SC_TYPED_MEMORY_OBJECTS') }}}:
case {{{ cDefine('_SC_V6_LP64_OFF64') }}}:
case {{{ cDefine('_SC_V6_LPBIG_OFFBIG') }}}:
case {{{ cDefine('_SC_2_FORT_DEV') }}}:
case {{{ cDefine('_SC_2_FORT_RUN') }}}:
case {{{ cDefine('_SC_2_PBS') }}}:
case {{{ cDefine('_SC_2_PBS_ACCOUNTING') }}}:
case {{{ cDefine('_SC_2_PBS_CHECKPOINT') }}}:
case {{{ cDefine('_SC_2_PBS_LOCATE') }}}:
case {{{ cDefine('_SC_2_PBS_MESSAGE') }}}:
case {{{ cDefine('_SC_2_PBS_TRACK') }}}:
case {{{ cDefine('_SC_2_UPE') }}}:
case {{{ cDefine('_SC_THREAD_THREADS_MAX') }}}:
case {{{ cDefine('_SC_SEM_NSEMS_MAX') }}}:
case {{{ cDefine('_SC_SYMLOOP_MAX') }}}:
case {{{ cDefine('_SC_TIMER_MAX') }}}:
return -1;
case {{{ cDefine('_SC_V6_ILP32_OFF32') }}}:
case {{{ cDefine('_SC_V6_ILP32_OFFBIG') }}}:
case {{{ cDefine('_SC_JOB_CONTROL') }}}:
case {{{ cDefine('_SC_REGEXP') }}}:
case {{{ cDefine('_SC_SAVED_IDS') }}}:
case {{{ cDefine('_SC_SHELL') }}}:
case {{{ cDefine('_SC_XBS5_ILP32_OFF32') }}}:
case {{{ cDefine('_SC_XBS5_ILP32_OFFBIG') }}}:
case {{{ cDefine('_SC_XOPEN_CRYPT') }}}:
case {{{ cDefine('_SC_XOPEN_ENH_I18N') }}}:
case {{{ cDefine('_SC_XOPEN_LEGACY') }}}:
case {{{ cDefine('_SC_XOPEN_REALTIME') }}}:
case {{{ cDefine('_SC_XOPEN_REALTIME_THREADS') }}}:
case {{{ cDefine('_SC_XOPEN_SHM') }}}:
case {{{ cDefine('_SC_XOPEN_UNIX') }}}:
return 1;
case {{{ cDefine('_SC_THREAD_KEYS_MAX') }}}:
case {{{ cDefine('_SC_IOV_MAX') }}}:
case {{{ cDefine('_SC_GETGR_R_SIZE_MAX') }}}:
case {{{ cDefine('_SC_GETPW_R_SIZE_MAX') }}}:
case {{{ cDefine('_SC_OPEN_MAX') }}}:
return 1024;
case {{{ cDefine('_SC_RTSIG_MAX') }}}:
case {{{ cDefine('_SC_EXPR_NEST_MAX') }}}:
case {{{ cDefine('_SC_TTY_NAME_MAX') }}}:
return 32;
case {{{ cDefine('_SC_ATEXIT_MAX') }}}:
case {{{ cDefine('_SC_DELAYTIMER_MAX') }}}:
case {{{ cDefine('_SC_SEM_VALUE_MAX') }}}:
return 2147483647;
case {{{ cDefine('_SC_SIGQUEUE_MAX') }}}:
case {{{ cDefine('_SC_CHILD_MAX') }}}:
return 47839;
case {{{ cDefine('_SC_BC_SCALE_MAX') }}}:
case {{{ cDefine('_SC_BC_BASE_MAX') }}}:
return 99;
case {{{ cDefine('_SC_LINE_MAX') }}}:
case {{{ cDefine('_SC_BC_DIM_MAX') }}}:
return 2048;
case {{{ cDefine('_SC_ARG_MAX') }}}: return 2097152;
case {{{ cDefine('_SC_NGROUPS_MAX') }}}: return 65536;
case {{{ cDefine('_SC_MQ_PRIO_MAX') }}}: return 32768;
case {{{ cDefine('_SC_RE_DUP_MAX') }}}: return 32767;
case {{{ cDefine('_SC_THREAD_STACK_MIN') }}}: return 16384;
case {{{ cDefine('_SC_BC_STRING_MAX') }}}: return 1000;
case {{{ cDefine('_SC_XOPEN_VERSION') }}}: return 700;
case {{{ cDefine('_SC_LOGIN_NAME_MAX') }}}: return 256;
case {{{ cDefine('_SC_COLL_WEIGHTS_MAX') }}}: return 255;
case {{{ cDefine('_SC_CLK_TCK') }}}: return 100;
case {{{ cDefine('_SC_HOST_NAME_MAX') }}}: return 64;
case {{{ cDefine('_SC_AIO_PRIO_DELTA_MAX') }}}: return 20;
case {{{ cDefine('_SC_STREAM_MAX') }}}: return 16;
case {{{ cDefine('_SC_TZNAME_MAX') }}}: return 6;
case {{{ cDefine('_SC_THREAD_DESTRUCTOR_ITERATIONS') }}}: return 4;
case {{{ cDefine('_SC_NPROCESSORS_ONLN') }}}: {
if (typeof navigator === 'object') return navigator['hardwareConcurrency'] || 1;
return 1;
}
}
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
},
emscripten_get_heap_size: function() {
return HEAPU8.length;
},
emscripten_get_sbrk_ptr__asm: true,
emscripten_get_sbrk_ptr__sig: 'i',
emscripten_get_sbrk_ptr: function() {
return {{{ DYNAMICTOP_PTR }}};
},
#if ABORTING_MALLOC && !ALLOW_MEMORY_GROWTH
$abortOnCannotGrowMemory: function(requestedSize) {
#if ASSERTIONS
#if WASM
abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s INITIAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
#else
abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s INITIAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime but prevents some optimizations, (3) set Module.INITIAL_MEMORY to a higher value before the program runs, or (4) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
#endif
#else
abort('OOM');
#endif
},
#endif
#if TEST_MEMORY_GROWTH_FAILS
$emscripten_realloc_buffer: function(size) {
return false;
},
#else
// Grows the asm.js/wasm heap to the given byte size, and updates both JS and asm.js/wasm side views to the buffer.
// Returns 1 on success, or undefined if growing failed.
$emscripten_realloc_buffer: function(size) {
#if MEMORYPROFILER
var oldHeapSize = buffer.byteLength;
#endif
try {
#if WASM
// round size grow request up to wasm page size (fixed 64KB per spec)
wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16); // .grow() takes a delta compared to the previous size
updateGlobalBufferAndViews(wasmMemory.buffer);
#else // asm.js:
var newBuffer = new ArrayBuffer(size);
if (newBuffer.byteLength != size) return /*undefined, allocation did not succeed*/;
new Int8Array(newBuffer).set(/**@type{!Int8Array}*/(HEAP8));
_emscripten_replace_memory(newBuffer);
updateGlobalBufferAndViews(newBuffer);
#endif
#if MEMORYPROFILER
if (typeof emscriptenMemoryProfiler !== 'undefined') {
emscriptenMemoryProfiler.onMemoryResize(oldHeapSize, buffer.byteLength);
}
#endif
return 1 /*success*/;
} catch(e) {
#if ASSERTIONS
console.error('emscripten_realloc_buffer: Attempted to grow heap from ' + buffer.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e);
#endif
}
},
#endif // ~TEST_MEMORY_GROWTH_FAILS
emscripten_resize_heap__deps: ['emscripten_get_heap_size'
#if ASSERTIONS == 2
, 'emscripten_get_now'
#endif
#if ABORTING_MALLOC && !ALLOW_MEMORY_GROWTH
, '$abortOnCannotGrowMemory'
#endif
#if ALLOW_MEMORY_GROWTH
, '$emscripten_realloc_buffer'
#endif
],
emscripten_resize_heap: function(requestedSize) {
#if CAN_ADDRESS_2GB
requestedSize = requestedSize >>> 0;
#endif
#if ALLOW_MEMORY_GROWTH == 0
#if ABORTING_MALLOC
abortOnCannotGrowMemory(requestedSize);
#else
return false; // malloc will report failure
#endif // ABORTING_MALLOC
#else // ALLOW_MEMORY_GROWTH == 0
var oldSize = _emscripten_get_heap_size();
// With pthreads, races can happen (another thread might increase the size in between), so return a failure, and let the caller retry.
#if USE_PTHREADS
if (requestedSize <= oldSize) {
return false;
}
#endif // USE_PTHREADS
#if ASSERTIONS && !USE_PTHREADS
assert(requestedSize > oldSize);
#endif
#if EMSCRIPTEN_TRACING
// Report old layout one last time
_emscripten_trace_report_memory_layout();
#endif
var PAGE_MULTIPLE = {{{ getMemoryPageSize() }}};
// Memory resize rules:
// 1. When resizing, always produce a resized heap that is at least 16MB (to avoid tiny heap sizes receiving lots of repeated resizes at startup)
// 2. Always increase heap size to at least the requested size, rounded up to next page multiple.
// 3a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap geometrically: increase the heap size according to
// MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%),
// At most overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
// 3b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap linearly: increase the heap size by at least MEMORY_GROWTH_LINEAR_STEP bytes.
// 4. Max size for the heap is capped at 2048MB-PAGE_MULTIPLE, or by MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
// 5. If we were unable to allocate as much memory, it may be due to over-eager decision to excessively reserve due to (3) above.
// Hence if an allocation fails, cut down on the amount of excess growth, in an attempt to succeed to perform a smaller allocation.
#if MAXIMUM_MEMORY != -1
// A limit was set for how much we can grow. We should not exceed that
// (the wasm binary specifies it, so if we tried, we'd fail anyhow).
var maxHeapSize = {{{ MAXIMUM_MEMORY }}};
#else
var maxHeapSize = {{{ CAN_ADDRESS_2GB ? 4294967296 : 2147483648 }}} - PAGE_MULTIPLE;
#endif
if (requestedSize > maxHeapSize) {
#if ASSERTIONS
err('Cannot enlarge memory, asked to go up to ' + requestedSize + ' bytes, but the limit is ' + maxHeapSize + ' bytes!');
#endif
return false;
}
#if USE_ASAN
// One byte of ASan's shadow memory shadows 8 bytes of real memory. Shadow memory area has a fixed size,
// so do not allow resizing past that limit.
maxHeapSize = Math.min(maxHeapSize, {{{ 8 * ASAN_SHADOW_SIZE }}});
if (requestedSize > maxHeapSize) {
#if ASSERTIONS
err('Failed to grow the heap from ' + oldSize + ', as we reached the limit of our shadow memory. Increase ASAN_SHADOW_SIZE.');
#endif
return false;
}
#endif
var minHeapSize = 16777216;
// Loop through potential heap size increases. If we attempt a too eager reservation that fails, cut down on the
// attempted size and reserve a smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
for(var cutDown = 1; cutDown <= 4; cutDown *= 2) {
#if MEMORY_GROWTH_LINEAR_STEP == -1
var overGrownHeapSize = oldSize * (1 + {{{ MEMORY_GROWTH_GEOMETRIC_STEP }}} / cutDown); // ensure geometric growth
#if MEMORY_GROWTH_GEOMETRIC_CAP
// but limit overreserving (default to capping at +96MB overgrowth at most)
overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + {{{ MEMORY_GROWTH_GEOMETRIC_CAP }}} );
#endif
#else
var overGrownHeapSize = oldSize + {{{ MEMORY_GROWTH_LINEAR_STEP }}} / cutDown; // ensure linear growth
#endif
var newSize = Math.min(maxHeapSize, alignUp(Math.max(minHeapSize, requestedSize, overGrownHeapSize), PAGE_MULTIPLE));
#if ASSERTIONS == 2
var t0 = _emscripten_get_now();
#endif
var replacement = emscripten_realloc_buffer(newSize);
#if ASSERTIONS == 2
var t1 = _emscripten_get_now();
console.log('Heap resize call from ' + oldSize + ' to ' + newSize + ' took ' + (t1 - t0) + ' msecs. Success: ' + !!replacement);
#endif
if (replacement) {
#if ASSERTIONS && (!WASM || WASM2JS)
err('Warning: Enlarging memory arrays, this is not fast! ' + [oldSize, newSize]);
#endif
#if EMSCRIPTEN_TRACING
_emscripten_trace_js_log_message("Emscripten", "Enlarging memory arrays from " + oldSize + " to " + newSize);
// And now report the new layout
_emscripten_trace_report_memory_layout();
#endif
return true;
}
}
#if ASSERTIONS
err('Failed to grow the heap from ' + oldSize + ' bytes to ' + newSize + ' bytes, not enough memory!');
#endif
return false;
#endif // ALLOW_MEMORY_GROWTH
},
// Called after wasm grows memory. At that time we need to update the views.
// Without this notification, we'd need to check the buffer in JS every time
// we return from any wasm, which adds overhead. See
// https://github.com/WebAssembly/WASI/issues/82
emscripten_notify_memory_growth: function(memoryIndex) {
#if ASSERTIONS
assert(memoryIndex == 0);
#endif
updateGlobalBufferAndViews(wasmMemory.buffer);
},
system__deps: ['__setErrNo'],
system: function(command) {
#if ENVIRONMENT_MAY_BE_NODE
if (ENVIRONMENT_IS_NODE) {
if (!command) return 1; // shell is available
var cmdstr = UTF8ToString(command);
if (!cmdstr.length) return 0; // this is what glibc seems to do (shell works test?)
var cp = require('child_process');
var ret = cp.spawnSync(cmdstr, [], {shell:true, stdio:'inherit'});
var _W_EXITCODE = function(ret, sig) {
return ((ret) << 8 | (sig));
}
// this really only can happen if process is killed by signal
if (ret.status === null) {
// sadly node doesn't expose such function
var signalToNumber = function(sig) {
// implement only the most common ones, and fallback to SIGINT
switch (sig) {
case 'SIGHUP': return 1;
case 'SIGINT': return 2;
case 'SIGQUIT': return 3;
case 'SIGFPE': return 8;
case 'SIGKILL': return 9;
case 'SIGALRM': return 14;
case 'SIGTERM': return 15;
}
return 2; // SIGINT
}
return _W_EXITCODE(0, signalToNumber(ret.signal));
}
return _W_EXITCODE(ret.status, 0);
}
#endif // ENVIRONMENT_MAY_BE_NODE
// int system(const char *command);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/system.html
// Can't call external programs.
if (!command) return 0; // no shell available
___setErrNo({{{ cDefine('EAGAIN') }}});
return -1;
},
// ==========================================================================
// stdlib.h
// ==========================================================================
#if !MINIMAL_RUNTIME && MALLOC != 'none'
// tiny, fake malloc/free implementation. If the program actually uses malloc,
// a compiled version will be used; this will only be used if the runtime
// needs to allocate something, for which this is good enough if otherwise
// no malloc is needed.
malloc: function(bytes) {
/* Over-allocate to make sure it is byte-aligned by 8.
* This will leak memory, but this is only the dummy
* implementation (replaced by dlmalloc normally) so
* not an issue.
*/
#if ASSERTIONS == 2
warnOnce('using stub malloc (reference it from C to have the real one included)');
#endif
var ptr = dynamicAlloc(bytes + 8);
return (ptr+8) & 0xFFFFFFF8;
},
free: function() {
#if ASSERTIONS == 2
warnOnce('using stub free (reference it from C to have the real one included)');
#endif
},
#endif
abs: 'Math_abs',
labs: 'Math_abs',
_ZSt9terminatev__deps: ['exit'],
_ZSt9terminatev: function() {
_exit(-1234);
},
#if MINIMAL_RUNTIME && !EXIT_RUNTIME
atexit: function(){},
__cxa_atexit: function(){},
__cxa_thread_atexit: function(){},
__cxa_thread_atexit_impl: function(){},
#else
atexit__proxy: 'sync',
atexit__sig: 'iii',
atexit: function(func, arg) {
#if ASSERTIONS
#if EXIT_RUNTIME == 0
warnOnce('atexit() called, but EXIT_RUNTIME is not set, so atexits() will not be called. set EXIT_RUNTIME to 1 (see the FAQ)');
#endif
#endif
__ATEXIT__.unshift({ func: func, arg: arg });
},
__cxa_atexit: 'atexit',
// used in rust, clang when doing thread_local statics
__cxa_thread_atexit: 'atexit',
__cxa_thread_atexit_impl: 'atexit',
#endif
// TODO: There are currently two abort() functions that get imported to asm module scope: the built-in runtime function abort(),
// and this function _abort(). Remove one of these, importing two functions for the same purpose is wasteful.
abort: function() {
#if MINIMAL_RUNTIME
// In MINIMAL_RUNTIME the module object does not exist, so its behavior to abort is to throw directly.
throw 'abort';
#else
abort();
#endif
},
// This object can be modified by the user during startup, which affects
// the initial values of the environment accessible by getenv. (This works
// in both fastcomp and upstream.
$ENV: {},
// This implementation of environ/getenv/etc. is used for fastcomp, due
// to limitations in the system libraries (we can't easily add a global
// ctor to create the environment without it always being linked in with
// libc).
__buildEnvironment__deps: ['$ENV', '_getExecutableName'],
__buildEnvironment: function(environ) {
// WARNING: Arbitrary limit!
var MAX_ENV_VALUES = 64;
var TOTAL_ENV_SIZE = 1024;
// Statically allocate memory for the environment.
var poolPtr;
var envPtr;
if (!___buildEnvironment.called) {
___buildEnvironment.called = true;
// Set default values. Use string keys for Closure Compiler compatibility.
ENV['USER'] = 'web_user';
ENV['LOGNAME'] = 'web_user';
ENV['PATH'] = '/';
ENV['PWD'] = '/';
ENV['HOME'] = '/home/web_user';
// Browser language detection #8751
ENV['LANG'] = ((typeof navigator === 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8';
ENV['_'] = __getExecutableName();
// Allocate memory.
#if !MINIMAL_RUNTIME // TODO: environment support in MINIMAL_RUNTIME
poolPtr = getMemory(TOTAL_ENV_SIZE);
envPtr = getMemory(MAX_ENV_VALUES * {{{ Runtime.POINTER_SIZE }}});
{{{ makeSetValue('envPtr', '0', 'poolPtr', 'i8*') }}};
{{{ makeSetValue('environ', 0, 'envPtr', 'i8*') }}};
#endif
} else {
envPtr = {{{ makeGetValue('environ', '0', 'i8**') }}};
poolPtr = {{{ makeGetValue('envPtr', '0', 'i8*') }}};
}
// Collect key=value lines.
var strings = [];
var totalSize = 0;
for (var key in ENV) {
if (typeof ENV[key] === 'string') {
var line = key + '=' + ENV[key];
strings.push(line);
totalSize += line.length;
}
}
if (totalSize > TOTAL_ENV_SIZE) {
throw new Error('Environment size exceeded TOTAL_ENV_SIZE!');
}
// Make new.
var ptrSize = {{{ Runtime.getNativeTypeSize('i8*') }}};
for (var i = 0; i < strings.length; i++) {
var line = strings[i];
writeAsciiToMemory(line, poolPtr);
{{{ makeSetValue('envPtr', 'i * ptrSize', 'poolPtr', 'i8*') }}};
poolPtr += line.length + 1;
}
{{{ makeSetValue('envPtr', 'strings.length * ptrSize', '0', 'i8*') }}};
},
getenv__deps: ['$ENV',
#if MINIMAL_RUNTIME
'$allocateUTF8',
#endif
],
getenv__proxy: 'sync',
getenv__sig: 'ii',
getenv: function(name) {
// char *getenv(const char *name);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/getenv.html
if (name === 0) return 0;
name = UTF8ToString(name);
if (!ENV.hasOwnProperty(name)) return 0;
if (_getenv.ret) _free(_getenv.ret);
_getenv.ret = allocateUTF8(ENV[name]);
return _getenv.ret;
},
// Alias for sanitizers which intercept getenv.
emscripten_get_env: 'getenv',
clearenv__deps: ['$ENV', '__buildEnvironment'],
clearenv__proxy: 'sync',
clearenv__sig: 'i',
clearenv: function() {
// int clearenv (void);
// http://www.gnu.org/s/hello/manual/libc/Environment-Access.html#index-clearenv-3107
ENV = {};
___buildEnvironment(__get_environ());
return 0;
},
setenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'],
setenv__proxy: 'sync',
setenv__sig: 'iiii',
setenv: function(envname, envval, overwrite) {
// int setenv(const char *envname, const char *envval, int overwrite);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/setenv.html
if (envname === 0) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
var name = UTF8ToString(envname);
var val = UTF8ToString(envval);
if (name === '' || name.indexOf('=') !== -1) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
if (ENV.hasOwnProperty(name) && !overwrite) return 0;
ENV[name] = val;
___buildEnvironment(__get_environ());
return 0;
},
unsetenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'],
unsetenv__proxy: 'sync',
unsetenv__sig: 'ii',
unsetenv: function(name) {
// int unsetenv(const char *name);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/unsetenv.html
if (name === 0) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
name = UTF8ToString(name);
if (name === '' || name.indexOf('=') !== -1) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
if (ENV.hasOwnProperty(name)) {
delete ENV[name];
___buildEnvironment(__get_environ());
}
return 0;
},
putenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'],
putenv__proxy: 'sync',
putenv__sig: 'ii',
putenv: function(string) {
// int putenv(char *string);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/putenv.html
// WARNING: According to the standard (and the glibc implementation), the
// string is taken by reference so future changes are reflected.
// We copy it instead, possibly breaking some uses.
if (string === 0) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
string = UTF8ToString(string);
var splitPoint = string.indexOf('=')
if (string === '' || string.indexOf('=') === -1) {
___setErrNo({{{ cDefine('EINVAL') }}});
return -1;
}
var name = string.slice(0, splitPoint);
var value = string.slice(splitPoint + 1);
if (!(name in ENV) || ENV[name] !== value) {
ENV[name] = value;
___buildEnvironment(__get_environ());
}
return 0;
},
getloadavg: function(loadavg, nelem) {
// int getloadavg(double loadavg[], int nelem);
// http://linux.die.net/man/3/getloadavg
var limit = Math.min(nelem, 3);
var doubleSize = {{{ Runtime.getNativeTypeSize('double') }}};
for (var i = 0; i < limit; i++) {
{{{ makeSetValue('loadavg', 'i * doubleSize', '0.1', 'double') }}};
}
return limit;
},
// ==========================================================================
// string.h
// ==========================================================================
memcpy__inline: function(dest, src, num, align) {
var ret = '';
ret += makeCopyValues(dest, src, num, 'null', null, align);
return ret;
},
#if MIN_CHROME_VERSION < 45 || MIN_EDGE_VERSION < 14 || MIN_FIREFOX_VERSION < 34 || MIN_IE_VERSION != TARGET_NOT_SUPPORTED || MIN_SAFARI_VERSION < 100101 || STANDALONE_WASM
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin lists browsers that support TypedArray.prototype.copyWithin, but it
// has outdated information for Safari, saying it would not support it.
// https://github.com/WebKit/webkit/commit/24a800eea4d82d6d595cdfec69d0f68e733b5c52#diff-c484911d8df319ba75fce0d8e7296333R1 suggests support was added on Aug 28, 2015.
// Manual testing suggests:
// Safari/601.1 Version/9.0 on iPhone 4s with iOS 9.3.6 (released September 30, 2015) does not support copyWithin.
// but the following systems do:
// AppleWebKit/602.2.14 Safari/602.1 Version/10.0 Mobile/14B100 iPhone OS 10_1_1 on iPhone 5s with iOS 10.1.1 (released October 31, 2016)
// AppleWebKit/603.3.8 Safari/602.1 Version/10.0 on iPhone 5 with iOS 10.3.4 (released July 22, 2019)
// AppleWebKit/605.1.15 iPhone OS 12_3_1 Version/12.1.1 Safari/604.1 on iPhone SE with iOS 12.3.1
// AppleWebKit/605.1.15 Safari/604.1 Version/13.0.4 iPhone OS 13_3 on iPhone 6s with iOS 13.3
// AppleWebKit/605.1.15 Version/13.0.3 Intel Mac OS X 10_15_1 on Safari 13.0.3 (15608.3.10.1.4) on macOS Catalina 10.15.1
// Hence the support status of .copyWithin() for Safari version range [10.0.0, 10.1.0] is unknown.
emscripten_memcpy_big__import: true,
emscripten_memcpy_big: '= Uint8Array.prototype.copyWithin\n' +
' ? function(dest, src, num) { HEAPU8.copyWithin(dest, src, src + num); }\n' +
' : function(dest, src, num) { HEAPU8.set(HEAPU8.subarray(src, src+num), dest); }\n',
#else
emscripten_memcpy_big: function(dest, src, num) {
HEAPU8.copyWithin(dest, src, src + num);
},
#endif
#if !WASM_BACKEND
memcpy__asm: true,
memcpy__sig: 'iiii',
memcpy__deps: ['emscripten_memcpy_big', 'Int8Array', 'Int32Array'],
memcpy: function(dest, src, num) {
dest = dest|0; src = src|0; num = num|0;
var ret = 0;
var aligned_dest_end = 0;
var block_aligned_dest_end = 0;
var dest_end = 0;
// Test against a benchmarked cutoff limit for when HEAPU8.copyWithin() becomes faster to use.
if ((num|0) >= 512) {
_emscripten_memcpy_big(dest|0, src|0, num|0)|0;
return dest|0;
}
ret = dest|0;
dest_end = (dest + num)|0;
if ((dest&3) == (src&3)) {
// The initial unaligned < 4-byte front.
while (dest & 3) {
if ((num|0) == 0) return ret|0;
{{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i8'), 'i8') }}};
dest = (dest+1)|0;
src = (src+1)|0;
num = (num-1)|0;
}
aligned_dest_end = (dest_end & -4)|0;
#if FAST_UNROLLED_MEMCPY_AND_MEMSET