· 8 years ago · Mar 03, 2018, 07:40 PM
1var WasmVideoEncoderProd = function(WasmVideoEncoderProd) {
2 WasmVideoEncoderProd = WasmVideoEncoderProd || {};
3
4// The Module object: Our interface to the outside world. We import
5// and export values on it. There are various ways Module can be used:
6// 1. Not defined. We create it here
7// 2. A function parameter, function(Module) { ..generated code.. }
8// 3. pre-run appended it, var Module = {}; ..generated code..
9// 4. External script tag defines var Module.
10// We need to check if Module already exists (e.g. case 3 above).
11// Substitution will be replaced with actual code on later stage of the build,
12// this way Closure Compiler will not mangle it (e.g. case 4. above).
13// Note that if you want to run closure, and also to use Module
14// after the generated code, you will need to define var Module = {};
15// before the code. Then that object will be used in the code, and you
16// can continue to use Module afterwards as well.
17var Module = typeof WasmVideoEncoderProd !== 'undefined' ? WasmVideoEncoderProd : {};
18
19// --pre-jses are emitted after the Module integration code, so that they can
20// refer to Module (if they choose; they can also define Module)
21// {{PRE_JSES}}
22
23// Sometimes an existing Module object exists with properties
24// meant to overwrite the default module functionality. Here
25// we collect those properties and reapply _after_ we configure
26// the current environment's defaults to avoid having to be so
27// defensive during initialization.
28var moduleOverrides = {};
29var key;
30for (key in Module) {
31 if (Module.hasOwnProperty(key)) {
32 moduleOverrides[key] = Module[key];
33 }
34}
35
36Module['arguments'] = [];
37Module['thisProgram'] = './this.program';
38Module['quit'] = function(status, toThrow) {
39 throw toThrow;
40};
41Module['preRun'] = [];
42Module['postRun'] = [];
43
44// The environment setup code below is customized to use Module.
45// *** Environment setup code ***
46var ENVIRONMENT_IS_WEB = false;
47var ENVIRONMENT_IS_WORKER = false;
48var ENVIRONMENT_IS_NODE = false;
49var ENVIRONMENT_IS_SHELL = false;
50
51// Three configurations we can be running in:
52// 1) We could be the application main() thread running in the main JS UI thread. (ENVIRONMENT_IS_WORKER == false and ENVIRONMENT_IS_PTHREAD == false)
53// 2) We could be the application main() thread proxied to worker. (with Emscripten -s PROXY_TO_WORKER=1) (ENVIRONMENT_IS_WORKER == true, ENVIRONMENT_IS_PTHREAD == false)
54// 3) We could be an application pthread running in a worker. (ENVIRONMENT_IS_WORKER == true and ENVIRONMENT_IS_PTHREAD == true)
55
56if (Module['ENVIRONMENT']) {
57 if (Module['ENVIRONMENT'] === 'WEB') {
58 ENVIRONMENT_IS_WEB = true;
59 } else if (Module['ENVIRONMENT'] === 'WORKER') {
60 ENVIRONMENT_IS_WORKER = true;
61 } else if (Module['ENVIRONMENT'] === 'NODE') {
62 ENVIRONMENT_IS_NODE = true;
63 } else if (Module['ENVIRONMENT'] === 'SHELL') {
64 ENVIRONMENT_IS_SHELL = true;
65 } else {
66 throw new Error('Module[\'ENVIRONMENT\'] value is not valid. must be one of: WEB|WORKER|NODE|SHELL.');
67 }
68} else {
69 ENVIRONMENT_IS_WEB = typeof window === 'object';
70 ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
71 ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function' && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER;
72 ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
73}
74
75
76if (ENVIRONMENT_IS_NODE) {
77 // Expose functionality in the same simple way that the shells work
78 // Note that we pollute the global namespace here, otherwise we break in node
79 var nodeFS;
80 var nodePath;
81
82 Module['read'] = function shell_read(filename, binary) {
83 var ret;
84 if (!nodeFS) nodeFS = require('fs');
85 if (!nodePath) nodePath = require('path');
86 filename = nodePath['normalize'](filename);
87 ret = nodeFS['readFileSync'](filename);
88 return binary ? ret : ret.toString();
89 };
90
91 Module['readBinary'] = function readBinary(filename) {
92 var ret = Module['read'](filename, true);
93 if (!ret.buffer) {
94 ret = new Uint8Array(ret);
95 }
96 assert(ret.buffer);
97 return ret;
98 };
99
100 if (process['argv'].length > 1) {
101 Module['thisProgram'] = process['argv'][1].replace(/\\/g, '/');
102 }
103
104 Module['arguments'] = process['argv'].slice(2);
105
106 // MODULARIZE will export the module in the proper place outside, we don't need to export here
107
108 process['on']('uncaughtException', function(ex) {
109 // suppress ExitStatus exceptions from showing an error
110 if (!(ex instanceof ExitStatus)) {
111 throw ex;
112 }
113 });
114 // Currently node will swallow unhandled rejections, but this behavior is
115 // deprecated, and in the future it will exit with error status.
116 process['on']('unhandledRejection', function(reason, p) {
117 Module['printErr']('node.js exiting due to unhandled promise rejection');
118 process['exit'](1);
119 });
120
121 Module['inspect'] = function () { return '[Emscripten Module object]'; };
122}
123else if (ENVIRONMENT_IS_SHELL) {
124 if (typeof read != 'undefined') {
125 Module['read'] = function shell_read(f) {
126 return read(f);
127 };
128 }
129
130 Module['readBinary'] = function readBinary(f) {
131 var data;
132 if (typeof readbuffer === 'function') {
133 return new Uint8Array(readbuffer(f));
134 }
135 data = read(f, 'binary');
136 assert(typeof data === 'object');
137 return data;
138 };
139
140 if (typeof scriptArgs != 'undefined') {
141 Module['arguments'] = scriptArgs;
142 } else if (typeof arguments != 'undefined') {
143 Module['arguments'] = arguments;
144 }
145
146 if (typeof quit === 'function') {
147 Module['quit'] = function(status, toThrow) {
148 quit(status);
149 }
150 }
151}
152else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
153 Module['read'] = function shell_read(url) {
154 var xhr = new XMLHttpRequest();
155 xhr.open('GET', url, false);
156 xhr.send(null);
157 return xhr.responseText;
158 };
159
160 if (ENVIRONMENT_IS_WORKER) {
161 Module['readBinary'] = function readBinary(url) {
162 var xhr = new XMLHttpRequest();
163 xhr.open('GET', url, false);
164 xhr.responseType = 'arraybuffer';
165 xhr.send(null);
166 return new Uint8Array(xhr.response);
167 };
168 }
169
170 Module['readAsync'] = function readAsync(url, onload, onerror) {
171 var xhr = new XMLHttpRequest();
172 xhr.open('GET', url, true);
173 xhr.responseType = 'arraybuffer';
174 xhr.onload = function xhr_onload() {
175 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
176 onload(xhr.response);
177 return;
178 }
179 onerror();
180 };
181 xhr.onerror = onerror;
182 xhr.send(null);
183 };
184
185 if (typeof arguments != 'undefined') {
186 Module['arguments'] = arguments;
187 }
188
189 Module['setWindowTitle'] = function(title) { document.title = title };
190}
191else {
192 // Unreachable because SHELL is dependent on the others
193 throw new Error('unknown runtime environment');
194}
195
196// console.log is checked first, as 'print' on the web will open a print dialogue
197// printErr is preferable to console.warn (works better in shells)
198// bind(console) is necessary to fix IE/Edge closed dev tools panel behavior.
199Module['print'] = typeof console !== 'undefined' ? console.log.bind(console) : (typeof print !== 'undefined' ? print : null);
200Module['printErr'] = typeof printErr !== 'undefined' ? printErr : ((typeof console !== 'undefined' && console.warn.bind(console)) || Module['print']);
201
202// *** Environment setup code ***
203
204// Closure helpers
205Module.print = Module['print'];
206Module.printErr = Module['printErr'];
207
208// Merge back in the overrides
209for (key in moduleOverrides) {
210 if (moduleOverrides.hasOwnProperty(key)) {
211 Module[key] = moduleOverrides[key];
212 }
213}
214// Free the object hierarchy contained in the overrides, this lets the GC
215// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
216moduleOverrides = undefined;
217
218
219
220// {{PREAMBLE_ADDITIONS}}
221
222var STACK_ALIGN = 16;
223
224// stack management, and other functionality that is provided by the compiled code,
225// should not be used before it is ready
226stackSave = stackRestore = stackAlloc = setTempRet0 = getTempRet0 = function() {
227 abort('cannot use the stack before compiled code is ready to run, and has provided stack access');
228};
229
230function staticAlloc(size) {
231 assert(!staticSealed);
232 var ret = STATICTOP;
233 STATICTOP = (STATICTOP + size + 15) & -16;
234 return ret;
235}
236
237function dynamicAlloc(size) {
238 assert(DYNAMICTOP_PTR);
239 var ret = HEAP32[DYNAMICTOP_PTR>>2];
240 var end = (ret + size + 15) & -16;
241 HEAP32[DYNAMICTOP_PTR>>2] = end;
242 if (end >= TOTAL_MEMORY) {
243 var success = enlargeMemory();
244 if (!success) {
245 HEAP32[DYNAMICTOP_PTR>>2] = ret;
246 return 0;
247 }
248 }
249 return ret;
250}
251
252function alignMemory(size, factor) {
253 if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default
254 var ret = size = Math.ceil(size / factor) * factor;
255 return ret;
256}
257
258function getNativeTypeSize(type) {
259 switch (type) {
260 case 'i1': case 'i8': return 1;
261 case 'i16': return 2;
262 case 'i32': return 4;
263 case 'i64': return 8;
264 case 'float': return 4;
265 case 'double': return 8;
266 default: {
267 if (type[type.length-1] === '*') {
268 return 4; // A pointer
269 } else if (type[0] === 'i') {
270 var bits = parseInt(type.substr(1));
271 assert(bits % 8 === 0);
272 return bits / 8;
273 } else {
274 return 0;
275 }
276 }
277 }
278}
279
280function warnOnce(text) {
281 if (!warnOnce.shown) warnOnce.shown = {};
282 if (!warnOnce.shown[text]) {
283 warnOnce.shown[text] = 1;
284 Module.printErr(text);
285 }
286}
287
288
289
290var jsCallStartIndex = 1;
291var functionPointers = new Array(0);
292
293// 'sig' parameter is only used on LLVM wasm backend
294function addFunction(func, sig) {
295 if (typeof sig === 'undefined') {
296 Module.printErr('Warning: addFunction: Provide a wasm function signature ' +
297 'string as a second argument');
298 }
299 var base = 0;
300 for (var i = base; i < base + 0; i++) {
301 if (!functionPointers[i]) {
302 functionPointers[i] = func;
303 return jsCallStartIndex + i;
304 }
305 }
306 throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
307}
308
309function removeFunction(index) {
310 functionPointers[index-jsCallStartIndex] = null;
311}
312
313var funcWrappers = {};
314
315function getFuncWrapper(func, sig) {
316 if (!func) return; // on null pointer, return undefined
317 assert(sig);
318 if (!funcWrappers[sig]) {
319 funcWrappers[sig] = {};
320 }
321 var sigCache = funcWrappers[sig];
322 if (!sigCache[func]) {
323 // optimize away arguments usage in common cases
324 if (sig.length === 1) {
325 sigCache[func] = function dynCall_wrapper() {
326 return dynCall(sig, func);
327 };
328 } else if (sig.length === 2) {
329 sigCache[func] = function dynCall_wrapper(arg) {
330 return dynCall(sig, func, [arg]);
331 };
332 } else {
333 // general case
334 sigCache[func] = function dynCall_wrapper() {
335 return dynCall(sig, func, Array.prototype.slice.call(arguments));
336 };
337 }
338 }
339 return sigCache[func];
340}
341
342
343function makeBigInt(low, high, unsigned) {
344 return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0));
345}
346
347function dynCall(sig, ptr, args) {
348 if (args && args.length) {
349 assert(args.length == sig.length-1);
350 assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
351 return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
352 } else {
353 assert(sig.length == 1);
354 assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
355 return Module['dynCall_' + sig].call(null, ptr);
356 }
357}
358
359
360function getCompilerSetting(name) {
361 throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for getCompilerSetting or emscripten_get_compiler_setting to work';
362}
363
364var Runtime = {
365 // FIXME backwards compatibility layer for ports. Support some Runtime.*
366 // for now, fix it there, then remove it from here. That way we
367 // can minimize any period of breakage.
368 dynCall: dynCall, // for SDL2 port
369 // helpful errors
370 getTempRet0: function() { abort('getTempRet0() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
371 staticAlloc: function() { abort('staticAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
372 stackAlloc: function() { abort('stackAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
373};
374
375// The address globals begin at. Very low in memory, for code size and optimization opportunities.
376// Above 0 is static memory, starting with globals.
377// Then the stack.
378// Then 'dynamic' memory for sbrk.
379var GLOBAL_BASE = 1024;
380
381
382
383// === Preamble library stuff ===
384
385// Documentation for the public APIs defined in this file must be updated in:
386// site/source/docs/api_reference/preamble.js.rst
387// A prebuilt local version of the documentation is available at:
388// site/build/text/docs/api_reference/preamble.js.txt
389// You can also build docs locally as HTML or other formats in site/
390// An online HTML version (which may be of a different version of Emscripten)
391// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
392
393
394
395//========================================
396// Runtime essentials
397//========================================
398
399var ABORT = 0; // whether we are quitting the application. no code should run after this. set in exit() and abort()
400var EXITSTATUS = 0;
401
402/** @type {function(*, string=)} */
403function assert(condition, text) {
404 if (!condition) {
405 abort('Assertion failed: ' + text);
406 }
407}
408
409var globalScope = this;
410
411// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
412function getCFunc(ident) {
413 var func = Module['_' + ident]; // closure exported function
414 assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
415 return func;
416}
417
418var JSfuncs = {
419 // Helpers for cwrap -- it can't refer to Runtime directly because it might
420 // be renamed by closure, instead it calls JSfuncs['stackSave'].body to find
421 // out what the minified function name is.
422 'stackSave': function() {
423 stackSave()
424 },
425 'stackRestore': function() {
426 stackRestore()
427 },
428 // type conversion from js to c
429 'arrayToC' : function(arr) {
430 var ret = stackAlloc(arr.length);
431 writeArrayToMemory(arr, ret);
432 return ret;
433 },
434 'stringToC' : function(str) {
435 var ret = 0;
436 if (str !== null && str !== undefined && str !== 0) { // null string
437 // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
438 var len = (str.length << 2) + 1;
439 ret = stackAlloc(len);
440 stringToUTF8(str, ret, len);
441 }
442 return ret;
443 }
444};
445// For fast lookup of conversion functions
446var toC = {'string' : JSfuncs['stringToC'], 'array' : JSfuncs['arrayToC']};
447
448// C calling interface.
449function ccall (ident, returnType, argTypes, args, opts) {
450 var func = getCFunc(ident);
451 var cArgs = [];
452 var stack = 0;
453 assert(returnType !== 'array', 'Return type should not be "array".');
454 if (args) {
455 for (var i = 0; i < args.length; i++) {
456 var converter = toC[argTypes[i]];
457 if (converter) {
458 if (stack === 0) stack = stackSave();
459 cArgs[i] = converter(args[i]);
460 } else {
461 cArgs[i] = args[i];
462 }
463 }
464 }
465 var ret = func.apply(null, cArgs);
466 if (returnType === 'string') ret = Pointer_stringify(ret);
467 if (stack !== 0) {
468 stackRestore(stack);
469 }
470 return ret;
471}
472
473function cwrap (ident, returnType, argTypes) {
474 argTypes = argTypes || [];
475 var cfunc = getCFunc(ident);
476 // When the function takes numbers and returns a number, we can just return
477 // the original function
478 var numericArgs = argTypes.every(function(type){ return type === 'number'});
479 var numericRet = returnType !== 'string';
480 if (numericRet && numericArgs) {
481 return cfunc;
482 }
483 return function() {
484 return ccall(ident, returnType, argTypes, arguments);
485 }
486}
487
488/** @type {function(number, number, string, boolean=)} */
489function setValue(ptr, value, type, noSafe) {
490 type = type || 'i8';
491 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
492 switch(type) {
493 case 'i1': HEAP8[((ptr)>>0)]=value; break;
494 case 'i8': HEAP8[((ptr)>>0)]=value; break;
495 case 'i16': HEAP16[((ptr)>>1)]=value; break;
496 case 'i32': HEAP32[((ptr)>>2)]=value; break;
497 case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
498 case 'float': HEAPF32[((ptr)>>2)]=value; break;
499 case 'double': HEAPF64[((ptr)>>3)]=value; break;
500 default: abort('invalid type for setValue: ' + type);
501 }
502}
503
504/** @type {function(number, string, boolean=)} */
505function getValue(ptr, type, noSafe) {
506 type = type || 'i8';
507 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
508 switch(type) {
509 case 'i1': return HEAP8[((ptr)>>0)];
510 case 'i8': return HEAP8[((ptr)>>0)];
511 case 'i16': return HEAP16[((ptr)>>1)];
512 case 'i32': return HEAP32[((ptr)>>2)];
513 case 'i64': return HEAP32[((ptr)>>2)];
514 case 'float': return HEAPF32[((ptr)>>2)];
515 case 'double': return HEAPF64[((ptr)>>3)];
516 default: abort('invalid type for getValue: ' + type);
517 }
518 return null;
519}
520
521var ALLOC_NORMAL = 0; // Tries to use _malloc()
522var ALLOC_STACK = 1; // Lives for the duration of the current function call
523var ALLOC_STATIC = 2; // Cannot be freed
524var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
525var ALLOC_NONE = 4; // Do not allocate
526
527// allocate(): This is for internal use. You can use it yourself as well, but the interface
528// is a little tricky (see docs right below). The reason is that it is optimized
529// for multiple syntaxes to save space in generated code. So you should
530// normally not use allocate(), and instead allocate memory using _malloc(),
531// initialize it with setValue(), and so forth.
532// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
533// in *bytes* (note that this is sometimes confusing: the next parameter does not
534// affect this!)
535// @types: Either an array of types, one for each byte (or 0 if no type at that position),
536// or a single type which is used for the entire block. This only matters if there
537// is initial data - if @slab is a number, then this does not matter at all and is
538// ignored.
539// @allocator: How to allocate memory, see ALLOC_*
540/** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
541function allocate(slab, types, allocator, ptr) {
542 var zeroinit, size;
543 if (typeof slab === 'number') {
544 zeroinit = true;
545 size = slab;
546 } else {
547 zeroinit = false;
548 size = slab.length;
549 }
550
551 var singleType = typeof types === 'string' ? types : null;
552
553 var ret;
554 if (allocator == ALLOC_NONE) {
555 ret = ptr;
556 } else {
557 ret = [typeof _malloc === 'function' ? _malloc : staticAlloc, stackAlloc, staticAlloc, dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
558 }
559
560 if (zeroinit) {
561 var stop;
562 ptr = ret;
563 assert((ret & 3) == 0);
564 stop = ret + (size & ~3);
565 for (; ptr < stop; ptr += 4) {
566 HEAP32[((ptr)>>2)]=0;
567 }
568 stop = ret + size;
569 while (ptr < stop) {
570 HEAP8[((ptr++)>>0)]=0;
571 }
572 return ret;
573 }
574
575 if (singleType === 'i8') {
576 if (slab.subarray || slab.slice) {
577 HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
578 } else {
579 HEAPU8.set(new Uint8Array(slab), ret);
580 }
581 return ret;
582 }
583
584 var i = 0, type, typeSize, previousType;
585 while (i < size) {
586 var curr = slab[i];
587
588 type = singleType || types[i];
589 if (type === 0) {
590 i++;
591 continue;
592 }
593 assert(type, 'Must know what type to store in allocate!');
594
595 if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
596
597 setValue(ret+i, curr, type);
598
599 // no need to look up size unless type changes, so cache it
600 if (previousType !== type) {
601 typeSize = getNativeTypeSize(type);
602 previousType = type;
603 }
604 i += typeSize;
605 }
606
607 return ret;
608}
609
610// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
611function getMemory(size) {
612 if (!staticSealed) return staticAlloc(size);
613 if (!runtimeInitialized) return dynamicAlloc(size);
614 return _malloc(size);
615}
616
617/** @type {function(number, number=)} */
618function Pointer_stringify(ptr, length) {
619 if (length === 0 || !ptr) return '';
620 // TODO: use TextDecoder
621 // Find the length, and check for UTF while doing so
622 var hasUtf = 0;
623 var t;
624 var i = 0;
625 while (1) {
626 assert(ptr + i < TOTAL_MEMORY);
627 t = HEAPU8[(((ptr)+(i))>>0)];
628 hasUtf |= t;
629 if (t == 0 && !length) break;
630 i++;
631 if (length && i == length) break;
632 }
633 if (!length) length = i;
634
635 var ret = '';
636
637 if (hasUtf < 128) {
638 var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
639 var curr;
640 while (length > 0) {
641 curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
642 ret = ret ? ret + curr : curr;
643 ptr += MAX_CHUNK;
644 length -= MAX_CHUNK;
645 }
646 return ret;
647 }
648 return UTF8ToString(ptr);
649}
650
651// Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
652// a copy of that string as a Javascript String object.
653
654function AsciiToString(ptr) {
655 var str = '';
656 while (1) {
657 var ch = HEAP8[((ptr++)>>0)];
658 if (!ch) return str;
659 str += String.fromCharCode(ch);
660 }
661}
662
663// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
664// null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
665
666function stringToAscii(str, outPtr) {
667 return writeAsciiToMemory(str, outPtr, false);
668}
669
670// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
671// a copy of that string as a Javascript String object.
672
673var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
674function UTF8ArrayToString(u8Array, idx) {
675 var endPtr = idx;
676 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
677 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
678 while (u8Array[endPtr]) ++endPtr;
679
680 if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
681 return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
682 } else {
683 var u0, u1, u2, u3, u4, u5;
684
685 var str = '';
686 while (1) {
687 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
688 u0 = u8Array[idx++];
689 if (!u0) return str;
690 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
691 u1 = u8Array[idx++] & 63;
692 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
693 u2 = u8Array[idx++] & 63;
694 if ((u0 & 0xF0) == 0xE0) {
695 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
696 } else {
697 u3 = u8Array[idx++] & 63;
698 if ((u0 & 0xF8) == 0xF0) {
699 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | u3;
700 } else {
701 u4 = u8Array[idx++] & 63;
702 if ((u0 & 0xFC) == 0xF8) {
703 u0 = ((u0 & 3) << 24) | (u1 << 18) | (u2 << 12) | (u3 << 6) | u4;
704 } else {
705 u5 = u8Array[idx++] & 63;
706 u0 = ((u0 & 1) << 30) | (u1 << 24) | (u2 << 18) | (u3 << 12) | (u4 << 6) | u5;
707 }
708 }
709 }
710 if (u0 < 0x10000) {
711 str += String.fromCharCode(u0);
712 } else {
713 var ch = u0 - 0x10000;
714 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
715 }
716 }
717 }
718}
719
720// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns
721// a copy of that string as a Javascript String object.
722
723function UTF8ToString(ptr) {
724 return UTF8ArrayToString(HEAPU8,ptr);
725}
726
727// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
728// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
729// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
730// Parameters:
731// str: the Javascript string to copy.
732// outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element.
733// outIdx: The starting offset in the array to begin the copying.
734// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
735// terminator, i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
736// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
737// Returns the number of bytes written, EXCLUDING the null terminator.
738
739function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) {
740 if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
741 return 0;
742
743 var startIdx = outIdx;
744 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
745 for (var i = 0; i < str.length; ++i) {
746 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
747 // See http://unicode.org/faq/utf_bom.html#utf16-3
748 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
749 var u = str.charCodeAt(i); // possibly a lead surrogate
750 if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
751 if (u <= 0x7F) {
752 if (outIdx >= endIdx) break;
753 outU8Array[outIdx++] = u;
754 } else if (u <= 0x7FF) {
755 if (outIdx + 1 >= endIdx) break;
756 outU8Array[outIdx++] = 0xC0 | (u >> 6);
757 outU8Array[outIdx++] = 0x80 | (u & 63);
758 } else if (u <= 0xFFFF) {
759 if (outIdx + 2 >= endIdx) break;
760 outU8Array[outIdx++] = 0xE0 | (u >> 12);
761 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
762 outU8Array[outIdx++] = 0x80 | (u & 63);
763 } else if (u <= 0x1FFFFF) {
764 if (outIdx + 3 >= endIdx) break;
765 outU8Array[outIdx++] = 0xF0 | (u >> 18);
766 outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
767 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
768 outU8Array[outIdx++] = 0x80 | (u & 63);
769 } else if (u <= 0x3FFFFFF) {
770 if (outIdx + 4 >= endIdx) break;
771 outU8Array[outIdx++] = 0xF8 | (u >> 24);
772 outU8Array[outIdx++] = 0x80 | ((u >> 18) & 63);
773 outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
774 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
775 outU8Array[outIdx++] = 0x80 | (u & 63);
776 } else {
777 if (outIdx + 5 >= endIdx) break;
778 outU8Array[outIdx++] = 0xFC | (u >> 30);
779 outU8Array[outIdx++] = 0x80 | ((u >> 24) & 63);
780 outU8Array[outIdx++] = 0x80 | ((u >> 18) & 63);
781 outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
782 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
783 outU8Array[outIdx++] = 0x80 | (u & 63);
784 }
785 }
786 // Null-terminate the pointer to the buffer.
787 outU8Array[outIdx] = 0;
788 return outIdx - startIdx;
789}
790
791// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
792// null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
793// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
794// Returns the number of bytes written, EXCLUDING the null terminator.
795
796function stringToUTF8(str, outPtr, maxBytesToWrite) {
797 assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
798 return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
799}
800
801// Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
802
803function lengthBytesUTF8(str) {
804 var len = 0;
805 for (var i = 0; i < str.length; ++i) {
806 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
807 // See http://unicode.org/faq/utf_bom.html#utf16-3
808 var u = str.charCodeAt(i); // possibly a lead surrogate
809 if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
810 if (u <= 0x7F) {
811 ++len;
812 } else if (u <= 0x7FF) {
813 len += 2;
814 } else if (u <= 0xFFFF) {
815 len += 3;
816 } else if (u <= 0x1FFFFF) {
817 len += 4;
818 } else if (u <= 0x3FFFFFF) {
819 len += 5;
820 } else {
821 len += 6;
822 }
823 }
824 return len;
825}
826
827// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
828// a copy of that string as a Javascript String object.
829
830var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
831function UTF16ToString(ptr) {
832 assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
833 var endPtr = ptr;
834 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
835 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
836 var idx = endPtr >> 1;
837 while (HEAP16[idx]) ++idx;
838 endPtr = idx << 1;
839
840 if (endPtr - ptr > 32 && UTF16Decoder) {
841 return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
842 } else {
843 var i = 0;
844
845 var str = '';
846 while (1) {
847 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
848 if (codeUnit == 0) return str;
849 ++i;
850 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
851 str += String.fromCharCode(codeUnit);
852 }
853 }
854}
855
856// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
857// null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
858// Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
859// Parameters:
860// str: the Javascript string to copy.
861// outPtr: Byte address in Emscripten HEAP where to write the string to.
862// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
863// terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
864// maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
865// Returns the number of bytes written, EXCLUDING the null terminator.
866
867function stringToUTF16(str, outPtr, maxBytesToWrite) {
868 assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
869 assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
870 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
871 if (maxBytesToWrite === undefined) {
872 maxBytesToWrite = 0x7FFFFFFF;
873 }
874 if (maxBytesToWrite < 2) return 0;
875 maxBytesToWrite -= 2; // Null terminator.
876 var startPtr = outPtr;
877 var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
878 for (var i = 0; i < numCharsToWrite; ++i) {
879 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
880 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
881 HEAP16[((outPtr)>>1)]=codeUnit;
882 outPtr += 2;
883 }
884 // Null-terminate the pointer to the HEAP.
885 HEAP16[((outPtr)>>1)]=0;
886 return outPtr - startPtr;
887}
888
889// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
890
891function lengthBytesUTF16(str) {
892 return str.length*2;
893}
894
895function UTF32ToString(ptr) {
896 assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
897 var i = 0;
898
899 var str = '';
900 while (1) {
901 var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
902 if (utf32 == 0)
903 return str;
904 ++i;
905 // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing.
906 // See http://unicode.org/faq/utf_bom.html#utf16-3
907 if (utf32 >= 0x10000) {
908 var ch = utf32 - 0x10000;
909 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
910 } else {
911 str += String.fromCharCode(utf32);
912 }
913 }
914}
915
916// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
917// null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
918// Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
919// Parameters:
920// str: the Javascript string to copy.
921// outPtr: Byte address in Emscripten HEAP where to write the string to.
922// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
923// terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
924// maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
925// Returns the number of bytes written, EXCLUDING the null terminator.
926
927function stringToUTF32(str, outPtr, maxBytesToWrite) {
928 assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
929 assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
930 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
931 if (maxBytesToWrite === undefined) {
932 maxBytesToWrite = 0x7FFFFFFF;
933 }
934 if (maxBytesToWrite < 4) return 0;
935 var startPtr = outPtr;
936 var endPtr = startPtr + maxBytesToWrite - 4;
937 for (var i = 0; i < str.length; ++i) {
938 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
939 // See http://unicode.org/faq/utf_bom.html#utf16-3
940 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
941 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
942 var trailSurrogate = str.charCodeAt(++i);
943 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
944 }
945 HEAP32[((outPtr)>>2)]=codeUnit;
946 outPtr += 4;
947 if (outPtr + 4 > endPtr) break;
948 }
949 // Null-terminate the pointer to the HEAP.
950 HEAP32[((outPtr)>>2)]=0;
951 return outPtr - startPtr;
952}
953
954// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
955
956function lengthBytesUTF32(str) {
957 var len = 0;
958 for (var i = 0; i < str.length; ++i) {
959 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
960 // See http://unicode.org/faq/utf_bom.html#utf16-3
961 var codeUnit = str.charCodeAt(i);
962 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
963 len += 4;
964 }
965
966 return len;
967}
968
969// Allocate heap space for a JS string, and write it there.
970// It is the responsibility of the caller to free() that memory.
971function allocateUTF8(str) {
972 var size = lengthBytesUTF8(str) + 1;
973 var ret = _malloc(size);
974 if (ret) stringToUTF8Array(str, HEAP8, ret, size);
975 return ret;
976}
977
978// Allocate stack space for a JS string, and write it there.
979function allocateUTF8OnStack(str) {
980 var size = lengthBytesUTF8(str) + 1;
981 var ret = stackAlloc(size);
982 stringToUTF8Array(str, HEAP8, ret, size);
983 return ret;
984}
985
986function demangle(func) {
987 warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
988 return func;
989}
990
991function demangleAll(text) {
992 var regex =
993 /__Z[\w\d_]+/g;
994 return text.replace(regex,
995 function(x) {
996 var y = demangle(x);
997 return x === y ? x : (x + ' [' + y + ']');
998 });
999}
1000
1001function jsStackTrace() {
1002 var err = new Error();
1003 if (!err.stack) {
1004 // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
1005 // so try that as a special-case.
1006 try {
1007 throw new Error(0);
1008 } catch(e) {
1009 err = e;
1010 }
1011 if (!err.stack) {
1012 return '(no stack trace available)';
1013 }
1014 }
1015 return err.stack.toString();
1016}
1017
1018function stackTrace() {
1019 var js = jsStackTrace();
1020 if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
1021 return demangleAll(js);
1022}
1023
1024// Memory management
1025
1026var PAGE_SIZE = 16384;
1027var WASM_PAGE_SIZE = 65536;
1028var ASMJS_PAGE_SIZE = 16777216;
1029var MIN_TOTAL_MEMORY = 16777216;
1030
1031function alignUp(x, multiple) {
1032 if (x % multiple > 0) {
1033 x += multiple - (x % multiple);
1034 }
1035 return x;
1036}
1037
1038var HEAP,
1039/** @type {ArrayBuffer} */
1040 buffer,
1041/** @type {Int8Array} */
1042 HEAP8,
1043/** @type {Uint8Array} */
1044 HEAPU8,
1045/** @type {Int16Array} */
1046 HEAP16,
1047/** @type {Uint16Array} */
1048 HEAPU16,
1049/** @type {Int32Array} */
1050 HEAP32,
1051/** @type {Uint32Array} */
1052 HEAPU32,
1053/** @type {Float32Array} */
1054 HEAPF32,
1055/** @type {Float64Array} */
1056 HEAPF64;
1057
1058function updateGlobalBuffer(buf) {
1059 Module['buffer'] = buffer = buf;
1060}
1061
1062function updateGlobalBufferViews() {
1063 Module['HEAP8'] = HEAP8 = new Int8Array(buffer);
1064 Module['HEAP16'] = HEAP16 = new Int16Array(buffer);
1065 Module['HEAP32'] = HEAP32 = new Int32Array(buffer);
1066 Module['HEAPU8'] = HEAPU8 = new Uint8Array(buffer);
1067 Module['HEAPU16'] = HEAPU16 = new Uint16Array(buffer);
1068 Module['HEAPU32'] = HEAPU32 = new Uint32Array(buffer);
1069 Module['HEAPF32'] = HEAPF32 = new Float32Array(buffer);
1070 Module['HEAPF64'] = HEAPF64 = new Float64Array(buffer);
1071}
1072
1073var STATIC_BASE, STATICTOP, staticSealed; // static area
1074var STACK_BASE, STACKTOP, STACK_MAX; // stack area
1075var DYNAMIC_BASE, DYNAMICTOP_PTR; // dynamic area handled by sbrk
1076
1077 STATIC_BASE = STATICTOP = STACK_BASE = STACKTOP = STACK_MAX = DYNAMIC_BASE = DYNAMICTOP_PTR = 0;
1078 staticSealed = false;
1079
1080
1081// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
1082function writeStackCookie() {
1083 assert((STACK_MAX & 3) == 0);
1084 HEAPU32[(STACK_MAX >> 2)-1] = 0x02135467;
1085 HEAPU32[(STACK_MAX >> 2)-2] = 0x89BACDFE;
1086}
1087
1088function checkStackCookie() {
1089 if (HEAPU32[(STACK_MAX >> 2)-1] != 0x02135467 || HEAPU32[(STACK_MAX >> 2)-2] != 0x89BACDFE) {
1090 abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x02135467, but received 0x' + HEAPU32[(STACK_MAX >> 2)-2].toString(16) + ' ' + HEAPU32[(STACK_MAX >> 2)-1].toString(16));
1091 }
1092 // Also test the global address 0 for integrity. This check is not compatible with SAFE_SPLIT_MEMORY though, since that mode already tests all address 0 accesses on its own.
1093 if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) throw 'Runtime error: The application has corrupted its heap memory area (address zero)!';
1094}
1095
1096function abortStackOverflow(allocSize) {
1097 abort('Stack overflow! Attempted to allocate ' + allocSize + ' bytes on the stack, but stack has only ' + (STACK_MAX - stackSave() + allocSize) + ' bytes available!');
1098}
1099
1100function abortOnCannotGrowMemory() {
1101 abort('Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value ' + TOTAL_MEMORY + ', (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 ');
1102}
1103
1104if (!Module['reallocBuffer']) Module['reallocBuffer'] = function(size) {
1105 var ret;
1106 try {
1107 if (ArrayBuffer.transfer) {
1108 ret = ArrayBuffer.transfer(buffer, size);
1109 } else {
1110 var oldHEAP8 = HEAP8;
1111 ret = new ArrayBuffer(size);
1112 var temp = new Int8Array(ret);
1113 temp.set(oldHEAP8);
1114 }
1115 } catch(e) {
1116 return false;
1117 }
1118 var success = _emscripten_replace_memory(ret);
1119 if (!success) return false;
1120 return ret;
1121};
1122
1123function enlargeMemory() {
1124 // TOTAL_MEMORY is the current size of the actual array, and DYNAMICTOP is the new top.
1125 assert(HEAP32[DYNAMICTOP_PTR>>2] > TOTAL_MEMORY); // This function should only ever be called after the ceiling of the dynamic heap has already been bumped to exceed the current total size of the asm.js heap.
1126
1127
1128 var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; // In wasm, heap size must be a multiple of 64KB. In asm.js, they need to be multiples of 16MB.
1129 var LIMIT = 2147483648 - PAGE_MULTIPLE; // We can do one page short of 2GB as theoretical maximum.
1130
1131 if (HEAP32[DYNAMICTOP_PTR>>2] > LIMIT) {
1132 Module.printErr('Cannot enlarge memory, asked to go up to ' + HEAP32[DYNAMICTOP_PTR>>2] + ' bytes, but the limit is ' + LIMIT + ' bytes!');
1133 return false;
1134 }
1135
1136 var OLD_TOTAL_MEMORY = TOTAL_MEMORY;
1137 TOTAL_MEMORY = Math.max(TOTAL_MEMORY, MIN_TOTAL_MEMORY); // So the loop below will not be infinite, and minimum asm.js memory size is 16MB.
1138
1139 while (TOTAL_MEMORY < HEAP32[DYNAMICTOP_PTR>>2]) { // Keep incrementing the heap size as long as it's less than what is requested.
1140 if (TOTAL_MEMORY <= 536870912) {
1141 TOTAL_MEMORY = alignUp(2 * TOTAL_MEMORY, PAGE_MULTIPLE); // Simple heuristic: double until 1GB...
1142 } else {
1143 TOTAL_MEMORY = Math.min(alignUp((3 * TOTAL_MEMORY + 2147483648) / 4, PAGE_MULTIPLE), LIMIT); // ..., but after that, add smaller increments towards 2GB, which we cannot reach
1144 }
1145 }
1146
1147 var start = Date.now();
1148
1149 var replacement = Module['reallocBuffer'](TOTAL_MEMORY);
1150 if (!replacement || replacement.byteLength != TOTAL_MEMORY) {
1151 Module.printErr('Failed to grow the heap from ' + OLD_TOTAL_MEMORY + ' bytes to ' + TOTAL_MEMORY + ' bytes, not enough memory!');
1152 if (replacement) {
1153 Module.printErr('Expected to get back a buffer of size ' + TOTAL_MEMORY + ' bytes, but instead got back a buffer of size ' + replacement.byteLength);
1154 }
1155 // restore the state to before this call, we failed
1156 TOTAL_MEMORY = OLD_TOTAL_MEMORY;
1157 return false;
1158 }
1159
1160 // everything worked
1161
1162 updateGlobalBuffer(replacement);
1163 updateGlobalBufferViews();
1164
1165 Module.printErr('enlarged memory arrays from ' + OLD_TOTAL_MEMORY + ' to ' + TOTAL_MEMORY + ', took ' + (Date.now() - start) + ' ms (has ArrayBuffer.transfer? ' + (!!ArrayBuffer.transfer) + ')');
1166
1167 if (!Module["usingWasm"]) {
1168 Module.printErr('Warning: Enlarging memory arrays, this is not fast! ' + [OLD_TOTAL_MEMORY, TOTAL_MEMORY]);
1169 }
1170
1171
1172 return true;
1173}
1174
1175var byteLength;
1176try {
1177 byteLength = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get);
1178 byteLength(new ArrayBuffer(4)); // can fail on older ie
1179} catch(e) { // can fail on older node/v8
1180 byteLength = function(buffer) { return buffer.byteLength; };
1181}
1182
1183var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
1184var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216;
1185if (TOTAL_MEMORY < TOTAL_STACK) Module.printErr('TOTAL_MEMORY should be larger than TOTAL_STACK, was ' + TOTAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
1186
1187// Initialize the runtime's memory
1188// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1189assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined,
1190 'JS engine does not provide full typed array support');
1191
1192
1193
1194// Use a provided buffer, if there is one, or else allocate a new one
1195if (Module['buffer']) {
1196 buffer = Module['buffer'];
1197 assert(buffer.byteLength === TOTAL_MEMORY, 'provided buffer should be ' + TOTAL_MEMORY + ' bytes, but it is ' + buffer.byteLength);
1198} else {
1199 // Use a WebAssembly memory where available
1200 if (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function') {
1201 assert(TOTAL_MEMORY % WASM_PAGE_SIZE === 0);
1202 Module['wasmMemory'] = new WebAssembly.Memory({ 'initial': TOTAL_MEMORY / WASM_PAGE_SIZE });
1203 buffer = Module['wasmMemory'].buffer;
1204 } else
1205 {
1206 buffer = new ArrayBuffer(TOTAL_MEMORY);
1207 }
1208 assert(buffer.byteLength === TOTAL_MEMORY);
1209 Module['buffer'] = buffer;
1210}
1211updateGlobalBufferViews();
1212
1213
1214function getTotalMemory() {
1215 return TOTAL_MEMORY;
1216}
1217
1218// Endianness check (note: assumes compiler arch was little-endian)
1219 HEAP32[0] = 0x63736d65; /* 'emsc' */
1220HEAP16[1] = 0x6373;
1221if (HEAPU8[2] !== 0x73 || HEAPU8[3] !== 0x63) throw 'Runtime error: expected the system to be little-endian!';
1222
1223function callRuntimeCallbacks(callbacks) {
1224 while(callbacks.length > 0) {
1225 var callback = callbacks.shift();
1226 if (typeof callback == 'function') {
1227 callback();
1228 continue;
1229 }
1230 var func = callback.func;
1231 if (typeof func === 'number') {
1232 if (callback.arg === undefined) {
1233 Module['dynCall_v'](func);
1234 } else {
1235 Module['dynCall_vi'](func, callback.arg);
1236 }
1237 } else {
1238 func(callback.arg === undefined ? null : callback.arg);
1239 }
1240 }
1241}
1242
1243var __ATPRERUN__ = []; // functions called before the runtime is initialized
1244var __ATINIT__ = []; // functions called during startup
1245var __ATMAIN__ = []; // functions called when main() is to be run
1246var __ATEXIT__ = []; // functions called during shutdown
1247var __ATPOSTRUN__ = []; // functions called after the runtime has exited
1248
1249var runtimeInitialized = false;
1250var runtimeExited = false;
1251
1252
1253function preRun() {
1254 // compatibility - merge in anything from Module['preRun'] at this time
1255 if (Module['preRun']) {
1256 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1257 while (Module['preRun'].length) {
1258 addOnPreRun(Module['preRun'].shift());
1259 }
1260 }
1261 callRuntimeCallbacks(__ATPRERUN__);
1262}
1263
1264function ensureInitRuntime() {
1265 checkStackCookie();
1266 if (runtimeInitialized) return;
1267 runtimeInitialized = true;
1268 callRuntimeCallbacks(__ATINIT__);
1269}
1270
1271function preMain() {
1272 checkStackCookie();
1273 callRuntimeCallbacks(__ATMAIN__);
1274}
1275
1276function exitRuntime() {
1277 checkStackCookie();
1278 callRuntimeCallbacks(__ATEXIT__);
1279 runtimeExited = true;
1280}
1281
1282function postRun() {
1283 checkStackCookie();
1284 // compatibility - merge in anything from Module['postRun'] at this time
1285 if (Module['postRun']) {
1286 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1287 while (Module['postRun'].length) {
1288 addOnPostRun(Module['postRun'].shift());
1289 }
1290 }
1291 callRuntimeCallbacks(__ATPOSTRUN__);
1292}
1293
1294function addOnPreRun(cb) {
1295 __ATPRERUN__.unshift(cb);
1296}
1297
1298function addOnInit(cb) {
1299 __ATINIT__.unshift(cb);
1300}
1301
1302function addOnPreMain(cb) {
1303 __ATMAIN__.unshift(cb);
1304}
1305
1306function addOnExit(cb) {
1307 __ATEXIT__.unshift(cb);
1308}
1309
1310function addOnPostRun(cb) {
1311 __ATPOSTRUN__.unshift(cb);
1312}
1313
1314// Deprecated: This function should not be called because it is unsafe and does not provide
1315// a maximum length limit of how many bytes it is allowed to write. Prefer calling the
1316// function stringToUTF8Array() instead, which takes in a maximum length that can be used
1317// to be secure from out of bounds writes.
1318/** @deprecated */
1319function writeStringToMemory(string, buffer, dontAddNull) {
1320 warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
1321
1322 var /** @type {number} */ lastChar, /** @type {number} */ end;
1323 if (dontAddNull) {
1324 // stringToUTF8Array always appends null. If we don't want to do that, remember the
1325 // character that existed at the location where the null will be placed, and restore
1326 // that after the write (below).
1327 end = buffer + lengthBytesUTF8(string);
1328 lastChar = HEAP8[end];
1329 }
1330 stringToUTF8(string, buffer, Infinity);
1331 if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
1332}
1333
1334function writeArrayToMemory(array, buffer) {
1335 assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')
1336 HEAP8.set(array, buffer);
1337}
1338
1339function writeAsciiToMemory(str, buffer, dontAddNull) {
1340 for (var i = 0; i < str.length; ++i) {
1341 assert(str.charCodeAt(i) === str.charCodeAt(i)&0xff);
1342 HEAP8[((buffer++)>>0)]=str.charCodeAt(i);
1343 }
1344 // Null-terminate the pointer to the HEAP.
1345 if (!dontAddNull) HEAP8[((buffer)>>0)]=0;
1346}
1347
1348function unSign(value, bits, ignore) {
1349 if (value >= 0) {
1350 return value;
1351 }
1352 return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value // Need some trickery, since if bits == 32, we are right at the limit of the bits JS uses in bitshifts
1353 : Math.pow(2, bits) + value;
1354}
1355function reSign(value, bits, ignore) {
1356 if (value <= 0) {
1357 return value;
1358 }
1359 var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1360 : Math.pow(2, bits-1);
1361 if (value >= half && (bits <= 32 || value > half)) { // for huge values, we can hit the precision limit and always get true here. so don't do that
1362 // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1363 // TODO: In i64 mode 1, resign the two parts separately and safely
1364 value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1365 }
1366 return value;
1367}
1368
1369assert(Math['imul'] && Math['fround'] && Math['clz32'] && Math['trunc'], 'this is a legacy browser, build with LEGACY_VM_SUPPORT');
1370
1371var Math_abs = Math.abs;
1372var Math_cos = Math.cos;
1373var Math_sin = Math.sin;
1374var Math_tan = Math.tan;
1375var Math_acos = Math.acos;
1376var Math_asin = Math.asin;
1377var Math_atan = Math.atan;
1378var Math_atan2 = Math.atan2;
1379var Math_exp = Math.exp;
1380var Math_log = Math.log;
1381var Math_sqrt = Math.sqrt;
1382var Math_ceil = Math.ceil;
1383var Math_floor = Math.floor;
1384var Math_pow = Math.pow;
1385var Math_imul = Math.imul;
1386var Math_fround = Math.fround;
1387var Math_round = Math.round;
1388var Math_min = Math.min;
1389var Math_max = Math.max;
1390var Math_clz32 = Math.clz32;
1391var Math_trunc = Math.trunc;
1392
1393// A counter of dependencies for calling run(). If we need to
1394// do asynchronous work before running, increment this and
1395// decrement it. Incrementing must happen in a place like
1396// PRE_RUN_ADDITIONS (used by emcc to add file preloading).
1397// Note that you can add dependencies in preRun, even though
1398// it happens right before run - run will be postponed until
1399// the dependencies are met.
1400var runDependencies = 0;
1401var runDependencyWatcher = null;
1402var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1403var runDependencyTracking = {};
1404
1405function getUniqueRunDependency(id) {
1406 var orig = id;
1407 while (1) {
1408 if (!runDependencyTracking[id]) return id;
1409 id = orig + Math.random();
1410 }
1411 return id;
1412}
1413
1414function addRunDependency(id) {
1415 runDependencies++;
1416 if (Module['monitorRunDependencies']) {
1417 Module['monitorRunDependencies'](runDependencies);
1418 }
1419 if (id) {
1420 assert(!runDependencyTracking[id]);
1421 runDependencyTracking[id] = 1;
1422 if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
1423 // Check for missing dependencies every few seconds
1424 runDependencyWatcher = setInterval(function() {
1425 if (ABORT) {
1426 clearInterval(runDependencyWatcher);
1427 runDependencyWatcher = null;
1428 return;
1429 }
1430 var shown = false;
1431 for (var dep in runDependencyTracking) {
1432 if (!shown) {
1433 shown = true;
1434 Module.printErr('still waiting on run dependencies:');
1435 }
1436 Module.printErr('dependency: ' + dep);
1437 }
1438 if (shown) {
1439 Module.printErr('(end of list)');
1440 }
1441 }, 10000);
1442 }
1443 } else {
1444 Module.printErr('warning: run dependency added without ID');
1445 }
1446}
1447
1448function removeRunDependency(id) {
1449 runDependencies--;
1450 if (Module['monitorRunDependencies']) {
1451 Module['monitorRunDependencies'](runDependencies);
1452 }
1453 if (id) {
1454 assert(runDependencyTracking[id]);
1455 delete runDependencyTracking[id];
1456 } else {
1457 Module.printErr('warning: run dependency removed without ID');
1458 }
1459 if (runDependencies == 0) {
1460 if (runDependencyWatcher !== null) {
1461 clearInterval(runDependencyWatcher);
1462 runDependencyWatcher = null;
1463 }
1464 if (dependenciesFulfilled) {
1465 var callback = dependenciesFulfilled;
1466 dependenciesFulfilled = null;
1467 callback(); // can add another dependenciesFulfilled
1468 }
1469 }
1470}
1471
1472Module["preloadedImages"] = {}; // maps url to image data
1473Module["preloadedAudios"] = {}; // maps url to audio data
1474
1475
1476
1477var memoryInitializer = null;
1478
1479
1480
1481
1482
1483
1484// Prefix of data URIs emitted by SINGLE_FILE and related options.
1485var dataURIPrefix = 'data:application/octet-stream;base64,';
1486
1487// Indicates whether filename is a base64 data URI.
1488function isDataURI(filename) {
1489 return String.prototype.startsWith ?
1490 filename.startsWith(dataURIPrefix) :
1491 filename.indexOf(dataURIPrefix) === 0;
1492}
1493
1494
1495
1496
1497function integrateWasmJS() {
1498 // wasm.js has several methods for creating the compiled code module here:
1499 // * 'native-wasm' : use native WebAssembly support in the browser
1500 // * 'interpret-s-expr': load s-expression code from a .wast and interpret
1501 // * 'interpret-binary': load binary wasm and interpret
1502 // * 'interpret-asm2wasm': load asm.js code, translate to wasm, and interpret
1503 // * 'asmjs': no wasm, just load the asm.js code and use that (good for testing)
1504 // The method is set at compile time (BINARYEN_METHOD)
1505 // The method can be a comma-separated list, in which case, we will try the
1506 // options one by one. Some of them can fail gracefully, and then we can try
1507 // the next.
1508
1509 // inputs
1510
1511 var method = 'native-wasm';
1512
1513 var wasmTextFile = 'WasmVideoEncoderProd.wast';
1514 var wasmBinaryFile = 'WasmVideoEncoderProd.wasm';
1515 var asmjsCodeFile = 'WasmVideoEncoderProd.temp.asm.js';
1516
1517 if (typeof Module['locateFile'] === 'function') {
1518 if (!isDataURI(wasmTextFile)) {
1519 wasmTextFile = Module['locateFile'](wasmTextFile);
1520 }
1521 if (!isDataURI(wasmBinaryFile)) {
1522 wasmBinaryFile = Module['locateFile'](wasmBinaryFile);
1523 }
1524 if (!isDataURI(asmjsCodeFile)) {
1525 asmjsCodeFile = Module['locateFile'](asmjsCodeFile);
1526 }
1527 }
1528
1529 // utilities
1530
1531 var wasmPageSize = 64*1024;
1532
1533 var info = {
1534 'global': null,
1535 'env': null,
1536 'asm2wasm': { // special asm2wasm imports
1537 "f64-rem": function(x, y) {
1538 return x % y;
1539 },
1540 "debugger": function() {
1541 debugger;
1542 }
1543 },
1544 'parent': Module // Module inside wasm-js.cpp refers to wasm-js.cpp; this allows access to the outside program.
1545 };
1546
1547 var exports = null;
1548
1549
1550 function mergeMemory(newBuffer) {
1551 // The wasm instance creates its memory. But static init code might have written to
1552 // buffer already, including the mem init file, and we must copy it over in a proper merge.
1553 // TODO: avoid this copy, by avoiding such static init writes
1554 // TODO: in shorter term, just copy up to the last static init write
1555 var oldBuffer = Module['buffer'];
1556 if (newBuffer.byteLength < oldBuffer.byteLength) {
1557 Module['printErr']('the new buffer in mergeMemory is smaller than the previous one. in native wasm, we should grow memory here');
1558 }
1559 var oldView = new Int8Array(oldBuffer);
1560 var newView = new Int8Array(newBuffer);
1561
1562
1563 newView.set(oldView);
1564 updateGlobalBuffer(newBuffer);
1565 updateGlobalBufferViews();
1566 }
1567
1568 function fixImports(imports) {
1569 return imports;
1570 }
1571
1572 function getBinary() {
1573 try {
1574 if (Module['wasmBinary']) {
1575 return new Uint8Array(Module['wasmBinary']);
1576 }
1577 if (Module['readBinary']) {
1578 return Module['readBinary'](wasmBinaryFile);
1579 } else {
1580 throw "on the web, we need the wasm binary to be preloaded and set on Module['wasmBinary']. emcc.py will do that for you when generating HTML (but not JS)";
1581 }
1582 }
1583 catch (err) {
1584 abort(err);
1585 }
1586 }
1587
1588 function getBinaryPromise() {
1589 // if we don't have the binary yet, and have the Fetch api, use that
1590 // in some environments, like Electron's render process, Fetch api may be present, but have a different context than expected, let's only use it on the Web
1591 if (!Module['wasmBinary'] && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === 'function') {
1592 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
1593 if (!response['ok']) {
1594 throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
1595 }
1596 return response['arrayBuffer']();
1597 }).catch(function () {
1598 return getBinary();
1599 });
1600 }
1601 // Otherwise, getBinary should be able to get it synchronously
1602 return new Promise(function(resolve, reject) {
1603 resolve(getBinary());
1604 });
1605 }
1606
1607 // do-method functions
1608
1609
1610 function doNativeWasm(global, env, providedBuffer) {
1611 if (typeof WebAssembly !== 'object') {
1612 Module['printErr']('no native wasm support detected');
1613 return false;
1614 }
1615 // prepare memory import
1616 if (!(Module['wasmMemory'] instanceof WebAssembly.Memory)) {
1617 Module['printErr']('no native wasm Memory in use');
1618 return false;
1619 }
1620 env['memory'] = Module['wasmMemory'];
1621 // Load the wasm module and create an instance of using native support in the JS engine.
1622 info['global'] = {
1623 'NaN': NaN,
1624 'Infinity': Infinity
1625 };
1626 info['global.Math'] = Math;
1627 info['env'] = env;
1628 // handle a generated wasm instance, receiving its exports and
1629 // performing other necessary setup
1630 function receiveInstance(instance, module) {
1631 exports = instance.exports;
1632 if (exports.memory) mergeMemory(exports.memory);
1633 Module['asm'] = exports;
1634 Module["usingWasm"] = true;
1635 removeRunDependency('wasm-instantiate');
1636 }
1637 addRunDependency('wasm-instantiate');
1638
1639 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
1640 // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
1641 // to any other async startup actions they are performing.
1642 if (Module['instantiateWasm']) {
1643 try {
1644 return Module['instantiateWasm'](info, receiveInstance);
1645 } catch(e) {
1646 Module['printErr']('Module.instantiateWasm callback failed with error: ' + e);
1647 return false;
1648 }
1649 }
1650
1651 // Async compilation can be confusing when an error on the page overwrites Module
1652 // (for example, if the order of elements is wrong, and the one defining Module is
1653 // later), so we save Module and check it later.
1654 var trueModule = Module;
1655 function receiveInstantiatedSource(output) {
1656 // 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
1657 // receiveInstance() will swap in the exports (to Module.asm) so they can be called
1658 assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
1659 trueModule = null;
1660 receiveInstance(output['instance'], output['module']);
1661 }
1662 function instantiateArrayBuffer(receiver) {
1663 getBinaryPromise().then(function(binary) {
1664 return WebAssembly.instantiate(binary, info);
1665 }).then(receiver).catch(function(reason) {
1666 Module['printErr']('failed to asynchronously prepare wasm: ' + reason);
1667 abort(reason);
1668 });
1669 }
1670 // Prefer streaming instantiation if available.
1671 if (!Module['wasmBinary'] &&
1672 typeof WebAssembly.instantiateStreaming === 'function' &&
1673 !isDataURI(wasmBinaryFile) &&
1674 typeof fetch === 'function') {
1675 WebAssembly.instantiateStreaming(fetch(wasmBinaryFile, { credentials: 'same-origin' }), info)
1676 .then(receiveInstantiatedSource)
1677 .catch(function(reason) {
1678 // We expect the most common failure cause to be a bad MIME type for the binary,
1679 // in which case falling back to ArrayBuffer instantiation should work.
1680 Module['printErr']('wasm streaming compile failed: ' + reason);
1681 Module['printErr']('falling back to ArrayBuffer instantiation');
1682 instantiateArrayBuffer(receiveInstantiatedSource);
1683 });
1684 } else {
1685 instantiateArrayBuffer(receiveInstantiatedSource);
1686 }
1687 return {}; // no exports yet; we'll fill them in later
1688 }
1689
1690
1691 // We may have a preloaded value in Module.asm, save it
1692 Module['asmPreload'] = Module['asm'];
1693
1694 // Memory growth integration code
1695
1696 var asmjsReallocBuffer = Module['reallocBuffer'];
1697
1698 var wasmReallocBuffer = function(size) {
1699 var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; // In wasm, heap size must be a multiple of 64KB. In asm.js, they need to be multiples of 16MB.
1700 size = alignUp(size, PAGE_MULTIPLE); // round up to wasm page size
1701 var old = Module['buffer'];
1702 var oldSize = old.byteLength;
1703 if (Module["usingWasm"]) {
1704 // native wasm support
1705 try {
1706 var result = Module['wasmMemory'].grow((size - oldSize) / wasmPageSize); // .grow() takes a delta compared to the previous size
1707 if (result !== (-1 | 0)) {
1708 // success in native wasm memory growth, get the buffer from the memory
1709 return Module['buffer'] = Module['wasmMemory'].buffer;
1710 } else {
1711 return null;
1712 }
1713 } catch(e) {
1714 console.error('Module.reallocBuffer: Attempted to grow from ' + oldSize + ' bytes to ' + size + ' bytes, but got error: ' + e);
1715 return null;
1716 }
1717 }
1718 };
1719
1720 Module['reallocBuffer'] = function(size) {
1721 if (finalMethod === 'asmjs') {
1722 return asmjsReallocBuffer(size);
1723 } else {
1724 return wasmReallocBuffer(size);
1725 }
1726 };
1727
1728 // we may try more than one; this is the final one, that worked and we are using
1729 var finalMethod = '';
1730
1731 // Provide an "asm.js function" for the application, called to "link" the asm.js module. We instantiate
1732 // the wasm module at that time, and it receives imports and provides exports and so forth, the app
1733 // doesn't need to care that it is wasm or olyfilled wasm or asm.js.
1734
1735 Module['asm'] = function(global, env, providedBuffer) {
1736 env = fixImports(env);
1737
1738 // import table
1739 if (!env['table']) {
1740 var TABLE_SIZE = Module['wasmTableSize'];
1741 if (TABLE_SIZE === undefined) TABLE_SIZE = 1024; // works in binaryen interpreter at least
1742 var MAX_TABLE_SIZE = Module['wasmMaxTableSize'];
1743 if (typeof WebAssembly === 'object' && typeof WebAssembly.Table === 'function') {
1744 if (MAX_TABLE_SIZE !== undefined) {
1745 env['table'] = new WebAssembly.Table({ 'initial': TABLE_SIZE, 'maximum': MAX_TABLE_SIZE, 'element': 'anyfunc' });
1746 } else {
1747 env['table'] = new WebAssembly.Table({ 'initial': TABLE_SIZE, element: 'anyfunc' });
1748 }
1749 } else {
1750 env['table'] = new Array(TABLE_SIZE); // works in binaryen interpreter at least
1751 }
1752 Module['wasmTable'] = env['table'];
1753 }
1754
1755 if (!env['memoryBase']) {
1756 env['memoryBase'] = Module['STATIC_BASE']; // tell the memory segments where to place themselves
1757 }
1758 if (!env['tableBase']) {
1759 env['tableBase'] = 0; // table starts at 0 by default, in dynamic linking this will change
1760 }
1761
1762 // try the methods. each should return the exports if it succeeded
1763
1764 var exports;
1765 exports = doNativeWasm(global, env, providedBuffer);
1766
1767 if (!exports) abort('no binaryen method succeeded. consider enabling more options, like interpreting, if you want that: https://github.com/kripken/emscripten/wiki/WebAssembly#binaryen-methods');
1768
1769
1770 return exports;
1771 };
1772
1773 var methodHandler = Module['asm']; // note our method handler, as we may modify Module['asm'] later
1774}
1775
1776integrateWasmJS();
1777
1778// === Body ===
1779
1780var ASM_CONSTS = [];
1781
1782
1783
1784
1785STATIC_BASE = GLOBAL_BASE;
1786
1787STATICTOP = STATIC_BASE + 1405616;
1788/* global initializers */ __ATINIT__.push();
1789
1790
1791
1792
1793
1794
1795
1796var STATIC_BUMP = 1405616;
1797Module["STATIC_BASE"] = STATIC_BASE;
1798Module["STATIC_BUMP"] = STATIC_BUMP;
1799
1800/* no memory initializer */
1801var tempDoublePtr = STATICTOP; STATICTOP += 16;
1802
1803assert(tempDoublePtr % 8 == 0);
1804
1805function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1806
1807 HEAP8[tempDoublePtr] = HEAP8[ptr];
1808
1809 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1810
1811 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1812
1813 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1814
1815}
1816
1817function copyTempDouble(ptr) {
1818
1819 HEAP8[tempDoublePtr] = HEAP8[ptr];
1820
1821 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1822
1823 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1824
1825 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1826
1827 HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1828
1829 HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1830
1831 HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1832
1833 HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1834
1835}
1836
1837// {{PRE_LIBRARY}}
1838
1839
1840 function ___assert_fail(condition, filename, line, func) {
1841 abort('Assertion failed: ' + Pointer_stringify(condition) + ', at: ' + [filename ? Pointer_stringify(filename) : 'unknown filename', line, func ? Pointer_stringify(func) : 'unknown function']);
1842 }
1843
1844 function ___lock() {}
1845
1846
1847
1848
1849 var ERRNO_CODES={EPERM:1,ENOENT:2,ESRCH:3,EINTR:4,EIO:5,ENXIO:6,E2BIG:7,ENOEXEC:8,EBADF:9,ECHILD:10,EAGAIN:11,EWOULDBLOCK:11,ENOMEM:12,EACCES:13,EFAULT:14,ENOTBLK:15,EBUSY:16,EEXIST:17,EXDEV:18,ENODEV:19,ENOTDIR:20,EISDIR:21,EINVAL:22,ENFILE:23,EMFILE:24,ENOTTY:25,ETXTBSY:26,EFBIG:27,ENOSPC:28,ESPIPE:29,EROFS:30,EMLINK:31,EPIPE:32,EDOM:33,ERANGE:34,ENOMSG:42,EIDRM:43,ECHRNG:44,EL2NSYNC:45,EL3HLT:46,EL3RST:47,ELNRNG:48,EUNATCH:49,ENOCSI:50,EL2HLT:51,EDEADLK:35,ENOLCK:37,EBADE:52,EBADR:53,EXFULL:54,ENOANO:55,EBADRQC:56,EBADSLT:57,EDEADLOCK:35,EBFONT:59,ENOSTR:60,ENODATA:61,ETIME:62,ENOSR:63,ENONET:64,ENOPKG:65,EREMOTE:66,ENOLINK:67,EADV:68,ESRMNT:69,ECOMM:70,EPROTO:71,EMULTIHOP:72,EDOTDOT:73,EBADMSG:74,ENOTUNIQ:76,EBADFD:77,EREMCHG:78,ELIBACC:79,ELIBBAD:80,ELIBSCN:81,ELIBMAX:82,ELIBEXEC:83,ENOSYS:38,ENOTEMPTY:39,ENAMETOOLONG:36,ELOOP:40,EOPNOTSUPP:95,EPFNOSUPPORT:96,ECONNRESET:104,ENOBUFS:105,EAFNOSUPPORT:97,EPROTOTYPE:91,ENOTSOCK:88,ENOPROTOOPT:92,ESHUTDOWN:108,ECONNREFUSED:111,EADDRINUSE:98,ECONNABORTED:103,ENETUNREACH:101,ENETDOWN:100,ETIMEDOUT:110,EHOSTDOWN:112,EHOSTUNREACH:113,EINPROGRESS:115,EALREADY:114,EDESTADDRREQ:89,EMSGSIZE:90,EPROTONOSUPPORT:93,ESOCKTNOSUPPORT:94,EADDRNOTAVAIL:99,ENETRESET:102,EISCONN:106,ENOTCONN:107,ETOOMANYREFS:109,EUSERS:87,EDQUOT:122,ESTALE:116,ENOTSUP:95,ENOMEDIUM:123,EILSEQ:84,EOVERFLOW:75,ECANCELED:125,ENOTRECOVERABLE:131,EOWNERDEAD:130,ESTRPIPE:86};
1850
1851 var ERRNO_MESSAGES={0:"Success",1:"Not super-user",2:"No such file or directory",3:"No such process",4:"Interrupted system call",5:"I/O error",6:"No such device or address",7:"Arg list too long",8:"Exec format error",9:"Bad file number",10:"No children",11:"No more processes",12:"Not enough core",13:"Permission denied",14:"Bad address",15:"Block device required",16:"Mount device busy",17:"File exists",18:"Cross-device link",19:"No such device",20:"Not a directory",21:"Is a directory",22:"Invalid argument",23:"Too many open files in system",24:"Too many open files",25:"Not a typewriter",26:"Text file busy",27:"File too large",28:"No space left on device",29:"Illegal seek",30:"Read only file system",31:"Too many links",32:"Broken pipe",33:"Math arg out of domain of func",34:"Math result not representable",35:"File locking deadlock error",36:"File or path name too long",37:"No record locks available",38:"Function not implemented",39:"Directory not empty",40:"Too many symbolic links",42:"No message of desired type",43:"Identifier removed",44:"Channel number out of range",45:"Level 2 not synchronized",46:"Level 3 halted",47:"Level 3 reset",48:"Link number out of range",49:"Protocol driver not attached",50:"No CSI structure available",51:"Level 2 halted",52:"Invalid exchange",53:"Invalid request descriptor",54:"Exchange full",55:"No anode",56:"Invalid request code",57:"Invalid slot",59:"Bad font file fmt",60:"Device not a stream",61:"No data (for no delay io)",62:"Timer expired",63:"Out of streams resources",64:"Machine is not on the network",65:"Package not installed",66:"The object is remote",67:"The link has been severed",68:"Advertise error",69:"Srmount error",70:"Communication error on send",71:"Protocol error",72:"Multihop attempted",73:"Cross mount point (not really error)",74:"Trying to read unreadable message",75:"Value too large for defined data type",76:"Given log. name not unique",77:"f.d. invalid for this operation",78:"Remote address changed",79:"Can access a needed shared lib",80:"Accessing a corrupted shared lib",81:".lib section in a.out corrupted",82:"Attempting to link in too many libs",83:"Attempting to exec a shared library",84:"Illegal byte sequence",86:"Streams pipe error",87:"Too many users",88:"Socket operation on non-socket",89:"Destination address required",90:"Message too long",91:"Protocol wrong type for socket",92:"Protocol not available",93:"Unknown protocol",94:"Socket type not supported",95:"Not supported",96:"Protocol family not supported",97:"Address family not supported by protocol family",98:"Address already in use",99:"Address not available",100:"Network interface is not configured",101:"Network is unreachable",102:"Connection reset by network",103:"Connection aborted",104:"Connection reset by peer",105:"No buffer space available",106:"Socket is already connected",107:"Socket is not connected",108:"Can't send after socket shutdown",109:"Too many references",110:"Connection timed out",111:"Connection refused",112:"Host is down",113:"Host is unreachable",114:"Socket already connected",115:"Connection already in progress",116:"Stale file handle",122:"Quota exceeded",123:"No medium (in tape drive)",125:"Operation canceled",130:"Previous owner died",131:"State not recoverable"};
1852
1853 function ___setErrNo(value) {
1854 if (Module['___errno_location']) HEAP32[((Module['___errno_location']())>>2)]=value;
1855 else Module.printErr('failed to set errno from JS');
1856 return value;
1857 }
1858
1859 var PATH={splitPath:function (filename) {
1860 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
1861 return splitPathRe.exec(filename).slice(1);
1862 },normalizeArray:function (parts, allowAboveRoot) {
1863 // if the path tries to go above the root, `up` ends up > 0
1864 var up = 0;
1865 for (var i = parts.length - 1; i >= 0; i--) {
1866 var last = parts[i];
1867 if (last === '.') {
1868 parts.splice(i, 1);
1869 } else if (last === '..') {
1870 parts.splice(i, 1);
1871 up++;
1872 } else if (up) {
1873 parts.splice(i, 1);
1874 up--;
1875 }
1876 }
1877 // if the path is allowed to go above the root, restore leading ..s
1878 if (allowAboveRoot) {
1879 for (; up; up--) {
1880 parts.unshift('..');
1881 }
1882 }
1883 return parts;
1884 },normalize:function (path) {
1885 var isAbsolute = path.charAt(0) === '/',
1886 trailingSlash = path.substr(-1) === '/';
1887 // Normalize the path
1888 path = PATH.normalizeArray(path.split('/').filter(function(p) {
1889 return !!p;
1890 }), !isAbsolute).join('/');
1891 if (!path && !isAbsolute) {
1892 path = '.';
1893 }
1894 if (path && trailingSlash) {
1895 path += '/';
1896 }
1897 return (isAbsolute ? '/' : '') + path;
1898 },dirname:function (path) {
1899 var result = PATH.splitPath(path),
1900 root = result[0],
1901 dir = result[1];
1902 if (!root && !dir) {
1903 // No dirname whatsoever
1904 return '.';
1905 }
1906 if (dir) {
1907 // It has a dirname, strip trailing slash
1908 dir = dir.substr(0, dir.length - 1);
1909 }
1910 return root + dir;
1911 },basename:function (path) {
1912 // EMSCRIPTEN return '/'' for '/', not an empty string
1913 if (path === '/') return '/';
1914 var lastSlash = path.lastIndexOf('/');
1915 if (lastSlash === -1) return path;
1916 return path.substr(lastSlash+1);
1917 },extname:function (path) {
1918 return PATH.splitPath(path)[3];
1919 },join:function () {
1920 var paths = Array.prototype.slice.call(arguments, 0);
1921 return PATH.normalize(paths.join('/'));
1922 },join2:function (l, r) {
1923 return PATH.normalize(l + '/' + r);
1924 },resolve:function () {
1925 var resolvedPath = '',
1926 resolvedAbsolute = false;
1927 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1928 var path = (i >= 0) ? arguments[i] : FS.cwd();
1929 // Skip empty and invalid entries
1930 if (typeof path !== 'string') {
1931 throw new TypeError('Arguments to path.resolve must be strings');
1932 } else if (!path) {
1933 return ''; // an invalid portion invalidates the whole thing
1934 }
1935 resolvedPath = path + '/' + resolvedPath;
1936 resolvedAbsolute = path.charAt(0) === '/';
1937 }
1938 // At this point the path should be resolved to a full absolute path, but
1939 // handle relative paths to be safe (might happen when process.cwd() fails)
1940 resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
1941 return !!p;
1942 }), !resolvedAbsolute).join('/');
1943 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
1944 },relative:function (from, to) {
1945 from = PATH.resolve(from).substr(1);
1946 to = PATH.resolve(to).substr(1);
1947 function trim(arr) {
1948 var start = 0;
1949 for (; start < arr.length; start++) {
1950 if (arr[start] !== '') break;
1951 }
1952 var end = arr.length - 1;
1953 for (; end >= 0; end--) {
1954 if (arr[end] !== '') break;
1955 }
1956 if (start > end) return [];
1957 return arr.slice(start, end - start + 1);
1958 }
1959 var fromParts = trim(from.split('/'));
1960 var toParts = trim(to.split('/'));
1961 var length = Math.min(fromParts.length, toParts.length);
1962 var samePartsLength = length;
1963 for (var i = 0; i < length; i++) {
1964 if (fromParts[i] !== toParts[i]) {
1965 samePartsLength = i;
1966 break;
1967 }
1968 }
1969 var outputParts = [];
1970 for (var i = samePartsLength; i < fromParts.length; i++) {
1971 outputParts.push('..');
1972 }
1973 outputParts = outputParts.concat(toParts.slice(samePartsLength));
1974 return outputParts.join('/');
1975 }};
1976
1977 var TTY={ttys:[],init:function () {
1978 // https://github.com/kripken/emscripten/pull/1555
1979 // if (ENVIRONMENT_IS_NODE) {
1980 // // currently, FS.init does not distinguish if process.stdin is a file or TTY
1981 // // device, it always assumes it's a TTY device. because of this, we're forcing
1982 // // process.stdin to UTF8 encoding to at least make stdin reading compatible
1983 // // with text files until FS.init can be refactored.
1984 // process['stdin']['setEncoding']('utf8');
1985 // }
1986 },shutdown:function () {
1987 // https://github.com/kripken/emscripten/pull/1555
1988 // if (ENVIRONMENT_IS_NODE) {
1989 // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
1990 // // isaacs: because now it's reading from the stream, you've expressed interest in it, so that read() kicks off a _read() which creates a ReadReq operation
1991 // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
1992 // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
1993 // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
1994 // process['stdin']['pause']();
1995 // }
1996 },register:function (dev, ops) {
1997 TTY.ttys[dev] = { input: [], output: [], ops: ops };
1998 FS.registerDevice(dev, TTY.stream_ops);
1999 },stream_ops:{open:function (stream) {
2000 var tty = TTY.ttys[stream.node.rdev];
2001 if (!tty) {
2002 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
2003 }
2004 stream.tty = tty;
2005 stream.seekable = false;
2006 },close:function (stream) {
2007 // flush any pending line data
2008 stream.tty.ops.flush(stream.tty);
2009 },flush:function (stream) {
2010 stream.tty.ops.flush(stream.tty);
2011 },read:function (stream, buffer, offset, length, pos /* ignored */) {
2012 if (!stream.tty || !stream.tty.ops.get_char) {
2013 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
2014 }
2015 var bytesRead = 0;
2016 for (var i = 0; i < length; i++) {
2017 var result;
2018 try {
2019 result = stream.tty.ops.get_char(stream.tty);
2020 } catch (e) {
2021 throw new FS.ErrnoError(ERRNO_CODES.EIO);
2022 }
2023 if (result === undefined && bytesRead === 0) {
2024 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
2025 }
2026 if (result === null || result === undefined) break;
2027 bytesRead++;
2028 buffer[offset+i] = result;
2029 }
2030 if (bytesRead) {
2031 stream.node.timestamp = Date.now();
2032 }
2033 return bytesRead;
2034 },write:function (stream, buffer, offset, length, pos) {
2035 if (!stream.tty || !stream.tty.ops.put_char) {
2036 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
2037 }
2038 for (var i = 0; i < length; i++) {
2039 try {
2040 stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
2041 } catch (e) {
2042 throw new FS.ErrnoError(ERRNO_CODES.EIO);
2043 }
2044 }
2045 if (length) {
2046 stream.node.timestamp = Date.now();
2047 }
2048 return i;
2049 }},default_tty_ops:{get_char:function (tty) {
2050 if (!tty.input.length) {
2051 var result = null;
2052 if (ENVIRONMENT_IS_NODE) {
2053 // we will read data by chunks of BUFSIZE
2054 var BUFSIZE = 256;
2055 var buf = new Buffer(BUFSIZE);
2056 var bytesRead = 0;
2057
2058 var isPosixPlatform = (process.platform != 'win32'); // Node doesn't offer a direct check, so test by exclusion
2059
2060 var fd = process.stdin.fd;
2061 if (isPosixPlatform) {
2062 // Linux and Mac cannot use process.stdin.fd (which isn't set up as sync)
2063 var usingDevice = false;
2064 try {
2065 fd = fs.openSync('/dev/stdin', 'r');
2066 usingDevice = true;
2067 } catch (e) {}
2068 }
2069
2070 try {
2071 bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null);
2072 } catch(e) {
2073 // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
2074 // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
2075 if (e.toString().indexOf('EOF') != -1) bytesRead = 0;
2076 else throw e;
2077 }
2078
2079 if (usingDevice) { fs.closeSync(fd); }
2080 if (bytesRead > 0) {
2081 result = buf.slice(0, bytesRead).toString('utf-8');
2082 } else {
2083 result = null;
2084 }
2085
2086 } else if (typeof window != 'undefined' &&
2087 typeof window.prompt == 'function') {
2088 // Browser.
2089 result = window.prompt('Input: '); // returns null on cancel
2090 if (result !== null) {
2091 result += '\n';
2092 }
2093 } else if (typeof readline == 'function') {
2094 // Command line.
2095 result = readline();
2096 if (result !== null) {
2097 result += '\n';
2098 }
2099 }
2100 if (!result) {
2101 return null;
2102 }
2103 tty.input = intArrayFromString(result, true);
2104 }
2105 return tty.input.shift();
2106 },put_char:function (tty, val) {
2107 if (val === null || val === 10) {
2108 Module['print'](UTF8ArrayToString(tty.output, 0));
2109 tty.output = [];
2110 } else {
2111 if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
2112 }
2113 },flush:function (tty) {
2114 if (tty.output && tty.output.length > 0) {
2115 Module['print'](UTF8ArrayToString(tty.output, 0));
2116 tty.output = [];
2117 }
2118 }},default_tty1_ops:{put_char:function (tty, val) {
2119 if (val === null || val === 10) {
2120 Module['printErr'](UTF8ArrayToString(tty.output, 0));
2121 tty.output = [];
2122 } else {
2123 if (val != 0) tty.output.push(val);
2124 }
2125 },flush:function (tty) {
2126 if (tty.output && tty.output.length > 0) {
2127 Module['printErr'](UTF8ArrayToString(tty.output, 0));
2128 tty.output = [];
2129 }
2130 }}};
2131
2132 var MEMFS={ops_table:null,mount:function (mount) {
2133 return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
2134 },createNode:function (parent, name, mode, dev) {
2135 if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
2136 // no supported
2137 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2138 }
2139 if (!MEMFS.ops_table) {
2140 MEMFS.ops_table = {
2141 dir: {
2142 node: {
2143 getattr: MEMFS.node_ops.getattr,
2144 setattr: MEMFS.node_ops.setattr,
2145 lookup: MEMFS.node_ops.lookup,
2146 mknod: MEMFS.node_ops.mknod,
2147 rename: MEMFS.node_ops.rename,
2148 unlink: MEMFS.node_ops.unlink,
2149 rmdir: MEMFS.node_ops.rmdir,
2150 readdir: MEMFS.node_ops.readdir,
2151 symlink: MEMFS.node_ops.symlink
2152 },
2153 stream: {
2154 llseek: MEMFS.stream_ops.llseek
2155 }
2156 },
2157 file: {
2158 node: {
2159 getattr: MEMFS.node_ops.getattr,
2160 setattr: MEMFS.node_ops.setattr
2161 },
2162 stream: {
2163 llseek: MEMFS.stream_ops.llseek,
2164 read: MEMFS.stream_ops.read,
2165 write: MEMFS.stream_ops.write,
2166 allocate: MEMFS.stream_ops.allocate,
2167 mmap: MEMFS.stream_ops.mmap,
2168 msync: MEMFS.stream_ops.msync
2169 }
2170 },
2171 link: {
2172 node: {
2173 getattr: MEMFS.node_ops.getattr,
2174 setattr: MEMFS.node_ops.setattr,
2175 readlink: MEMFS.node_ops.readlink
2176 },
2177 stream: {}
2178 },
2179 chrdev: {
2180 node: {
2181 getattr: MEMFS.node_ops.getattr,
2182 setattr: MEMFS.node_ops.setattr
2183 },
2184 stream: FS.chrdev_stream_ops
2185 }
2186 };
2187 }
2188 var node = FS.createNode(parent, name, mode, dev);
2189 if (FS.isDir(node.mode)) {
2190 node.node_ops = MEMFS.ops_table.dir.node;
2191 node.stream_ops = MEMFS.ops_table.dir.stream;
2192 node.contents = {};
2193 } else if (FS.isFile(node.mode)) {
2194 node.node_ops = MEMFS.ops_table.file.node;
2195 node.stream_ops = MEMFS.ops_table.file.stream;
2196 node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
2197 // When the byte data of the file is populated, this will point to either a typed array, or a normal JS array. Typed arrays are preferred
2198 // for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
2199 // penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
2200 node.contents = null;
2201 } else if (FS.isLink(node.mode)) {
2202 node.node_ops = MEMFS.ops_table.link.node;
2203 node.stream_ops = MEMFS.ops_table.link.stream;
2204 } else if (FS.isChrdev(node.mode)) {
2205 node.node_ops = MEMFS.ops_table.chrdev.node;
2206 node.stream_ops = MEMFS.ops_table.chrdev.stream;
2207 }
2208 node.timestamp = Date.now();
2209 // add the new node to the parent
2210 if (parent) {
2211 parent.contents[name] = node;
2212 }
2213 return node;
2214 },getFileDataAsRegularArray:function (node) {
2215 if (node.contents && node.contents.subarray) {
2216 var arr = [];
2217 for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]);
2218 return arr; // Returns a copy of the original data.
2219 }
2220 return node.contents; // No-op, the file contents are already in a JS array. Return as-is.
2221 },getFileDataAsTypedArray:function (node) {
2222 if (!node.contents) return new Uint8Array;
2223 if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
2224 return new Uint8Array(node.contents);
2225 },expandFileStorage:function (node, newCapacity) {
2226 // If we are asked to expand the size of a file that already exists, revert to using a standard JS array to store the file
2227 // instead of a typed array. This makes resizing the array more flexible because we can just .push() elements at the back to
2228 // increase the size.
2229 if (node.contents && node.contents.subarray && newCapacity > node.contents.length) {
2230 node.contents = MEMFS.getFileDataAsRegularArray(node);
2231 node.usedBytes = node.contents.length; // We might be writing to a lazy-loaded file which had overridden this property, so force-reset it.
2232 }
2233
2234 if (!node.contents || node.contents.subarray) { // Keep using a typed array if creating a new storage, or if old one was a typed array as well.
2235 var prevCapacity = node.contents ? node.contents.length : 0;
2236 if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
2237 // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
2238 // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
2239 // avoid overshooting the allocation cap by a very large margin.
2240 var CAPACITY_DOUBLING_MAX = 1024 * 1024;
2241 newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) | 0);
2242 if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
2243 var oldContents = node.contents;
2244 node.contents = new Uint8Array(newCapacity); // Allocate new storage.
2245 if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
2246 return;
2247 }
2248 // Not using a typed array to back the file storage. Use a standard JS array instead.
2249 if (!node.contents && newCapacity > 0) node.contents = [];
2250 while (node.contents.length < newCapacity) node.contents.push(0);
2251 },resizeFileStorage:function (node, newSize) {
2252 if (node.usedBytes == newSize) return;
2253 if (newSize == 0) {
2254 node.contents = null; // Fully decommit when requesting a resize to zero.
2255 node.usedBytes = 0;
2256 return;
2257 }
2258 if (!node.contents || node.contents.subarray) { // Resize a typed array if that is being used as the backing store.
2259 var oldContents = node.contents;
2260 node.contents = new Uint8Array(new ArrayBuffer(newSize)); // Allocate new storage.
2261 if (oldContents) {
2262 node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
2263 }
2264 node.usedBytes = newSize;
2265 return;
2266 }
2267 // Backing with a JS array.
2268 if (!node.contents) node.contents = [];
2269 if (node.contents.length > newSize) node.contents.length = newSize;
2270 else while (node.contents.length < newSize) node.contents.push(0);
2271 node.usedBytes = newSize;
2272 },node_ops:{getattr:function (node) {
2273 var attr = {};
2274 // device numbers reuse inode numbers.
2275 attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
2276 attr.ino = node.id;
2277 attr.mode = node.mode;
2278 attr.nlink = 1;
2279 attr.uid = 0;
2280 attr.gid = 0;
2281 attr.rdev = node.rdev;
2282 if (FS.isDir(node.mode)) {
2283 attr.size = 4096;
2284 } else if (FS.isFile(node.mode)) {
2285 attr.size = node.usedBytes;
2286 } else if (FS.isLink(node.mode)) {
2287 attr.size = node.link.length;
2288 } else {
2289 attr.size = 0;
2290 }
2291 attr.atime = new Date(node.timestamp);
2292 attr.mtime = new Date(node.timestamp);
2293 attr.ctime = new Date(node.timestamp);
2294 // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
2295 // but this is not required by the standard.
2296 attr.blksize = 4096;
2297 attr.blocks = Math.ceil(attr.size / attr.blksize);
2298 return attr;
2299 },setattr:function (node, attr) {
2300 if (attr.mode !== undefined) {
2301 node.mode = attr.mode;
2302 }
2303 if (attr.timestamp !== undefined) {
2304 node.timestamp = attr.timestamp;
2305 }
2306 if (attr.size !== undefined) {
2307 MEMFS.resizeFileStorage(node, attr.size);
2308 }
2309 },lookup:function (parent, name) {
2310 throw FS.genericErrors[ERRNO_CODES.ENOENT];
2311 },mknod:function (parent, name, mode, dev) {
2312 return MEMFS.createNode(parent, name, mode, dev);
2313 },rename:function (old_node, new_dir, new_name) {
2314 // if we're overwriting a directory at new_name, make sure it's empty.
2315 if (FS.isDir(old_node.mode)) {
2316 var new_node;
2317 try {
2318 new_node = FS.lookupNode(new_dir, new_name);
2319 } catch (e) {
2320 }
2321 if (new_node) {
2322 for (var i in new_node.contents) {
2323 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
2324 }
2325 }
2326 }
2327 // do the internal rewiring
2328 delete old_node.parent.contents[old_node.name];
2329 old_node.name = new_name;
2330 new_dir.contents[new_name] = old_node;
2331 old_node.parent = new_dir;
2332 },unlink:function (parent, name) {
2333 delete parent.contents[name];
2334 },rmdir:function (parent, name) {
2335 var node = FS.lookupNode(parent, name);
2336 for (var i in node.contents) {
2337 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
2338 }
2339 delete parent.contents[name];
2340 },readdir:function (node) {
2341 var entries = ['.', '..']
2342 for (var key in node.contents) {
2343 if (!node.contents.hasOwnProperty(key)) {
2344 continue;
2345 }
2346 entries.push(key);
2347 }
2348 return entries;
2349 },symlink:function (parent, newname, oldpath) {
2350 var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
2351 node.link = oldpath;
2352 return node;
2353 },readlink:function (node) {
2354 if (!FS.isLink(node.mode)) {
2355 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2356 }
2357 return node.link;
2358 }},stream_ops:{read:function (stream, buffer, offset, length, position) {
2359 var contents = stream.node.contents;
2360 if (position >= stream.node.usedBytes) return 0;
2361 var size = Math.min(stream.node.usedBytes - position, length);
2362 assert(size >= 0);
2363 if (size > 8 && contents.subarray) { // non-trivial, and typed array
2364 buffer.set(contents.subarray(position, position + size), offset);
2365 } else {
2366 for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
2367 }
2368 return size;
2369 },write:function (stream, buffer, offset, length, position, canOwn) {
2370 if (!length) return 0;
2371 var node = stream.node;
2372 node.timestamp = Date.now();
2373
2374 if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
2375 if (canOwn) {
2376 assert(position === 0, 'canOwn must imply no weird position inside the file');
2377 node.contents = buffer.subarray(offset, offset + length);
2378 node.usedBytes = length;
2379 return length;
2380 } else if (node.usedBytes === 0 && position === 0) { // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
2381 node.contents = new Uint8Array(buffer.subarray(offset, offset + length));
2382 node.usedBytes = length;
2383 return length;
2384 } else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
2385 node.contents.set(buffer.subarray(offset, offset + length), position);
2386 return length;
2387 }
2388 }
2389
2390 // Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
2391 MEMFS.expandFileStorage(node, position+length);
2392 if (node.contents.subarray && buffer.subarray) node.contents.set(buffer.subarray(offset, offset + length), position); // Use typed array write if available.
2393 else {
2394 for (var i = 0; i < length; i++) {
2395 node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
2396 }
2397 }
2398 node.usedBytes = Math.max(node.usedBytes, position+length);
2399 return length;
2400 },llseek:function (stream, offset, whence) {
2401 var position = offset;
2402 if (whence === 1) { // SEEK_CUR.
2403 position += stream.position;
2404 } else if (whence === 2) { // SEEK_END.
2405 if (FS.isFile(stream.node.mode)) {
2406 position += stream.node.usedBytes;
2407 }
2408 }
2409 if (position < 0) {
2410 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2411 }
2412 return position;
2413 },allocate:function (stream, offset, length) {
2414 MEMFS.expandFileStorage(stream.node, offset + length);
2415 stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
2416 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
2417 if (!FS.isFile(stream.node.mode)) {
2418 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
2419 }
2420 var ptr;
2421 var allocated;
2422 var contents = stream.node.contents;
2423 // Only make a new copy when MAP_PRIVATE is specified.
2424 if ( !(flags & 2) &&
2425 (contents.buffer === buffer || contents.buffer === buffer.buffer) ) {
2426 // We can't emulate MAP_SHARED when the file is not backed by the buffer
2427 // we're mapping to (e.g. the HEAP buffer).
2428 allocated = false;
2429 ptr = contents.byteOffset;
2430 } else {
2431 // Try to avoid unnecessary slices.
2432 if (position > 0 || position + length < stream.node.usedBytes) {
2433 if (contents.subarray) {
2434 contents = contents.subarray(position, position + length);
2435 } else {
2436 contents = Array.prototype.slice.call(contents, position, position + length);
2437 }
2438 }
2439 allocated = true;
2440 ptr = _malloc(length);
2441 if (!ptr) {
2442 throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
2443 }
2444 buffer.set(contents, ptr);
2445 }
2446 return { ptr: ptr, allocated: allocated };
2447 },msync:function (stream, buffer, offset, length, mmapFlags) {
2448 if (!FS.isFile(stream.node.mode)) {
2449 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
2450 }
2451 if (mmapFlags & 2) {
2452 // MAP_PRIVATE calls need not to be synced back to underlying fs
2453 return 0;
2454 }
2455
2456 var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
2457 // should we check if bytesWritten and length are the same?
2458 return 0;
2459 }}};
2460
2461 var IDBFS={dbs:{},indexedDB:function () {
2462 if (typeof indexedDB !== 'undefined') return indexedDB;
2463 var ret = null;
2464 if (typeof window === 'object') ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
2465 assert(ret, 'IDBFS used, but indexedDB not supported');
2466 return ret;
2467 },DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function (mount) {
2468 // reuse all of the core MEMFS functionality
2469 return MEMFS.mount.apply(null, arguments);
2470 },syncfs:function (mount, populate, callback) {
2471 IDBFS.getLocalSet(mount, function(err, local) {
2472 if (err) return callback(err);
2473
2474 IDBFS.getRemoteSet(mount, function(err, remote) {
2475 if (err) return callback(err);
2476
2477 var src = populate ? remote : local;
2478 var dst = populate ? local : remote;
2479
2480 IDBFS.reconcile(src, dst, callback);
2481 });
2482 });
2483 },getDB:function (name, callback) {
2484 // check the cache first
2485 var db = IDBFS.dbs[name];
2486 if (db) {
2487 return callback(null, db);
2488 }
2489
2490 var req;
2491 try {
2492 req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
2493 } catch (e) {
2494 return callback(e);
2495 }
2496 if (!req) {
2497 return callback("Unable to connect to IndexedDB");
2498 }
2499 req.onupgradeneeded = function(e) {
2500 var db = e.target.result;
2501 var transaction = e.target.transaction;
2502
2503 var fileStore;
2504
2505 if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
2506 fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
2507 } else {
2508 fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
2509 }
2510
2511 if (!fileStore.indexNames.contains('timestamp')) {
2512 fileStore.createIndex('timestamp', 'timestamp', { unique: false });
2513 }
2514 };
2515 req.onsuccess = function() {
2516 db = req.result;
2517
2518 // add to the cache
2519 IDBFS.dbs[name] = db;
2520 callback(null, db);
2521 };
2522 req.onerror = function(e) {
2523 callback(this.error);
2524 e.preventDefault();
2525 };
2526 },getLocalSet:function (mount, callback) {
2527 var entries = {};
2528
2529 function isRealDir(p) {
2530 return p !== '.' && p !== '..';
2531 };
2532 function toAbsolute(root) {
2533 return function(p) {
2534 return PATH.join2(root, p);
2535 }
2536 };
2537
2538 var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
2539
2540 while (check.length) {
2541 var path = check.pop();
2542 var stat;
2543
2544 try {
2545 stat = FS.stat(path);
2546 } catch (e) {
2547 return callback(e);
2548 }
2549
2550 if (FS.isDir(stat.mode)) {
2551 check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
2552 }
2553
2554 entries[path] = { timestamp: stat.mtime };
2555 }
2556
2557 return callback(null, { type: 'local', entries: entries });
2558 },getRemoteSet:function (mount, callback) {
2559 var entries = {};
2560
2561 IDBFS.getDB(mount.mountpoint, function(err, db) {
2562 if (err) return callback(err);
2563
2564 try {
2565 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
2566 transaction.onerror = function(e) {
2567 callback(this.error);
2568 e.preventDefault();
2569 };
2570
2571 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2572 var index = store.index('timestamp');
2573
2574 index.openKeyCursor().onsuccess = function(event) {
2575 var cursor = event.target.result;
2576
2577 if (!cursor) {
2578 return callback(null, { type: 'remote', db: db, entries: entries });
2579 }
2580
2581 entries[cursor.primaryKey] = { timestamp: cursor.key };
2582
2583 cursor.continue();
2584 };
2585 } catch (e) {
2586 return callback(e);
2587 }
2588 });
2589 },loadLocalEntry:function (path, callback) {
2590 var stat, node;
2591
2592 try {
2593 var lookup = FS.lookupPath(path);
2594 node = lookup.node;
2595 stat = FS.stat(path);
2596 } catch (e) {
2597 return callback(e);
2598 }
2599
2600 if (FS.isDir(stat.mode)) {
2601 return callback(null, { timestamp: stat.mtime, mode: stat.mode });
2602 } else if (FS.isFile(stat.mode)) {
2603 // Performance consideration: storing a normal JavaScript array to a IndexedDB is much slower than storing a typed array.
2604 // Therefore always convert the file contents to a typed array first before writing the data to IndexedDB.
2605 node.contents = MEMFS.getFileDataAsTypedArray(node);
2606 return callback(null, { timestamp: stat.mtime, mode: stat.mode, contents: node.contents });
2607 } else {
2608 return callback(new Error('node type not supported'));
2609 }
2610 },storeLocalEntry:function (path, entry, callback) {
2611 try {
2612 if (FS.isDir(entry.mode)) {
2613 FS.mkdir(path, entry.mode);
2614 } else if (FS.isFile(entry.mode)) {
2615 FS.writeFile(path, entry.contents, { canOwn: true });
2616 } else {
2617 return callback(new Error('node type not supported'));
2618 }
2619
2620 FS.chmod(path, entry.mode);
2621 FS.utime(path, entry.timestamp, entry.timestamp);
2622 } catch (e) {
2623 return callback(e);
2624 }
2625
2626 callback(null);
2627 },removeLocalEntry:function (path, callback) {
2628 try {
2629 var lookup = FS.lookupPath(path);
2630 var stat = FS.stat(path);
2631
2632 if (FS.isDir(stat.mode)) {
2633 FS.rmdir(path);
2634 } else if (FS.isFile(stat.mode)) {
2635 FS.unlink(path);
2636 }
2637 } catch (e) {
2638 return callback(e);
2639 }
2640
2641 callback(null);
2642 },loadRemoteEntry:function (store, path, callback) {
2643 var req = store.get(path);
2644 req.onsuccess = function(event) { callback(null, event.target.result); };
2645 req.onerror = function(e) {
2646 callback(this.error);
2647 e.preventDefault();
2648 };
2649 },storeRemoteEntry:function (store, path, entry, callback) {
2650 var req = store.put(entry, path);
2651 req.onsuccess = function() { callback(null); };
2652 req.onerror = function(e) {
2653 callback(this.error);
2654 e.preventDefault();
2655 };
2656 },removeRemoteEntry:function (store, path, callback) {
2657 var req = store.delete(path);
2658 req.onsuccess = function() { callback(null); };
2659 req.onerror = function(e) {
2660 callback(this.error);
2661 e.preventDefault();
2662 };
2663 },reconcile:function (src, dst, callback) {
2664 var total = 0;
2665
2666 var create = [];
2667 Object.keys(src.entries).forEach(function (key) {
2668 var e = src.entries[key];
2669 var e2 = dst.entries[key];
2670 if (!e2 || e.timestamp > e2.timestamp) {
2671 create.push(key);
2672 total++;
2673 }
2674 });
2675
2676 var remove = [];
2677 Object.keys(dst.entries).forEach(function (key) {
2678 var e = dst.entries[key];
2679 var e2 = src.entries[key];
2680 if (!e2) {
2681 remove.push(key);
2682 total++;
2683 }
2684 });
2685
2686 if (!total) {
2687 return callback(null);
2688 }
2689
2690 var errored = false;
2691 var completed = 0;
2692 var db = src.type === 'remote' ? src.db : dst.db;
2693 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
2694 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2695
2696 function done(err) {
2697 if (err) {
2698 if (!done.errored) {
2699 done.errored = true;
2700 return callback(err);
2701 }
2702 return;
2703 }
2704 if (++completed >= total) {
2705 return callback(null);
2706 }
2707 };
2708
2709 transaction.onerror = function(e) {
2710 done(this.error);
2711 e.preventDefault();
2712 };
2713
2714 // sort paths in ascending order so directory entries are created
2715 // before the files inside them
2716 create.sort().forEach(function (path) {
2717 if (dst.type === 'local') {
2718 IDBFS.loadRemoteEntry(store, path, function (err, entry) {
2719 if (err) return done(err);
2720 IDBFS.storeLocalEntry(path, entry, done);
2721 });
2722 } else {
2723 IDBFS.loadLocalEntry(path, function (err, entry) {
2724 if (err) return done(err);
2725 IDBFS.storeRemoteEntry(store, path, entry, done);
2726 });
2727 }
2728 });
2729
2730 // sort paths in descending order so files are deleted before their
2731 // parent directories
2732 remove.sort().reverse().forEach(function(path) {
2733 if (dst.type === 'local') {
2734 IDBFS.removeLocalEntry(path, done);
2735 } else {
2736 IDBFS.removeRemoteEntry(store, path, done);
2737 }
2738 });
2739 }};
2740
2741 var NODEFS={isWindows:false,staticInit:function () {
2742 NODEFS.isWindows = !!process.platform.match(/^win/);
2743 var flags = process["binding"]("constants");
2744 // Node.js 4 compatibility: it has no namespaces for constants
2745 if (flags["fs"]) {
2746 flags = flags["fs"];
2747 }
2748 NODEFS.flagsForNodeMap = {
2749 "1024": flags["O_APPEND"],
2750 "64": flags["O_CREAT"],
2751 "128": flags["O_EXCL"],
2752 "0": flags["O_RDONLY"],
2753 "2": flags["O_RDWR"],
2754 "4096": flags["O_SYNC"],
2755 "512": flags["O_TRUNC"],
2756 "1": flags["O_WRONLY"]
2757 };
2758 },bufferFrom:function (arrayBuffer) {
2759 // Node.js < 4.5 compatibility: Buffer.from does not support ArrayBuffer
2760 // Buffer.from before 4.5 was just a method inherited from Uint8Array
2761 // Buffer.alloc has been added with Buffer.from together, so check it instead
2762 return Buffer.alloc ? Buffer.from(arrayBuffer) : new Buffer(arrayBuffer);
2763 },mount:function (mount) {
2764 assert(ENVIRONMENT_IS_NODE);
2765 return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
2766 },createNode:function (parent, name, mode, dev) {
2767 if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
2768 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2769 }
2770 var node = FS.createNode(parent, name, mode);
2771 node.node_ops = NODEFS.node_ops;
2772 node.stream_ops = NODEFS.stream_ops;
2773 return node;
2774 },getMode:function (path) {
2775 var stat;
2776 try {
2777 stat = fs.lstatSync(path);
2778 if (NODEFS.isWindows) {
2779 // Node.js on Windows never represents permission bit 'x', so
2780 // propagate read bits to execute bits
2781 stat.mode = stat.mode | ((stat.mode & 292) >> 2);
2782 }
2783 } catch (e) {
2784 if (!e.code) throw e;
2785 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2786 }
2787 return stat.mode;
2788 },realPath:function (node) {
2789 var parts = [];
2790 while (node.parent !== node) {
2791 parts.push(node.name);
2792 node = node.parent;
2793 }
2794 parts.push(node.mount.opts.root);
2795 parts.reverse();
2796 return PATH.join.apply(null, parts);
2797 },flagsForNode:function (flags) {
2798 flags &= ~0x200000 /*O_PATH*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
2799 flags &= ~0x800 /*O_NONBLOCK*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
2800 flags &= ~0x8000 /*O_LARGEFILE*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
2801 flags &= ~0x80000 /*O_CLOEXEC*/; // Some applications may pass it; it makes no sense for a single process.
2802 var newFlags = 0;
2803 for (var k in NODEFS.flagsForNodeMap) {
2804 if (flags & k) {
2805 newFlags |= NODEFS.flagsForNodeMap[k];
2806 flags ^= k;
2807 }
2808 }
2809
2810 if (!flags) {
2811 return newFlags;
2812 } else {
2813 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2814 }
2815 },node_ops:{getattr:function (node) {
2816 var path = NODEFS.realPath(node);
2817 var stat;
2818 try {
2819 stat = fs.lstatSync(path);
2820 } catch (e) {
2821 if (!e.code) throw e;
2822 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2823 }
2824 // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
2825 // See http://support.microsoft.com/kb/140365
2826 if (NODEFS.isWindows && !stat.blksize) {
2827 stat.blksize = 4096;
2828 }
2829 if (NODEFS.isWindows && !stat.blocks) {
2830 stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
2831 }
2832 return {
2833 dev: stat.dev,
2834 ino: stat.ino,
2835 mode: stat.mode,
2836 nlink: stat.nlink,
2837 uid: stat.uid,
2838 gid: stat.gid,
2839 rdev: stat.rdev,
2840 size: stat.size,
2841 atime: stat.atime,
2842 mtime: stat.mtime,
2843 ctime: stat.ctime,
2844 blksize: stat.blksize,
2845 blocks: stat.blocks
2846 };
2847 },setattr:function (node, attr) {
2848 var path = NODEFS.realPath(node);
2849 try {
2850 if (attr.mode !== undefined) {
2851 fs.chmodSync(path, attr.mode);
2852 // update the common node structure mode as well
2853 node.mode = attr.mode;
2854 }
2855 if (attr.timestamp !== undefined) {
2856 var date = new Date(attr.timestamp);
2857 fs.utimesSync(path, date, date);
2858 }
2859 if (attr.size !== undefined) {
2860 fs.truncateSync(path, attr.size);
2861 }
2862 } catch (e) {
2863 if (!e.code) throw e;
2864 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2865 }
2866 },lookup:function (parent, name) {
2867 var path = PATH.join2(NODEFS.realPath(parent), name);
2868 var mode = NODEFS.getMode(path);
2869 return NODEFS.createNode(parent, name, mode);
2870 },mknod:function (parent, name, mode, dev) {
2871 var node = NODEFS.createNode(parent, name, mode, dev);
2872 // create the backing node for this in the fs root as well
2873 var path = NODEFS.realPath(node);
2874 try {
2875 if (FS.isDir(node.mode)) {
2876 fs.mkdirSync(path, node.mode);
2877 } else {
2878 fs.writeFileSync(path, '', { mode: node.mode });
2879 }
2880 } catch (e) {
2881 if (!e.code) throw e;
2882 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2883 }
2884 return node;
2885 },rename:function (oldNode, newDir, newName) {
2886 var oldPath = NODEFS.realPath(oldNode);
2887 var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
2888 try {
2889 fs.renameSync(oldPath, newPath);
2890 } catch (e) {
2891 if (!e.code) throw e;
2892 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2893 }
2894 },unlink:function (parent, name) {
2895 var path = PATH.join2(NODEFS.realPath(parent), name);
2896 try {
2897 fs.unlinkSync(path);
2898 } catch (e) {
2899 if (!e.code) throw e;
2900 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2901 }
2902 },rmdir:function (parent, name) {
2903 var path = PATH.join2(NODEFS.realPath(parent), name);
2904 try {
2905 fs.rmdirSync(path);
2906 } catch (e) {
2907 if (!e.code) throw e;
2908 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2909 }
2910 },readdir:function (node) {
2911 var path = NODEFS.realPath(node);
2912 try {
2913 return fs.readdirSync(path);
2914 } catch (e) {
2915 if (!e.code) throw e;
2916 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2917 }
2918 },symlink:function (parent, newName, oldPath) {
2919 var newPath = PATH.join2(NODEFS.realPath(parent), newName);
2920 try {
2921 fs.symlinkSync(oldPath, newPath);
2922 } catch (e) {
2923 if (!e.code) throw e;
2924 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2925 }
2926 },readlink:function (node) {
2927 var path = NODEFS.realPath(node);
2928 try {
2929 path = fs.readlinkSync(path);
2930 path = NODEJS_PATH.relative(NODEJS_PATH.resolve(node.mount.opts.root), path);
2931 return path;
2932 } catch (e) {
2933 if (!e.code) throw e;
2934 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2935 }
2936 }},stream_ops:{open:function (stream) {
2937 var path = NODEFS.realPath(stream.node);
2938 try {
2939 if (FS.isFile(stream.node.mode)) {
2940 stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags));
2941 }
2942 } catch (e) {
2943 if (!e.code) throw e;
2944 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2945 }
2946 },close:function (stream) {
2947 try {
2948 if (FS.isFile(stream.node.mode) && stream.nfd) {
2949 fs.closeSync(stream.nfd);
2950 }
2951 } catch (e) {
2952 if (!e.code) throw e;
2953 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2954 }
2955 },read:function (stream, buffer, offset, length, position) {
2956 // Node.js < 6 compatibility: node errors on 0 length reads
2957 if (length === 0) return 0;
2958 try {
2959 return fs.readSync(stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position);
2960 } catch (e) {
2961 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2962 }
2963 },write:function (stream, buffer, offset, length, position) {
2964 try {
2965 return fs.writeSync(stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position);
2966 } catch (e) {
2967 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2968 }
2969 },llseek:function (stream, offset, whence) {
2970 var position = offset;
2971 if (whence === 1) { // SEEK_CUR.
2972 position += stream.position;
2973 } else if (whence === 2) { // SEEK_END.
2974 if (FS.isFile(stream.node.mode)) {
2975 try {
2976 var stat = fs.fstatSync(stream.nfd);
2977 position += stat.size;
2978 } catch (e) {
2979 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2980 }
2981 }
2982 }
2983
2984 if (position < 0) {
2985 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2986 }
2987
2988 return position;
2989 }}};
2990
2991 var WORKERFS={DIR_MODE:16895,FILE_MODE:33279,reader:null,mount:function (mount) {
2992 assert(ENVIRONMENT_IS_WORKER);
2993 if (!WORKERFS.reader) WORKERFS.reader = new FileReaderSync();
2994 var root = WORKERFS.createNode(null, '/', WORKERFS.DIR_MODE, 0);
2995 var createdParents = {};
2996 function ensureParent(path) {
2997 // return the parent node, creating subdirs as necessary
2998 var parts = path.split('/');
2999 var parent = root;
3000 for (var i = 0; i < parts.length-1; i++) {
3001 var curr = parts.slice(0, i+1).join('/');
3002 // Issue 4254: Using curr as a node name will prevent the node
3003 // from being found in FS.nameTable when FS.open is called on
3004 // a path which holds a child of this node,
3005 // given that all FS functions assume node names
3006 // are just their corresponding parts within their given path,
3007 // rather than incremental aggregates which include their parent's
3008 // directories.
3009 if (!createdParents[curr]) {
3010 createdParents[curr] = WORKERFS.createNode(parent, parts[i], WORKERFS.DIR_MODE, 0);
3011 }
3012 parent = createdParents[curr];
3013 }
3014 return parent;
3015 }
3016 function base(path) {
3017 var parts = path.split('/');
3018 return parts[parts.length-1];
3019 }
3020 // We also accept FileList here, by using Array.prototype
3021 Array.prototype.forEach.call(mount.opts["files"] || [], function(file) {
3022 WORKERFS.createNode(ensureParent(file.name), base(file.name), WORKERFS.FILE_MODE, 0, file, file.lastModifiedDate);
3023 });
3024 (mount.opts["blobs"] || []).forEach(function(obj) {
3025 WORKERFS.createNode(ensureParent(obj["name"]), base(obj["name"]), WORKERFS.FILE_MODE, 0, obj["data"]);
3026 });
3027 (mount.opts["packages"] || []).forEach(function(pack) {
3028 pack['metadata'].files.forEach(function(file) {
3029 var name = file.filename.substr(1); // remove initial slash
3030 WORKERFS.createNode(ensureParent(name), base(name), WORKERFS.FILE_MODE, 0, pack['blob'].slice(file.start, file.end));
3031 });
3032 });
3033 return root;
3034 },createNode:function (parent, name, mode, dev, contents, mtime) {
3035 var node = FS.createNode(parent, name, mode);
3036 node.mode = mode;
3037 node.node_ops = WORKERFS.node_ops;
3038 node.stream_ops = WORKERFS.stream_ops;
3039 node.timestamp = (mtime || new Date).getTime();
3040 assert(WORKERFS.FILE_MODE !== WORKERFS.DIR_MODE);
3041 if (mode === WORKERFS.FILE_MODE) {
3042 node.size = contents.size;
3043 node.contents = contents;
3044 } else {
3045 node.size = 4096;
3046 node.contents = {};
3047 }
3048 if (parent) {
3049 parent.contents[name] = node;
3050 }
3051 return node;
3052 },node_ops:{getattr:function (node) {
3053 return {
3054 dev: 1,
3055 ino: undefined,
3056 mode: node.mode,
3057 nlink: 1,
3058 uid: 0,
3059 gid: 0,
3060 rdev: undefined,
3061 size: node.size,
3062 atime: new Date(node.timestamp),
3063 mtime: new Date(node.timestamp),
3064 ctime: new Date(node.timestamp),
3065 blksize: 4096,
3066 blocks: Math.ceil(node.size / 4096),
3067 };
3068 },setattr:function (node, attr) {
3069 if (attr.mode !== undefined) {
3070 node.mode = attr.mode;
3071 }
3072 if (attr.timestamp !== undefined) {
3073 node.timestamp = attr.timestamp;
3074 }
3075 },lookup:function (parent, name) {
3076 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3077 },mknod:function (parent, name, mode, dev) {
3078 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3079 },rename:function (oldNode, newDir, newName) {
3080 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3081 },unlink:function (parent, name) {
3082 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3083 },rmdir:function (parent, name) {
3084 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3085 },readdir:function (node) {
3086 var entries = ['.', '..'];
3087 for (var key in node.contents) {
3088 if (!node.contents.hasOwnProperty(key)) {
3089 continue;
3090 }
3091 entries.push(key);
3092 }
3093 return entries;
3094 },symlink:function (parent, newName, oldPath) {
3095 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3096 },readlink:function (node) {
3097 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3098 }},stream_ops:{read:function (stream, buffer, offset, length, position) {
3099 if (position >= stream.node.size) return 0;
3100 var chunk = stream.node.contents.slice(position, position + length);
3101 var ab = WORKERFS.reader.readAsArrayBuffer(chunk);
3102 buffer.set(new Uint8Array(ab), offset);
3103 return chunk.size;
3104 },write:function (stream, buffer, offset, length, position) {
3105 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3106 },llseek:function (stream, offset, whence) {
3107 var position = offset;
3108 if (whence === 1) { // SEEK_CUR.
3109 position += stream.position;
3110 } else if (whence === 2) { // SEEK_END.
3111 if (FS.isFile(stream.node.mode)) {
3112 position += stream.node.size;
3113 }
3114 }
3115 if (position < 0) {
3116 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3117 }
3118 return position;
3119 }}};
3120
3121 var _stdin=STATICTOP; STATICTOP += 16;;
3122
3123 var _stdout=STATICTOP; STATICTOP += 16;;
3124
3125 var _stderr=STATICTOP; STATICTOP += 16;;var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,trackingDelegate:{},tracking:{openFlags:{READ:1,WRITE:2}},ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,handleFSError:function (e) {
3126 if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
3127 return ___setErrNo(e.errno);
3128 },lookupPath:function (path, opts) {
3129 path = PATH.resolve(FS.cwd(), path);
3130 opts = opts || {};
3131
3132 if (!path) return { path: '', node: null };
3133
3134 var defaults = {
3135 follow_mount: true,
3136 recurse_count: 0
3137 };
3138 for (var key in defaults) {
3139 if (opts[key] === undefined) {
3140 opts[key] = defaults[key];
3141 }
3142 }
3143
3144 if (opts.recurse_count > 8) { // max recursive lookup of 8
3145 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
3146 }
3147
3148 // split the path
3149 var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
3150 return !!p;
3151 }), false);
3152
3153 // start at the root
3154 var current = FS.root;
3155 var current_path = '/';
3156
3157 for (var i = 0; i < parts.length; i++) {
3158 var islast = (i === parts.length-1);
3159 if (islast && opts.parent) {
3160 // stop resolving
3161 break;
3162 }
3163
3164 current = FS.lookupNode(current, parts[i]);
3165 current_path = PATH.join2(current_path, parts[i]);
3166
3167 // jump to the mount's root node if this is a mountpoint
3168 if (FS.isMountpoint(current)) {
3169 if (!islast || (islast && opts.follow_mount)) {
3170 current = current.mounted.root;
3171 }
3172 }
3173
3174 // by default, lookupPath will not follow a symlink if it is the final path component.
3175 // setting opts.follow = true will override this behavior.
3176 if (!islast || opts.follow) {
3177 var count = 0;
3178 while (FS.isLink(current.mode)) {
3179 var link = FS.readlink(current_path);
3180 current_path = PATH.resolve(PATH.dirname(current_path), link);
3181
3182 var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
3183 current = lookup.node;
3184
3185 if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
3186 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
3187 }
3188 }
3189 }
3190 }
3191
3192 return { path: current_path, node: current };
3193 },getPath:function (node) {
3194 var path;
3195 while (true) {
3196 if (FS.isRoot(node)) {
3197 var mount = node.mount.mountpoint;
3198 if (!path) return mount;
3199 return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
3200 }
3201 path = path ? node.name + '/' + path : node.name;
3202 node = node.parent;
3203 }
3204 },hashName:function (parentid, name) {
3205 var hash = 0;
3206
3207
3208 for (var i = 0; i < name.length; i++) {
3209 hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
3210 }
3211 return ((parentid + hash) >>> 0) % FS.nameTable.length;
3212 },hashAddNode:function (node) {
3213 var hash = FS.hashName(node.parent.id, node.name);
3214 node.name_next = FS.nameTable[hash];
3215 FS.nameTable[hash] = node;
3216 },hashRemoveNode:function (node) {
3217 var hash = FS.hashName(node.parent.id, node.name);
3218 if (FS.nameTable[hash] === node) {
3219 FS.nameTable[hash] = node.name_next;
3220 } else {
3221 var current = FS.nameTable[hash];
3222 while (current) {
3223 if (current.name_next === node) {
3224 current.name_next = node.name_next;
3225 break;
3226 }
3227 current = current.name_next;
3228 }
3229 }
3230 },lookupNode:function (parent, name) {
3231 var err = FS.mayLookup(parent);
3232 if (err) {
3233 throw new FS.ErrnoError(err, parent);
3234 }
3235 var hash = FS.hashName(parent.id, name);
3236 for (var node = FS.nameTable[hash]; node; node = node.name_next) {
3237 var nodeName = node.name;
3238 if (node.parent.id === parent.id && nodeName === name) {
3239 return node;
3240 }
3241 }
3242 // if we failed to find it in the cache, call into the VFS
3243 return FS.lookup(parent, name);
3244 },createNode:function (parent, name, mode, rdev) {
3245 if (!FS.FSNode) {
3246 FS.FSNode = function(parent, name, mode, rdev) {
3247 if (!parent) {
3248 parent = this; // root node sets parent to itself
3249 }
3250 this.parent = parent;
3251 this.mount = parent.mount;
3252 this.mounted = null;
3253 this.id = FS.nextInode++;
3254 this.name = name;
3255 this.mode = mode;
3256 this.node_ops = {};
3257 this.stream_ops = {};
3258 this.rdev = rdev;
3259 };
3260
3261 FS.FSNode.prototype = {};
3262
3263 // compatibility
3264 var readMode = 292 | 73;
3265 var writeMode = 146;
3266
3267 // NOTE we must use Object.defineProperties instead of individual calls to
3268 // Object.defineProperty in order to make closure compiler happy
3269 Object.defineProperties(FS.FSNode.prototype, {
3270 read: {
3271 get: function() { return (this.mode & readMode) === readMode; },
3272 set: function(val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
3273 },
3274 write: {
3275 get: function() { return (this.mode & writeMode) === writeMode; },
3276 set: function(val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
3277 },
3278 isFolder: {
3279 get: function() { return FS.isDir(this.mode); }
3280 },
3281 isDevice: {
3282 get: function() { return FS.isChrdev(this.mode); }
3283 }
3284 });
3285 }
3286
3287 var node = new FS.FSNode(parent, name, mode, rdev);
3288
3289 FS.hashAddNode(node);
3290
3291 return node;
3292 },destroyNode:function (node) {
3293 FS.hashRemoveNode(node);
3294 },isRoot:function (node) {
3295 return node === node.parent;
3296 },isMountpoint:function (node) {
3297 return !!node.mounted;
3298 },isFile:function (mode) {
3299 return (mode & 61440) === 32768;
3300 },isDir:function (mode) {
3301 return (mode & 61440) === 16384;
3302 },isLink:function (mode) {
3303 return (mode & 61440) === 40960;
3304 },isChrdev:function (mode) {
3305 return (mode & 61440) === 8192;
3306 },isBlkdev:function (mode) {
3307 return (mode & 61440) === 24576;
3308 },isFIFO:function (mode) {
3309 return (mode & 61440) === 4096;
3310 },isSocket:function (mode) {
3311 return (mode & 49152) === 49152;
3312 },flagModes:{"r":0,"rs":1052672,"r+":2,"w":577,"wx":705,"xw":705,"w+":578,"wx+":706,"xw+":706,"a":1089,"ax":1217,"xa":1217,"a+":1090,"ax+":1218,"xa+":1218},modeStringToFlags:function (str) {
3313 var flags = FS.flagModes[str];
3314 if (typeof flags === 'undefined') {
3315 throw new Error('Unknown file open mode: ' + str);
3316 }
3317 return flags;
3318 },flagsToPermissionString:function (flag) {
3319 var perms = ['r', 'w', 'rw'][flag & 3];
3320 if ((flag & 512)) {
3321 perms += 'w';
3322 }
3323 return perms;
3324 },nodePermissions:function (node, perms) {
3325 if (FS.ignorePermissions) {
3326 return 0;
3327 }
3328 // return 0 if any user, group or owner bits are set.
3329 if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
3330 return ERRNO_CODES.EACCES;
3331 } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
3332 return ERRNO_CODES.EACCES;
3333 } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
3334 return ERRNO_CODES.EACCES;
3335 }
3336 return 0;
3337 },mayLookup:function (dir) {
3338 var err = FS.nodePermissions(dir, 'x');
3339 if (err) return err;
3340 if (!dir.node_ops.lookup) return ERRNO_CODES.EACCES;
3341 return 0;
3342 },mayCreate:function (dir, name) {
3343 try {
3344 var node = FS.lookupNode(dir, name);
3345 return ERRNO_CODES.EEXIST;
3346 } catch (e) {
3347 }
3348 return FS.nodePermissions(dir, 'wx');
3349 },mayDelete:function (dir, name, isdir) {
3350 var node;
3351 try {
3352 node = FS.lookupNode(dir, name);
3353 } catch (e) {
3354 return e.errno;
3355 }
3356 var err = FS.nodePermissions(dir, 'wx');
3357 if (err) {
3358 return err;
3359 }
3360 if (isdir) {
3361 if (!FS.isDir(node.mode)) {
3362 return ERRNO_CODES.ENOTDIR;
3363 }
3364 if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
3365 return ERRNO_CODES.EBUSY;
3366 }
3367 } else {
3368 if (FS.isDir(node.mode)) {
3369 return ERRNO_CODES.EISDIR;
3370 }
3371 }
3372 return 0;
3373 },mayOpen:function (node, flags) {
3374 if (!node) {
3375 return ERRNO_CODES.ENOENT;
3376 }
3377 if (FS.isLink(node.mode)) {
3378 return ERRNO_CODES.ELOOP;
3379 } else if (FS.isDir(node.mode)) {
3380 if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
3381 (flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
3382 return ERRNO_CODES.EISDIR;
3383 }
3384 }
3385 return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
3386 },MAX_OPEN_FDS:4096,nextfd:function (fd_start, fd_end) {
3387 fd_start = fd_start || 0;
3388 fd_end = fd_end || FS.MAX_OPEN_FDS;
3389 for (var fd = fd_start; fd <= fd_end; fd++) {
3390 if (!FS.streams[fd]) {
3391 return fd;
3392 }
3393 }
3394 throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
3395 },getStream:function (fd) {
3396 return FS.streams[fd];
3397 },createStream:function (stream, fd_start, fd_end) {
3398 if (!FS.FSStream) {
3399 FS.FSStream = function(){};
3400 FS.FSStream.prototype = {};
3401 // compatibility
3402 Object.defineProperties(FS.FSStream.prototype, {
3403 object: {
3404 get: function() { return this.node; },
3405 set: function(val) { this.node = val; }
3406 },
3407 isRead: {
3408 get: function() { return (this.flags & 2097155) !== 1; }
3409 },
3410 isWrite: {
3411 get: function() { return (this.flags & 2097155) !== 0; }
3412 },
3413 isAppend: {
3414 get: function() { return (this.flags & 1024); }
3415 }
3416 });
3417 }
3418 // clone it, so we can return an instance of FSStream
3419 var newStream = new FS.FSStream();
3420 for (var p in stream) {
3421 newStream[p] = stream[p];
3422 }
3423 stream = newStream;
3424 var fd = FS.nextfd(fd_start, fd_end);
3425 stream.fd = fd;
3426 FS.streams[fd] = stream;
3427 return stream;
3428 },closeStream:function (fd) {
3429 FS.streams[fd] = null;
3430 },chrdev_stream_ops:{open:function (stream) {
3431 var device = FS.getDevice(stream.node.rdev);
3432 // override node's stream ops with the device's
3433 stream.stream_ops = device.stream_ops;
3434 // forward the open call
3435 if (stream.stream_ops.open) {
3436 stream.stream_ops.open(stream);
3437 }
3438 },llseek:function () {
3439 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3440 }},major:function (dev) {
3441 return ((dev) >> 8);
3442 },minor:function (dev) {
3443 return ((dev) & 0xff);
3444 },makedev:function (ma, mi) {
3445 return ((ma) << 8 | (mi));
3446 },registerDevice:function (dev, ops) {
3447 FS.devices[dev] = { stream_ops: ops };
3448 },getDevice:function (dev) {
3449 return FS.devices[dev];
3450 },getMounts:function (mount) {
3451 var mounts = [];
3452 var check = [mount];
3453
3454 while (check.length) {
3455 var m = check.pop();
3456
3457 mounts.push(m);
3458
3459 check.push.apply(check, m.mounts);
3460 }
3461
3462 return mounts;
3463 },syncfs:function (populate, callback) {
3464 if (typeof(populate) === 'function') {
3465 callback = populate;
3466 populate = false;
3467 }
3468
3469 FS.syncFSRequests++;
3470
3471 if (FS.syncFSRequests > 1) {
3472 console.log('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
3473 }
3474
3475 var mounts = FS.getMounts(FS.root.mount);
3476 var completed = 0;
3477
3478 function doCallback(err) {
3479 assert(FS.syncFSRequests > 0);
3480 FS.syncFSRequests--;
3481 return callback(err);
3482 }
3483
3484 function done(err) {
3485 if (err) {
3486 if (!done.errored) {
3487 done.errored = true;
3488 return doCallback(err);
3489 }
3490 return;
3491 }
3492 if (++completed >= mounts.length) {
3493 doCallback(null);
3494 }
3495 };
3496
3497 // sync all mounts
3498 mounts.forEach(function (mount) {
3499 if (!mount.type.syncfs) {
3500 return done(null);
3501 }
3502 mount.type.syncfs(mount, populate, done);
3503 });
3504 },mount:function (type, opts, mountpoint) {
3505 var root = mountpoint === '/';
3506 var pseudo = !mountpoint;
3507 var node;
3508
3509 if (root && FS.root) {
3510 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3511 } else if (!root && !pseudo) {
3512 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
3513
3514 mountpoint = lookup.path; // use the absolute path
3515 node = lookup.node;
3516
3517 if (FS.isMountpoint(node)) {
3518 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3519 }
3520
3521 if (!FS.isDir(node.mode)) {
3522 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3523 }
3524 }
3525
3526 var mount = {
3527 type: type,
3528 opts: opts,
3529 mountpoint: mountpoint,
3530 mounts: []
3531 };
3532
3533 // create a root node for the fs
3534 var mountRoot = type.mount(mount);
3535 mountRoot.mount = mount;
3536 mount.root = mountRoot;
3537
3538 if (root) {
3539 FS.root = mountRoot;
3540 } else if (node) {
3541 // set as a mountpoint
3542 node.mounted = mount;
3543
3544 // add the new mount to the current mount's children
3545 if (node.mount) {
3546 node.mount.mounts.push(mount);
3547 }
3548 }
3549
3550 return mountRoot;
3551 },unmount:function (mountpoint) {
3552 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
3553
3554 if (!FS.isMountpoint(lookup.node)) {
3555 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3556 }
3557
3558 // destroy the nodes for this mount, and all its child mounts
3559 var node = lookup.node;
3560 var mount = node.mounted;
3561 var mounts = FS.getMounts(mount);
3562
3563 Object.keys(FS.nameTable).forEach(function (hash) {
3564 var current = FS.nameTable[hash];
3565
3566 while (current) {
3567 var next = current.name_next;
3568
3569 if (mounts.indexOf(current.mount) !== -1) {
3570 FS.destroyNode(current);
3571 }
3572
3573 current = next;
3574 }
3575 });
3576
3577 // no longer a mountpoint
3578 node.mounted = null;
3579
3580 // remove this mount from the child mounts
3581 var idx = node.mount.mounts.indexOf(mount);
3582 assert(idx !== -1);
3583 node.mount.mounts.splice(idx, 1);
3584 },lookup:function (parent, name) {
3585 return parent.node_ops.lookup(parent, name);
3586 },mknod:function (path, mode, dev) {
3587 var lookup = FS.lookupPath(path, { parent: true });
3588 var parent = lookup.node;
3589 var name = PATH.basename(path);
3590 if (!name || name === '.' || name === '..') {
3591 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3592 }
3593 var err = FS.mayCreate(parent, name);
3594 if (err) {
3595 throw new FS.ErrnoError(err);
3596 }
3597 if (!parent.node_ops.mknod) {
3598 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3599 }
3600 return parent.node_ops.mknod(parent, name, mode, dev);
3601 },create:function (path, mode) {
3602 mode = mode !== undefined ? mode : 438 /* 0666 */;
3603 mode &= 4095;
3604 mode |= 32768;
3605 return FS.mknod(path, mode, 0);
3606 },mkdir:function (path, mode) {
3607 mode = mode !== undefined ? mode : 511 /* 0777 */;
3608 mode &= 511 | 512;
3609 mode |= 16384;
3610 return FS.mknod(path, mode, 0);
3611 },mkdirTree:function (path, mode) {
3612 var dirs = path.split('/');
3613 var d = '';
3614 for (var i = 0; i < dirs.length; ++i) {
3615 if (!dirs[i]) continue;
3616 d += '/' + dirs[i];
3617 try {
3618 FS.mkdir(d, mode);
3619 } catch(e) {
3620 if (e.errno != ERRNO_CODES.EEXIST) throw e;
3621 }
3622 }
3623 },mkdev:function (path, mode, dev) {
3624 if (typeof(dev) === 'undefined') {
3625 dev = mode;
3626 mode = 438 /* 0666 */;
3627 }
3628 mode |= 8192;
3629 return FS.mknod(path, mode, dev);
3630 },symlink:function (oldpath, newpath) {
3631 if (!PATH.resolve(oldpath)) {
3632 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3633 }
3634 var lookup = FS.lookupPath(newpath, { parent: true });
3635 var parent = lookup.node;
3636 if (!parent) {
3637 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3638 }
3639 var newname = PATH.basename(newpath);
3640 var err = FS.mayCreate(parent, newname);
3641 if (err) {
3642 throw new FS.ErrnoError(err);
3643 }
3644 if (!parent.node_ops.symlink) {
3645 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3646 }
3647 return parent.node_ops.symlink(parent, newname, oldpath);
3648 },rename:function (old_path, new_path) {
3649 var old_dirname = PATH.dirname(old_path);
3650 var new_dirname = PATH.dirname(new_path);
3651 var old_name = PATH.basename(old_path);
3652 var new_name = PATH.basename(new_path);
3653 // parents must exist
3654 var lookup, old_dir, new_dir;
3655 try {
3656 lookup = FS.lookupPath(old_path, { parent: true });
3657 old_dir = lookup.node;
3658 lookup = FS.lookupPath(new_path, { parent: true });
3659 new_dir = lookup.node;
3660 } catch (e) {
3661 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3662 }
3663 if (!old_dir || !new_dir) throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3664 // need to be part of the same mount
3665 if (old_dir.mount !== new_dir.mount) {
3666 throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
3667 }
3668 // source must exist
3669 var old_node = FS.lookupNode(old_dir, old_name);
3670 // old path should not be an ancestor of the new path
3671 var relative = PATH.relative(old_path, new_dirname);
3672 if (relative.charAt(0) !== '.') {
3673 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3674 }
3675 // new path should not be an ancestor of the old path
3676 relative = PATH.relative(new_path, old_dirname);
3677 if (relative.charAt(0) !== '.') {
3678 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
3679 }
3680 // see if the new path already exists
3681 var new_node;
3682 try {
3683 new_node = FS.lookupNode(new_dir, new_name);
3684 } catch (e) {
3685 // not fatal
3686 }
3687 // early out if nothing needs to change
3688 if (old_node === new_node) {
3689 return;
3690 }
3691 // we'll need to delete the old entry
3692 var isdir = FS.isDir(old_node.mode);
3693 var err = FS.mayDelete(old_dir, old_name, isdir);
3694 if (err) {
3695 throw new FS.ErrnoError(err);
3696 }
3697 // need delete permissions if we'll be overwriting.
3698 // need create permissions if new doesn't already exist.
3699 err = new_node ?
3700 FS.mayDelete(new_dir, new_name, isdir) :
3701 FS.mayCreate(new_dir, new_name);
3702 if (err) {
3703 throw new FS.ErrnoError(err);
3704 }
3705 if (!old_dir.node_ops.rename) {
3706 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3707 }
3708 if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
3709 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3710 }
3711 // if we are going to change the parent, check write permissions
3712 if (new_dir !== old_dir) {
3713 err = FS.nodePermissions(old_dir, 'w');
3714 if (err) {
3715 throw new FS.ErrnoError(err);
3716 }
3717 }
3718 try {
3719 if (FS.trackingDelegate['willMovePath']) {
3720 FS.trackingDelegate['willMovePath'](old_path, new_path);
3721 }
3722 } catch(e) {
3723 console.log("FS.trackingDelegate['willMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3724 }
3725 // remove the node from the lookup hash
3726 FS.hashRemoveNode(old_node);
3727 // do the underlying fs rename
3728 try {
3729 old_dir.node_ops.rename(old_node, new_dir, new_name);
3730 } catch (e) {
3731 throw e;
3732 } finally {
3733 // add the node back to the hash (in case node_ops.rename
3734 // changed its name)
3735 FS.hashAddNode(old_node);
3736 }
3737 try {
3738 if (FS.trackingDelegate['onMovePath']) FS.trackingDelegate['onMovePath'](old_path, new_path);
3739 } catch(e) {
3740 console.log("FS.trackingDelegate['onMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3741 }
3742 },rmdir:function (path) {
3743 var lookup = FS.lookupPath(path, { parent: true });
3744 var parent = lookup.node;
3745 var name = PATH.basename(path);
3746 var node = FS.lookupNode(parent, name);
3747 var err = FS.mayDelete(parent, name, true);
3748 if (err) {
3749 throw new FS.ErrnoError(err);
3750 }
3751 if (!parent.node_ops.rmdir) {
3752 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3753 }
3754 if (FS.isMountpoint(node)) {
3755 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3756 }
3757 try {
3758 if (FS.trackingDelegate['willDeletePath']) {
3759 FS.trackingDelegate['willDeletePath'](path);
3760 }
3761 } catch(e) {
3762 console.log("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3763 }
3764 parent.node_ops.rmdir(parent, name);
3765 FS.destroyNode(node);
3766 try {
3767 if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3768 } catch(e) {
3769 console.log("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3770 }
3771 },readdir:function (path) {
3772 var lookup = FS.lookupPath(path, { follow: true });
3773 var node = lookup.node;
3774 if (!node.node_ops.readdir) {
3775 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3776 }
3777 return node.node_ops.readdir(node);
3778 },unlink:function (path) {
3779 var lookup = FS.lookupPath(path, { parent: true });
3780 var parent = lookup.node;
3781 var name = PATH.basename(path);
3782 var node = FS.lookupNode(parent, name);
3783 var err = FS.mayDelete(parent, name, false);
3784 if (err) {
3785 // According to POSIX, we should map EISDIR to EPERM, but
3786 // we instead do what Linux does (and we must, as we use
3787 // the musl linux libc).
3788 throw new FS.ErrnoError(err);
3789 }
3790 if (!parent.node_ops.unlink) {
3791 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3792 }
3793 if (FS.isMountpoint(node)) {
3794 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3795 }
3796 try {
3797 if (FS.trackingDelegate['willDeletePath']) {
3798 FS.trackingDelegate['willDeletePath'](path);
3799 }
3800 } catch(e) {
3801 console.log("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3802 }
3803 parent.node_ops.unlink(parent, name);
3804 FS.destroyNode(node);
3805 try {
3806 if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3807 } catch(e) {
3808 console.log("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3809 }
3810 },readlink:function (path) {
3811 var lookup = FS.lookupPath(path);
3812 var link = lookup.node;
3813 if (!link) {
3814 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3815 }
3816 if (!link.node_ops.readlink) {
3817 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3818 }
3819 return PATH.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
3820 },stat:function (path, dontFollow) {
3821 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3822 var node = lookup.node;
3823 if (!node) {
3824 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3825 }
3826 if (!node.node_ops.getattr) {
3827 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3828 }
3829 return node.node_ops.getattr(node);
3830 },lstat:function (path) {
3831 return FS.stat(path, true);
3832 },chmod:function (path, mode, dontFollow) {
3833 var node;
3834 if (typeof path === 'string') {
3835 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3836 node = lookup.node;
3837 } else {
3838 node = path;
3839 }
3840 if (!node.node_ops.setattr) {
3841 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3842 }
3843 node.node_ops.setattr(node, {
3844 mode: (mode & 4095) | (node.mode & ~4095),
3845 timestamp: Date.now()
3846 });
3847 },lchmod:function (path, mode) {
3848 FS.chmod(path, mode, true);
3849 },fchmod:function (fd, mode) {
3850 var stream = FS.getStream(fd);
3851 if (!stream) {
3852 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3853 }
3854 FS.chmod(stream.node, mode);
3855 },chown:function (path, uid, gid, dontFollow) {
3856 var node;
3857 if (typeof path === 'string') {
3858 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3859 node = lookup.node;
3860 } else {
3861 node = path;
3862 }
3863 if (!node.node_ops.setattr) {
3864 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3865 }
3866 node.node_ops.setattr(node, {
3867 timestamp: Date.now()
3868 // we ignore the uid / gid for now
3869 });
3870 },lchown:function (path, uid, gid) {
3871 FS.chown(path, uid, gid, true);
3872 },fchown:function (fd, uid, gid) {
3873 var stream = FS.getStream(fd);
3874 if (!stream) {
3875 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3876 }
3877 FS.chown(stream.node, uid, gid);
3878 },truncate:function (path, len) {
3879 if (len < 0) {
3880 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3881 }
3882 var node;
3883 if (typeof path === 'string') {
3884 var lookup = FS.lookupPath(path, { follow: true });
3885 node = lookup.node;
3886 } else {
3887 node = path;
3888 }
3889 if (!node.node_ops.setattr) {
3890 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3891 }
3892 if (FS.isDir(node.mode)) {
3893 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3894 }
3895 if (!FS.isFile(node.mode)) {
3896 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3897 }
3898 var err = FS.nodePermissions(node, 'w');
3899 if (err) {
3900 throw new FS.ErrnoError(err);
3901 }
3902 node.node_ops.setattr(node, {
3903 size: len,
3904 timestamp: Date.now()
3905 });
3906 },ftruncate:function (fd, len) {
3907 var stream = FS.getStream(fd);
3908 if (!stream) {
3909 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3910 }
3911 if ((stream.flags & 2097155) === 0) {
3912 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3913 }
3914 FS.truncate(stream.node, len);
3915 },utime:function (path, atime, mtime) {
3916 var lookup = FS.lookupPath(path, { follow: true });
3917 var node = lookup.node;
3918 node.node_ops.setattr(node, {
3919 timestamp: Math.max(atime, mtime)
3920 });
3921 },open:function (path, flags, mode, fd_start, fd_end) {
3922 if (path === "") {
3923 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3924 }
3925 flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3926 mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3927 if ((flags & 64)) {
3928 mode = (mode & 4095) | 32768;
3929 } else {
3930 mode = 0;
3931 }
3932 var node;
3933 if (typeof path === 'object') {
3934 node = path;
3935 } else {
3936 path = PATH.normalize(path);
3937 try {
3938 var lookup = FS.lookupPath(path, {
3939 follow: !(flags & 131072)
3940 });
3941 node = lookup.node;
3942 } catch (e) {
3943 // ignore
3944 }
3945 }
3946 // perhaps we need to create the node
3947 var created = false;
3948 if ((flags & 64)) {
3949 if (node) {
3950 // if O_CREAT and O_EXCL are set, error out if the node already exists
3951 if ((flags & 128)) {
3952 throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
3953 }
3954 } else {
3955 // node doesn't exist, try to create it
3956 node = FS.mknod(path, mode, 0);
3957 created = true;
3958 }
3959 }
3960 if (!node) {
3961 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3962 }
3963 // can't truncate a device
3964 if (FS.isChrdev(node.mode)) {
3965 flags &= ~512;
3966 }
3967 // if asked only for a directory, then this must be one
3968 if ((flags & 65536) && !FS.isDir(node.mode)) {
3969 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3970 }
3971 // check permissions, if this is not a file we just created now (it is ok to
3972 // create and write to a file with read-only permissions; it is read-only
3973 // for later use)
3974 if (!created) {
3975 var err = FS.mayOpen(node, flags);
3976 if (err) {
3977 throw new FS.ErrnoError(err);
3978 }
3979 }
3980 // do truncation if necessary
3981 if ((flags & 512)) {
3982 FS.truncate(node, 0);
3983 }
3984 // we've already handled these, don't pass down to the underlying vfs
3985 flags &= ~(128 | 512);
3986
3987 // register the stream with the filesystem
3988 var stream = FS.createStream({
3989 node: node,
3990 path: FS.getPath(node), // we want the absolute path to the node
3991 flags: flags,
3992 seekable: true,
3993 position: 0,
3994 stream_ops: node.stream_ops,
3995 // used by the file family libc calls (fopen, fwrite, ferror, etc.)
3996 ungotten: [],
3997 error: false
3998 }, fd_start, fd_end);
3999 // call the new stream's open function
4000 if (stream.stream_ops.open) {
4001 stream.stream_ops.open(stream);
4002 }
4003 if (Module['logReadFiles'] && !(flags & 1)) {
4004 if (!FS.readFiles) FS.readFiles = {};
4005 if (!(path in FS.readFiles)) {
4006 FS.readFiles[path] = 1;
4007 Module['printErr']('read file: ' + path);
4008 }
4009 }
4010 try {
4011 if (FS.trackingDelegate['onOpenFile']) {
4012 var trackingFlags = 0;
4013 if ((flags & 2097155) !== 1) {
4014 trackingFlags |= FS.tracking.openFlags.READ;
4015 }
4016 if ((flags & 2097155) !== 0) {
4017 trackingFlags |= FS.tracking.openFlags.WRITE;
4018 }
4019 FS.trackingDelegate['onOpenFile'](path, trackingFlags);
4020 }
4021 } catch(e) {
4022 console.log("FS.trackingDelegate['onOpenFile']('"+path+"', flags) threw an exception: " + e.message);
4023 }
4024 return stream;
4025 },close:function (stream) {
4026 if (stream.getdents) stream.getdents = null; // free readdir state
4027 try {
4028 if (stream.stream_ops.close) {
4029 stream.stream_ops.close(stream);
4030 }
4031 } catch (e) {
4032 throw e;
4033 } finally {
4034 FS.closeStream(stream.fd);
4035 }
4036 },llseek:function (stream, offset, whence) {
4037 if (!stream.seekable || !stream.stream_ops.llseek) {
4038 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
4039 }
4040 stream.position = stream.stream_ops.llseek(stream, offset, whence);
4041 stream.ungotten = [];
4042 return stream.position;
4043 },read:function (stream, buffer, offset, length, position) {
4044 if (length < 0 || position < 0) {
4045 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4046 }
4047 if ((stream.flags & 2097155) === 1) {
4048 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4049 }
4050 if (FS.isDir(stream.node.mode)) {
4051 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
4052 }
4053 if (!stream.stream_ops.read) {
4054 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4055 }
4056 var seeking = typeof position !== 'undefined';
4057 if (!seeking) {
4058 position = stream.position;
4059 } else if (!stream.seekable) {
4060 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
4061 }
4062 var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
4063 if (!seeking) stream.position += bytesRead;
4064 return bytesRead;
4065 },write:function (stream, buffer, offset, length, position, canOwn) {
4066 if (length < 0 || position < 0) {
4067 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4068 }
4069 if ((stream.flags & 2097155) === 0) {
4070 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4071 }
4072 if (FS.isDir(stream.node.mode)) {
4073 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
4074 }
4075 if (!stream.stream_ops.write) {
4076 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4077 }
4078 if (stream.flags & 1024) {
4079 // seek to the end before writing in append mode
4080 FS.llseek(stream, 0, 2);
4081 }
4082 var seeking = typeof position !== 'undefined';
4083 if (!seeking) {
4084 position = stream.position;
4085 } else if (!stream.seekable) {
4086 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
4087 }
4088 var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
4089 if (!seeking) stream.position += bytesWritten;
4090 try {
4091 if (stream.path && FS.trackingDelegate['onWriteToFile']) FS.trackingDelegate['onWriteToFile'](stream.path);
4092 } catch(e) {
4093 console.log("FS.trackingDelegate['onWriteToFile']('"+path+"') threw an exception: " + e.message);
4094 }
4095 return bytesWritten;
4096 },allocate:function (stream, offset, length) {
4097 if (offset < 0 || length <= 0) {
4098 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4099 }
4100 if ((stream.flags & 2097155) === 0) {
4101 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4102 }
4103 if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
4104 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
4105 }
4106 if (!stream.stream_ops.allocate) {
4107 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
4108 }
4109 stream.stream_ops.allocate(stream, offset, length);
4110 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
4111 // TODO if PROT is PROT_WRITE, make sure we have write access
4112 if ((stream.flags & 2097155) === 1) {
4113 throw new FS.ErrnoError(ERRNO_CODES.EACCES);
4114 }
4115 if (!stream.stream_ops.mmap) {
4116 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
4117 }
4118 return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
4119 },msync:function (stream, buffer, offset, length, mmapFlags) {
4120 if (!stream || !stream.stream_ops.msync) {
4121 return 0;
4122 }
4123 return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
4124 },munmap:function (stream) {
4125 return 0;
4126 },ioctl:function (stream, cmd, arg) {
4127 if (!stream.stream_ops.ioctl) {
4128 throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
4129 }
4130 return stream.stream_ops.ioctl(stream, cmd, arg);
4131 },readFile:function (path, opts) {
4132 opts = opts || {};
4133 opts.flags = opts.flags || 'r';
4134 opts.encoding = opts.encoding || 'binary';
4135 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
4136 throw new Error('Invalid encoding type "' + opts.encoding + '"');
4137 }
4138 var ret;
4139 var stream = FS.open(path, opts.flags);
4140 var stat = FS.stat(path);
4141 var length = stat.size;
4142 var buf = new Uint8Array(length);
4143 FS.read(stream, buf, 0, length, 0);
4144 if (opts.encoding === 'utf8') {
4145 ret = UTF8ArrayToString(buf, 0);
4146 } else if (opts.encoding === 'binary') {
4147 ret = buf;
4148 }
4149 FS.close(stream);
4150 return ret;
4151 },writeFile:function (path, data, opts) {
4152 opts = opts || {};
4153 opts.flags = opts.flags || 'w';
4154 var stream = FS.open(path, opts.flags, opts.mode);
4155 if (typeof data === 'string') {
4156 var buf = new Uint8Array(lengthBytesUTF8(data)+1);
4157 var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
4158 FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
4159 } else if (ArrayBuffer.isView(data)) {
4160 FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
4161 } else {
4162 throw new Error('Unsupported data type');
4163 }
4164 FS.close(stream);
4165 },cwd:function () {
4166 return FS.currentPath;
4167 },chdir:function (path) {
4168 var lookup = FS.lookupPath(path, { follow: true });
4169 if (lookup.node === null) {
4170 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
4171 }
4172 if (!FS.isDir(lookup.node.mode)) {
4173 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
4174 }
4175 var err = FS.nodePermissions(lookup.node, 'x');
4176 if (err) {
4177 throw new FS.ErrnoError(err);
4178 }
4179 FS.currentPath = lookup.path;
4180 },createDefaultDirectories:function () {
4181 FS.mkdir('/tmp');
4182 FS.mkdir('/home');
4183 FS.mkdir('/home/web_user');
4184 },createDefaultDevices:function () {
4185 // create /dev
4186 FS.mkdir('/dev');
4187 // setup /dev/null
4188 FS.registerDevice(FS.makedev(1, 3), {
4189 read: function() { return 0; },
4190 write: function(stream, buffer, offset, length, pos) { return length; }
4191 });
4192 FS.mkdev('/dev/null', FS.makedev(1, 3));
4193 // setup /dev/tty and /dev/tty1
4194 // stderr needs to print output using Module['printErr']
4195 // so we register a second tty just for it.
4196 TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
4197 TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
4198 FS.mkdev('/dev/tty', FS.makedev(5, 0));
4199 FS.mkdev('/dev/tty1', FS.makedev(6, 0));
4200 // setup /dev/[u]random
4201 var random_device;
4202 if (typeof crypto !== 'undefined') {
4203 // for modern web browsers
4204 var randomBuffer = new Uint8Array(1);
4205 random_device = function() { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
4206 } else if (ENVIRONMENT_IS_NODE) {
4207 // for nodejs
4208 random_device = function() { return require('crypto')['randomBytes'](1)[0]; };
4209 } else {
4210 // default for ES5 platforms
4211 random_device = function() { return (Math.random()*256)|0; };
4212 }
4213 FS.createDevice('/dev', 'random', random_device);
4214 FS.createDevice('/dev', 'urandom', random_device);
4215 // we're not going to emulate the actual shm device,
4216 // just create the tmp dirs that reside in it commonly
4217 FS.mkdir('/dev/shm');
4218 FS.mkdir('/dev/shm/tmp');
4219 },createSpecialDirectories:function () {
4220 // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the name of the stream for fd 6 (see test_unistd_ttyname)
4221 FS.mkdir('/proc');
4222 FS.mkdir('/proc/self');
4223 FS.mkdir('/proc/self/fd');
4224 FS.mount({
4225 mount: function() {
4226 var node = FS.createNode('/proc/self', 'fd', 16384 | 511 /* 0777 */, 73);
4227 node.node_ops = {
4228 lookup: function(parent, name) {
4229 var fd = +name;
4230 var stream = FS.getStream(fd);
4231 if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4232 var ret = {
4233 parent: null,
4234 mount: { mountpoint: 'fake' },
4235 node_ops: { readlink: function() { return stream.path } }
4236 };
4237 ret.parent = ret; // make it look like a simple root node
4238 return ret;
4239 }
4240 };
4241 return node;
4242 }
4243 }, {}, '/proc/self/fd');
4244 },createStandardStreams:function () {
4245 // TODO deprecate the old functionality of a single
4246 // input / output callback and that utilizes FS.createDevice
4247 // and instead require a unique set of stream ops
4248
4249 // by default, we symlink the standard streams to the
4250 // default tty devices. however, if the standard streams
4251 // have been overwritten we create a unique device for
4252 // them instead.
4253 if (Module['stdin']) {
4254 FS.createDevice('/dev', 'stdin', Module['stdin']);
4255 } else {
4256 FS.symlink('/dev/tty', '/dev/stdin');
4257 }
4258 if (Module['stdout']) {
4259 FS.createDevice('/dev', 'stdout', null, Module['stdout']);
4260 } else {
4261 FS.symlink('/dev/tty', '/dev/stdout');
4262 }
4263 if (Module['stderr']) {
4264 FS.createDevice('/dev', 'stderr', null, Module['stderr']);
4265 } else {
4266 FS.symlink('/dev/tty1', '/dev/stderr');
4267 }
4268
4269 // open default streams for the stdin, stdout and stderr devices
4270 var stdin = FS.open('/dev/stdin', 'r');
4271 assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
4272
4273 var stdout = FS.open('/dev/stdout', 'w');
4274 assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
4275
4276 var stderr = FS.open('/dev/stderr', 'w');
4277 assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
4278 },ensureErrnoError:function () {
4279 if (FS.ErrnoError) return;
4280 FS.ErrnoError = function ErrnoError(errno, node) {
4281 //Module.printErr(stackTrace()); // useful for debugging
4282 this.node = node;
4283 this.setErrno = function(errno) {
4284 this.errno = errno;
4285 for (var key in ERRNO_CODES) {
4286 if (ERRNO_CODES[key] === errno) {
4287 this.code = key;
4288 break;
4289 }
4290 }
4291 };
4292 this.setErrno(errno);
4293 this.message = ERRNO_MESSAGES[errno];
4294 // Node.js compatibility: assigning on this.stack fails on Node 4 (but fixed on Node 8)
4295 if (this.stack) Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true });
4296 if (this.stack) this.stack = demangleAll(this.stack);
4297 };
4298 FS.ErrnoError.prototype = new Error();
4299 FS.ErrnoError.prototype.constructor = FS.ErrnoError;
4300 // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
4301 [ERRNO_CODES.ENOENT].forEach(function(code) {
4302 FS.genericErrors[code] = new FS.ErrnoError(code);
4303 FS.genericErrors[code].stack = '<generic error, no stack>';
4304 });
4305 },staticInit:function () {
4306 FS.ensureErrnoError();
4307
4308 FS.nameTable = new Array(4096);
4309
4310 FS.mount(MEMFS, {}, '/');
4311
4312 FS.createDefaultDirectories();
4313 FS.createDefaultDevices();
4314 FS.createSpecialDirectories();
4315
4316 FS.filesystems = {
4317 'MEMFS': MEMFS,
4318 'IDBFS': IDBFS,
4319 'NODEFS': NODEFS,
4320 'WORKERFS': WORKERFS,
4321 };
4322 },init:function (input, output, error) {
4323 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)');
4324 FS.init.initialized = true;
4325
4326 FS.ensureErrnoError();
4327
4328 // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
4329 Module['stdin'] = input || Module['stdin'];
4330 Module['stdout'] = output || Module['stdout'];
4331 Module['stderr'] = error || Module['stderr'];
4332
4333 FS.createStandardStreams();
4334 },quit:function () {
4335 FS.init.initialized = false;
4336 // force-flush all streams, so we get musl std streams printed out
4337 var fflush = Module['_fflush'];
4338 if (fflush) fflush(0);
4339 // close all of our streams
4340 for (var i = 0; i < FS.streams.length; i++) {
4341 var stream = FS.streams[i];
4342 if (!stream) {
4343 continue;
4344 }
4345 FS.close(stream);
4346 }
4347 },getMode:function (canRead, canWrite) {
4348 var mode = 0;
4349 if (canRead) mode |= 292 | 73;
4350 if (canWrite) mode |= 146;
4351 return mode;
4352 },joinPath:function (parts, forceRelative) {
4353 var path = PATH.join.apply(null, parts);
4354 if (forceRelative && path[0] == '/') path = path.substr(1);
4355 return path;
4356 },absolutePath:function (relative, base) {
4357 return PATH.resolve(base, relative);
4358 },standardizePath:function (path) {
4359 return PATH.normalize(path);
4360 },findObject:function (path, dontResolveLastLink) {
4361 var ret = FS.analyzePath(path, dontResolveLastLink);
4362 if (ret.exists) {
4363 return ret.object;
4364 } else {
4365 ___setErrNo(ret.error);
4366 return null;
4367 }
4368 },analyzePath:function (path, dontResolveLastLink) {
4369 // operate from within the context of the symlink's target
4370 try {
4371 var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4372 path = lookup.path;
4373 } catch (e) {
4374 }
4375 var ret = {
4376 isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
4377 parentExists: false, parentPath: null, parentObject: null
4378 };
4379 try {
4380 var lookup = FS.lookupPath(path, { parent: true });
4381 ret.parentExists = true;
4382 ret.parentPath = lookup.path;
4383 ret.parentObject = lookup.node;
4384 ret.name = PATH.basename(path);
4385 lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4386 ret.exists = true;
4387 ret.path = lookup.path;
4388 ret.object = lookup.node;
4389 ret.name = lookup.node.name;
4390 ret.isRoot = lookup.path === '/';
4391 } catch (e) {
4392 ret.error = e.errno;
4393 };
4394 return ret;
4395 },createFolder:function (parent, name, canRead, canWrite) {
4396 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
4397 var mode = FS.getMode(canRead, canWrite);
4398 return FS.mkdir(path, mode);
4399 },createPath:function (parent, path, canRead, canWrite) {
4400 parent = typeof parent === 'string' ? parent : FS.getPath(parent);
4401 var parts = path.split('/').reverse();
4402 while (parts.length) {
4403 var part = parts.pop();
4404 if (!part) continue;
4405 var current = PATH.join2(parent, part);
4406 try {
4407 FS.mkdir(current);
4408 } catch (e) {
4409 // ignore EEXIST
4410 }
4411 parent = current;
4412 }
4413 return current;
4414 },createFile:function (parent, name, properties, canRead, canWrite) {
4415 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
4416 var mode = FS.getMode(canRead, canWrite);
4417 return FS.create(path, mode);
4418 },createDataFile:function (parent, name, data, canRead, canWrite, canOwn) {
4419 var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
4420 var mode = FS.getMode(canRead, canWrite);
4421 var node = FS.create(path, mode);
4422 if (data) {
4423 if (typeof data === 'string') {
4424 var arr = new Array(data.length);
4425 for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
4426 data = arr;
4427 }
4428 // make sure we can write to the file
4429 FS.chmod(node, mode | 146);
4430 var stream = FS.open(node, 'w');
4431 FS.write(stream, data, 0, data.length, 0, canOwn);
4432 FS.close(stream);
4433 FS.chmod(node, mode);
4434 }
4435 return node;
4436 },createDevice:function (parent, name, input, output) {
4437 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
4438 var mode = FS.getMode(!!input, !!output);
4439 if (!FS.createDevice.major) FS.createDevice.major = 64;
4440 var dev = FS.makedev(FS.createDevice.major++, 0);
4441 // Create a fake device that a set of stream ops to emulate
4442 // the old behavior.
4443 FS.registerDevice(dev, {
4444 open: function(stream) {
4445 stream.seekable = false;
4446 },
4447 close: function(stream) {
4448 // flush any pending line data
4449 if (output && output.buffer && output.buffer.length) {
4450 output(10);
4451 }
4452 },
4453 read: function(stream, buffer, offset, length, pos /* ignored */) {
4454 var bytesRead = 0;
4455 for (var i = 0; i < length; i++) {
4456 var result;
4457 try {
4458 result = input();
4459 } catch (e) {
4460 throw new FS.ErrnoError(ERRNO_CODES.EIO);
4461 }
4462 if (result === undefined && bytesRead === 0) {
4463 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4464 }
4465 if (result === null || result === undefined) break;
4466 bytesRead++;
4467 buffer[offset+i] = result;
4468 }
4469 if (bytesRead) {
4470 stream.node.timestamp = Date.now();
4471 }
4472 return bytesRead;
4473 },
4474 write: function(stream, buffer, offset, length, pos) {
4475 for (var i = 0; i < length; i++) {
4476 try {
4477 output(buffer[offset+i]);
4478 } catch (e) {
4479 throw new FS.ErrnoError(ERRNO_CODES.EIO);
4480 }
4481 }
4482 if (length) {
4483 stream.node.timestamp = Date.now();
4484 }
4485 return i;
4486 }
4487 });
4488 return FS.mkdev(path, mode, dev);
4489 },createLink:function (parent, name, target, canRead, canWrite) {
4490 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
4491 return FS.symlink(target, path);
4492 },forceLoadFile:function (obj) {
4493 if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
4494 var success = true;
4495 if (typeof XMLHttpRequest !== 'undefined') {
4496 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.");
4497 } else if (Module['read']) {
4498 // Command-line.
4499 try {
4500 // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
4501 // read() will try to parse UTF8.
4502 obj.contents = intArrayFromString(Module['read'](obj.url), true);
4503 obj.usedBytes = obj.contents.length;
4504 } catch (e) {
4505 success = false;
4506 }
4507 } else {
4508 throw new Error('Cannot load without read() or XMLHttpRequest.');
4509 }
4510 if (!success) ___setErrNo(ERRNO_CODES.EIO);
4511 return success;
4512 },createLazyFile:function (parent, name, url, canRead, canWrite) {
4513 // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
4514 function LazyUint8Array() {
4515 this.lengthKnown = false;
4516 this.chunks = []; // Loaded chunks. Index is the chunk number
4517 }
4518 LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
4519 if (idx > this.length-1 || idx < 0) {
4520 return undefined;
4521 }
4522 var chunkOffset = idx % this.chunkSize;
4523 var chunkNum = (idx / this.chunkSize)|0;
4524 return this.getter(chunkNum)[chunkOffset];
4525 }
4526 LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
4527 this.getter = getter;
4528 }
4529 LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
4530 // Find length
4531 var xhr = new XMLHttpRequest();
4532 xhr.open('HEAD', url, false);
4533 xhr.send(null);
4534 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
4535 var datalength = Number(xhr.getResponseHeader("Content-length"));
4536 var header;
4537 var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
4538 var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
4539
4540 var chunkSize = 1024*1024; // Chunk size in bytes
4541
4542 if (!hasByteServing) chunkSize = datalength;
4543
4544 // Function to get a range from the remote URL.
4545 var doXHR = (function(from, to) {
4546 if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
4547 if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
4548
4549 // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
4550 var xhr = new XMLHttpRequest();
4551 xhr.open('GET', url, false);
4552 if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
4553
4554 // Some hints to the browser that we want binary data.
4555 if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
4556 if (xhr.overrideMimeType) {
4557 xhr.overrideMimeType('text/plain; charset=x-user-defined');
4558 }
4559
4560 xhr.send(null);
4561 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
4562 if (xhr.response !== undefined) {
4563 return new Uint8Array(xhr.response || []);
4564 } else {
4565 return intArrayFromString(xhr.responseText || '', true);
4566 }
4567 });
4568 var lazyArray = this;
4569 lazyArray.setDataGetter(function(chunkNum) {
4570 var start = chunkNum * chunkSize;
4571 var end = (chunkNum+1) * chunkSize - 1; // including this byte
4572 end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
4573 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
4574 lazyArray.chunks[chunkNum] = doXHR(start, end);
4575 }
4576 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
4577 return lazyArray.chunks[chunkNum];
4578 });
4579
4580 if (usesGzip || !datalength) {
4581 // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
4582 chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
4583 datalength = this.getter(0).length;
4584 chunkSize = datalength;
4585 console.log("LazyFiles on gzip forces download of the whole file when length is accessed");
4586 }
4587
4588 this._length = datalength;
4589 this._chunkSize = chunkSize;
4590 this.lengthKnown = true;
4591 }
4592 if (typeof XMLHttpRequest !== 'undefined') {
4593 if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
4594 var lazyArray = new LazyUint8Array();
4595 Object.defineProperties(lazyArray, {
4596 length: {
4597 get: function() {
4598 if(!this.lengthKnown) {
4599 this.cacheLength();
4600 }
4601 return this._length;
4602 }
4603 },
4604 chunkSize: {
4605 get: function() {
4606 if(!this.lengthKnown) {
4607 this.cacheLength();
4608 }
4609 return this._chunkSize;
4610 }
4611 }
4612 });
4613
4614 var properties = { isDevice: false, contents: lazyArray };
4615 } else {
4616 var properties = { isDevice: false, url: url };
4617 }
4618
4619 var node = FS.createFile(parent, name, properties, canRead, canWrite);
4620 // This is a total hack, but I want to get this lazy file code out of the
4621 // core of MEMFS. If we want to keep this lazy file concept I feel it should
4622 // be its own thin LAZYFS proxying calls to MEMFS.
4623 if (properties.contents) {
4624 node.contents = properties.contents;
4625 } else if (properties.url) {
4626 node.contents = null;
4627 node.url = properties.url;
4628 }
4629 // Add a function that defers querying the file size until it is asked the first time.
4630 Object.defineProperties(node, {
4631 usedBytes: {
4632 get: function() { return this.contents.length; }
4633 }
4634 });
4635 // override each stream op with one that tries to force load the lazy file first
4636 var stream_ops = {};
4637 var keys = Object.keys(node.stream_ops);
4638 keys.forEach(function(key) {
4639 var fn = node.stream_ops[key];
4640 stream_ops[key] = function forceLoadLazyFile() {
4641 if (!FS.forceLoadFile(node)) {
4642 throw new FS.ErrnoError(ERRNO_CODES.EIO);
4643 }
4644 return fn.apply(null, arguments);
4645 };
4646 });
4647 // use a custom read function
4648 stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
4649 if (!FS.forceLoadFile(node)) {
4650 throw new FS.ErrnoError(ERRNO_CODES.EIO);
4651 }
4652 var contents = stream.node.contents;
4653 if (position >= contents.length)
4654 return 0;
4655 var size = Math.min(contents.length - position, length);
4656 assert(size >= 0);
4657 if (contents.slice) { // normal array
4658 for (var i = 0; i < size; i++) {
4659 buffer[offset + i] = contents[position + i];
4660 }
4661 } else {
4662 for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
4663 buffer[offset + i] = contents.get(position + i);
4664 }
4665 }
4666 return size;
4667 };
4668 node.stream_ops = stream_ops;
4669 return node;
4670 },createPreloadedFile:function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
4671 Browser.init(); // XXX perhaps this method should move onto Browser?
4672 // TODO we should allow people to just pass in a complete filename instead
4673 // of parent and name being that we just join them anyways
4674 var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
4675 var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
4676 function processData(byteArray) {
4677 function finish(byteArray) {
4678 if (preFinish) preFinish();
4679 if (!dontCreateFile) {
4680 FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
4681 }
4682 if (onload) onload();
4683 removeRunDependency(dep);
4684 }
4685 var handled = false;
4686 Module['preloadPlugins'].forEach(function(plugin) {
4687 if (handled) return;
4688 if (plugin['canHandle'](fullname)) {
4689 plugin['handle'](byteArray, fullname, finish, function() {
4690 if (onerror) onerror();
4691 removeRunDependency(dep);
4692 });
4693 handled = true;
4694 }
4695 });
4696 if (!handled) finish(byteArray);
4697 }
4698 addRunDependency(dep);
4699 if (typeof url == 'string') {
4700 Browser.asyncLoad(url, function(byteArray) {
4701 processData(byteArray);
4702 }, onerror);
4703 } else {
4704 processData(url);
4705 }
4706 },indexedDB:function () {
4707 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
4708 },DB_NAME:function () {
4709 return 'EM_FS_' + window.location.pathname;
4710 },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function (paths, onload, onerror) {
4711 onload = onload || function(){};
4712 onerror = onerror || function(){};
4713 var indexedDB = FS.indexedDB();
4714 try {
4715 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4716 } catch (e) {
4717 return onerror(e);
4718 }
4719 openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
4720 console.log('creating db');
4721 var db = openRequest.result;
4722 db.createObjectStore(FS.DB_STORE_NAME);
4723 };
4724 openRequest.onsuccess = function openRequest_onsuccess() {
4725 var db = openRequest.result;
4726 var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
4727 var files = transaction.objectStore(FS.DB_STORE_NAME);
4728 var ok = 0, fail = 0, total = paths.length;
4729 function finish() {
4730 if (fail == 0) onload(); else onerror();
4731 }
4732 paths.forEach(function(path) {
4733 var putRequest = files.put(FS.analyzePath(path).object.contents, path);
4734 putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
4735 putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
4736 });
4737 transaction.onerror = onerror;
4738 };
4739 openRequest.onerror = onerror;
4740 },loadFilesFromDB:function (paths, onload, onerror) {
4741 onload = onload || function(){};
4742 onerror = onerror || function(){};
4743 var indexedDB = FS.indexedDB();
4744 try {
4745 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4746 } catch (e) {
4747 return onerror(e);
4748 }
4749 openRequest.onupgradeneeded = onerror; // no database to load from
4750 openRequest.onsuccess = function openRequest_onsuccess() {
4751 var db = openRequest.result;
4752 try {
4753 var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
4754 } catch(e) {
4755 onerror(e);
4756 return;
4757 }
4758 var files = transaction.objectStore(FS.DB_STORE_NAME);
4759 var ok = 0, fail = 0, total = paths.length;
4760 function finish() {
4761 if (fail == 0) onload(); else onerror();
4762 }
4763 paths.forEach(function(path) {
4764 var getRequest = files.get(path);
4765 getRequest.onsuccess = function getRequest_onsuccess() {
4766 if (FS.analyzePath(path).exists) {
4767 FS.unlink(path);
4768 }
4769 FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
4770 ok++;
4771 if (ok + fail == total) finish();
4772 };
4773 getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
4774 });
4775 transaction.onerror = onerror;
4776 };
4777 openRequest.onerror = onerror;
4778 }};var SYSCALLS={DEFAULT_POLLMASK:5,mappings:{},umask:511,calculateAt:function (dirfd, path) {
4779 if (path[0] !== '/') {
4780 // relative path
4781 var dir;
4782 if (dirfd === -100) {
4783 dir = FS.cwd();
4784 } else {
4785 var dirstream = FS.getStream(dirfd);
4786 if (!dirstream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4787 dir = dirstream.path;
4788 }
4789 path = PATH.join2(dir, path);
4790 }
4791 return path;
4792 },doStat:function (func, path, buf) {
4793 try {
4794 var stat = func(path);
4795 } catch (e) {
4796 if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
4797 // an error occurred while trying to look up the path; we should just report ENOTDIR
4798 return -ERRNO_CODES.ENOTDIR;
4799 }
4800 throw e;
4801 }
4802 HEAP32[((buf)>>2)]=stat.dev;
4803 HEAP32[(((buf)+(4))>>2)]=0;
4804 HEAP32[(((buf)+(8))>>2)]=stat.ino;
4805 HEAP32[(((buf)+(12))>>2)]=stat.mode;
4806 HEAP32[(((buf)+(16))>>2)]=stat.nlink;
4807 HEAP32[(((buf)+(20))>>2)]=stat.uid;
4808 HEAP32[(((buf)+(24))>>2)]=stat.gid;
4809 HEAP32[(((buf)+(28))>>2)]=stat.rdev;
4810 HEAP32[(((buf)+(32))>>2)]=0;
4811 HEAP32[(((buf)+(36))>>2)]=stat.size;
4812 HEAP32[(((buf)+(40))>>2)]=4096;
4813 HEAP32[(((buf)+(44))>>2)]=stat.blocks;
4814 HEAP32[(((buf)+(48))>>2)]=(stat.atime.getTime() / 1000)|0;
4815 HEAP32[(((buf)+(52))>>2)]=0;
4816 HEAP32[(((buf)+(56))>>2)]=(stat.mtime.getTime() / 1000)|0;
4817 HEAP32[(((buf)+(60))>>2)]=0;
4818 HEAP32[(((buf)+(64))>>2)]=(stat.ctime.getTime() / 1000)|0;
4819 HEAP32[(((buf)+(68))>>2)]=0;
4820 HEAP32[(((buf)+(72))>>2)]=stat.ino;
4821 return 0;
4822 },doMsync:function (addr, stream, len, flags) {
4823 var buffer = new Uint8Array(HEAPU8.subarray(addr, addr + len));
4824 FS.msync(stream, buffer, 0, len, flags);
4825 },doMkdir:function (path, mode) {
4826 // remove a trailing slash, if one - /a/b/ has basename of '', but
4827 // we want to create b in the context of this function
4828 path = PATH.normalize(path);
4829 if (path[path.length-1] === '/') path = path.substr(0, path.length-1);
4830 FS.mkdir(path, mode, 0);
4831 return 0;
4832 },doMknod:function (path, mode, dev) {
4833 // we don't want this in the JS API as it uses mknod to create all nodes.
4834 switch (mode & 61440) {
4835 case 32768:
4836 case 8192:
4837 case 24576:
4838 case 4096:
4839 case 49152:
4840 break;
4841 default: return -ERRNO_CODES.EINVAL;
4842 }
4843 FS.mknod(path, mode, dev);
4844 return 0;
4845 },doReadlink:function (path, buf, bufsize) {
4846 if (bufsize <= 0) return -ERRNO_CODES.EINVAL;
4847 var ret = FS.readlink(path);
4848
4849 var len = Math.min(bufsize, lengthBytesUTF8(ret));
4850 var endChar = HEAP8[buf+len];
4851 stringToUTF8(ret, buf, bufsize+1);
4852 // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
4853 // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
4854 HEAP8[buf+len] = endChar;
4855
4856 return len;
4857 },doAccess:function (path, amode) {
4858 if (amode & ~7) {
4859 // need a valid mode
4860 return -ERRNO_CODES.EINVAL;
4861 }
4862 var node;
4863 var lookup = FS.lookupPath(path, { follow: true });
4864 node = lookup.node;
4865 var perms = '';
4866 if (amode & 4) perms += 'r';
4867 if (amode & 2) perms += 'w';
4868 if (amode & 1) perms += 'x';
4869 if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
4870 return -ERRNO_CODES.EACCES;
4871 }
4872 return 0;
4873 },doDup:function (path, flags, suggestFD) {
4874 var suggest = FS.getStream(suggestFD);
4875 if (suggest) FS.close(suggest);
4876 return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
4877 },doReadv:function (stream, iov, iovcnt, offset) {
4878 var ret = 0;
4879 for (var i = 0; i < iovcnt; i++) {
4880 var ptr = HEAP32[(((iov)+(i*8))>>2)];
4881 var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4882 var curr = FS.read(stream, HEAP8,ptr, len, offset);
4883 if (curr < 0) return -1;
4884 ret += curr;
4885 if (curr < len) break; // nothing more to read
4886 }
4887 return ret;
4888 },doWritev:function (stream, iov, iovcnt, offset) {
4889 var ret = 0;
4890 for (var i = 0; i < iovcnt; i++) {
4891 var ptr = HEAP32[(((iov)+(i*8))>>2)];
4892 var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4893 var curr = FS.write(stream, HEAP8,ptr, len, offset);
4894 if (curr < 0) return -1;
4895 ret += curr;
4896 }
4897 return ret;
4898 },varargs:0,get:function (varargs) {
4899 SYSCALLS.varargs += 4;
4900 var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
4901 return ret;
4902 },getStr:function () {
4903 var ret = Pointer_stringify(SYSCALLS.get());
4904 return ret;
4905 },getStreamFromFD:function () {
4906 var stream = FS.getStream(SYSCALLS.get());
4907 if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4908 return stream;
4909 },getSocketFromFD:function () {
4910 var socket = SOCKFS.getSocket(SYSCALLS.get());
4911 if (!socket) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
4912 return socket;
4913 },getSocketAddress:function (allowNull) {
4914 var addrp = SYSCALLS.get(), addrlen = SYSCALLS.get();
4915 if (allowNull && addrp === 0) return null;
4916 var info = __read_sockaddr(addrp, addrlen);
4917 if (info.errno) throw new FS.ErrnoError(info.errno);
4918 info.addr = DNS.lookup_addr(info.addr) || info.addr;
4919 return info;
4920 },get64:function () {
4921 var low = SYSCALLS.get(), high = SYSCALLS.get();
4922 if (low >= 0) assert(high === 0);
4923 else assert(high === -1);
4924 return low;
4925 },getZero:function () {
4926 assert(SYSCALLS.get() === 0);
4927 }};function ___syscall10(which, varargs) {SYSCALLS.varargs = varargs;
4928 try {
4929 // unlink
4930 var path = SYSCALLS.getStr();
4931 FS.unlink(path);
4932 return 0;
4933 } catch (e) {
4934 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4935 return -e.errno;
4936 }
4937 }
4938
4939 function ___syscall140(which, varargs) {SYSCALLS.varargs = varargs;
4940 try {
4941 // llseek
4942 var stream = SYSCALLS.getStreamFromFD(), offset_high = SYSCALLS.get(), offset_low = SYSCALLS.get(), result = SYSCALLS.get(), whence = SYSCALLS.get();
4943 // NOTE: offset_high is unused - Emscripten's off_t is 32-bit
4944 var offset = offset_low;
4945 FS.llseek(stream, offset, whence);
4946 HEAP32[((result)>>2)]=stream.position;
4947 if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
4948 return 0;
4949 } catch (e) {
4950 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4951 return -e.errno;
4952 }
4953 }
4954
4955 function ___syscall145(which, varargs) {SYSCALLS.varargs = varargs;
4956 try {
4957 // readv
4958 var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get();
4959 return SYSCALLS.doReadv(stream, iov, iovcnt);
4960 } catch (e) {
4961 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4962 return -e.errno;
4963 }
4964 }
4965
4966 function ___syscall146(which, varargs) {SYSCALLS.varargs = varargs;
4967 try {
4968 // writev
4969 var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get();
4970 return SYSCALLS.doWritev(stream, iov, iovcnt);
4971 } catch (e) {
4972 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4973 return -e.errno;
4974 }
4975 }
4976
4977 function ___syscall195(which, varargs) {SYSCALLS.varargs = varargs;
4978 try {
4979 // SYS_stat64
4980 var path = SYSCALLS.getStr(), buf = SYSCALLS.get();
4981 return SYSCALLS.doStat(FS.stat, path, buf);
4982 } catch (e) {
4983 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4984 return -e.errno;
4985 }
4986 }
4987
4988 function ___syscall196(which, varargs) {SYSCALLS.varargs = varargs;
4989 try {
4990 // SYS_lstat64
4991 var path = SYSCALLS.getStr(), buf = SYSCALLS.get();
4992 return SYSCALLS.doStat(FS.lstat, path, buf);
4993 } catch (e) {
4994 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4995 return -e.errno;
4996 }
4997 }
4998
4999 function ___syscall197(which, varargs) {SYSCALLS.varargs = varargs;
5000 try {
5001 // SYS_fstat64
5002 var stream = SYSCALLS.getStreamFromFD(), buf = SYSCALLS.get();
5003 return SYSCALLS.doStat(FS.stat, stream.path, buf);
5004 } catch (e) {
5005 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5006 return -e.errno;
5007 }
5008 }
5009
5010 function ___syscall219(which, varargs) {SYSCALLS.varargs = varargs;
5011 try {
5012 // madvise
5013 return 0; // advice is welcome, but ignored
5014 } catch (e) {
5015 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5016 return -e.errno;
5017 }
5018 }
5019
5020 function ___syscall220(which, varargs) {SYSCALLS.varargs = varargs;
5021 try {
5022 // SYS_getdents64
5023 var stream = SYSCALLS.getStreamFromFD(), dirp = SYSCALLS.get(), count = SYSCALLS.get();
5024 if (!stream.getdents) {
5025 stream.getdents = FS.readdir(stream.path);
5026 }
5027 var pos = 0;
5028 while (stream.getdents.length > 0 && pos + 268 <= count) {
5029 var id;
5030 var type;
5031 var name = stream.getdents.pop();
5032 if (name[0] === '.') {
5033 id = 1;
5034 type = 4; // DT_DIR
5035 } else {
5036 var child = FS.lookupNode(stream.node, name);
5037 id = child.id;
5038 type = FS.isChrdev(child.mode) ? 2 : // DT_CHR, character device.
5039 FS.isDir(child.mode) ? 4 : // DT_DIR, directory.
5040 FS.isLink(child.mode) ? 10 : // DT_LNK, symbolic link.
5041 8; // DT_REG, regular file.
5042 }
5043 HEAP32[((dirp + pos)>>2)]=id;
5044 HEAP32[(((dirp + pos)+(4))>>2)]=stream.position;
5045 HEAP16[(((dirp + pos)+(8))>>1)]=268;
5046 HEAP8[(((dirp + pos)+(10))>>0)]=type;
5047 stringToUTF8(name, dirp + pos + 11, 256);
5048 pos += 268;
5049 }
5050 return pos;
5051 } catch (e) {
5052 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5053 return -e.errno;
5054 }
5055 }
5056
5057 function ___syscall221(which, varargs) {SYSCALLS.varargs = varargs;
5058 try {
5059 // fcntl64
5060 var stream = SYSCALLS.getStreamFromFD(), cmd = SYSCALLS.get();
5061 switch (cmd) {
5062 case 0: {
5063 var arg = SYSCALLS.get();
5064 if (arg < 0) {
5065 return -ERRNO_CODES.EINVAL;
5066 }
5067 var newStream;
5068 newStream = FS.open(stream.path, stream.flags, 0, arg);
5069 return newStream.fd;
5070 }
5071 case 1:
5072 case 2:
5073 return 0; // FD_CLOEXEC makes no sense for a single process.
5074 case 3:
5075 return stream.flags;
5076 case 4: {
5077 var arg = SYSCALLS.get();
5078 stream.flags |= arg;
5079 return 0;
5080 }
5081 case 12:
5082 case 12: {
5083 var arg = SYSCALLS.get();
5084 var offset = 0;
5085 // We're always unlocked.
5086 HEAP16[(((arg)+(offset))>>1)]=2;
5087 return 0;
5088 }
5089 case 13:
5090 case 14:
5091 case 13:
5092 case 14:
5093 return 0; // Pretend that the locking is successful.
5094 case 16:
5095 case 8:
5096 return -ERRNO_CODES.EINVAL; // These are for sockets. We don't have them fully implemented yet.
5097 case 9:
5098 // musl trusts getown return values, due to a bug where they must be, as they overlap with errors. just return -1 here, so fnctl() returns that, and we set errno ourselves.
5099 ___setErrNo(ERRNO_CODES.EINVAL);
5100 return -1;
5101 default: {
5102 return -ERRNO_CODES.EINVAL;
5103 }
5104 }
5105 } catch (e) {
5106 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5107 return -e.errno;
5108 }
5109 }
5110
5111 function ___syscall3(which, varargs) {SYSCALLS.varargs = varargs;
5112 try {
5113 // read
5114 var stream = SYSCALLS.getStreamFromFD(), buf = SYSCALLS.get(), count = SYSCALLS.get();
5115 return FS.read(stream, HEAP8,buf, count);
5116 } catch (e) {
5117 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5118 return -e.errno;
5119 }
5120 }
5121
5122 function ___syscall33(which, varargs) {SYSCALLS.varargs = varargs;
5123 try {
5124 // access
5125 var path = SYSCALLS.getStr(), amode = SYSCALLS.get();
5126 return SYSCALLS.doAccess(path, amode);
5127 } catch (e) {
5128 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5129 return -e.errno;
5130 }
5131 }
5132
5133 function ___syscall38(which, varargs) {SYSCALLS.varargs = varargs;
5134 try {
5135 // rename
5136 var old_path = SYSCALLS.getStr(), new_path = SYSCALLS.getStr();
5137 FS.rename(old_path, new_path);
5138 return 0;
5139 } catch (e) {
5140 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5141 return -e.errno;
5142 }
5143 }
5144
5145 function ___syscall4(which, varargs) {SYSCALLS.varargs = varargs;
5146 try {
5147 // write
5148 var stream = SYSCALLS.getStreamFromFD(), buf = SYSCALLS.get(), count = SYSCALLS.get();
5149 return FS.write(stream, HEAP8,buf, count);
5150 } catch (e) {
5151 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5152 return -e.errno;
5153 }
5154 }
5155
5156 function ___syscall40(which, varargs) {SYSCALLS.varargs = varargs;
5157 try {
5158 // rmdir
5159 var path = SYSCALLS.getStr();
5160 FS.rmdir(path);
5161 return 0;
5162 } catch (e) {
5163 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5164 return -e.errno;
5165 }
5166 }
5167
5168 function ___syscall5(which, varargs) {SYSCALLS.varargs = varargs;
5169 try {
5170 // open
5171 var pathname = SYSCALLS.getStr(), flags = SYSCALLS.get(), mode = SYSCALLS.get() // optional TODO
5172 var stream = FS.open(pathname, flags, mode);
5173 return stream.fd;
5174 } catch (e) {
5175 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5176 return -e.errno;
5177 }
5178 }
5179
5180 function ___syscall54(which, varargs) {SYSCALLS.varargs = varargs;
5181 try {
5182 // ioctl
5183 var stream = SYSCALLS.getStreamFromFD(), op = SYSCALLS.get();
5184 switch (op) {
5185 case 21509:
5186 case 21505: {
5187 if (!stream.tty) return -ERRNO_CODES.ENOTTY;
5188 return 0;
5189 }
5190 case 21510:
5191 case 21511:
5192 case 21512:
5193 case 21506:
5194 case 21507:
5195 case 21508: {
5196 if (!stream.tty) return -ERRNO_CODES.ENOTTY;
5197 return 0; // no-op, not actually adjusting terminal settings
5198 }
5199 case 21519: {
5200 if (!stream.tty) return -ERRNO_CODES.ENOTTY;
5201 var argp = SYSCALLS.get();
5202 HEAP32[((argp)>>2)]=0;
5203 return 0;
5204 }
5205 case 21520: {
5206 if (!stream.tty) return -ERRNO_CODES.ENOTTY;
5207 return -ERRNO_CODES.EINVAL; // not supported
5208 }
5209 case 21531: {
5210 var argp = SYSCALLS.get();
5211 return FS.ioctl(stream, op, argp);
5212 }
5213 case 21523: {
5214 // TODO: in theory we should write to the winsize struct that gets
5215 // passed in, but for now musl doesn't read anything on it
5216 if (!stream.tty) return -ERRNO_CODES.ENOTTY;
5217 return 0;
5218 }
5219 default: abort('bad ioctl syscall ' + op);
5220 }
5221 } catch (e) {
5222 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5223 return -e.errno;
5224 }
5225 }
5226
5227 function ___syscall6(which, varargs) {SYSCALLS.varargs = varargs;
5228 try {
5229 // close
5230 var stream = SYSCALLS.getStreamFromFD();
5231 FS.close(stream);
5232 return 0;
5233 } catch (e) {
5234 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
5235 return -e.errno;
5236 }
5237 }
5238
5239 function ___unlock() {}
5240
5241 function _abort() {
5242 Module['abort']();
5243 }
5244
5245 function _clock() {
5246 if (_clock.start === undefined) _clock.start = Date.now();
5247 return ((Date.now() - _clock.start) * (1000000 / 1000))|0;
5248 }
5249
5250
5251 function _emscripten_get_now() { abort() }
5252
5253 function _emscripten_get_now_is_monotonic() {
5254 // return whether emscripten_get_now is guaranteed monotonic; the Date.now
5255 // implementation is not :(
5256 return ENVIRONMENT_IS_NODE || (typeof dateNow !== 'undefined') ||
5257 ((ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && self['performance'] && self['performance']['now']);
5258 }function _clock_gettime(clk_id, tp) {
5259 // int clock_gettime(clockid_t clk_id, struct timespec *tp);
5260 var now;
5261 if (clk_id === 0) {
5262 now = Date.now();
5263 } else if (clk_id === 1 && _emscripten_get_now_is_monotonic()) {
5264 now = _emscripten_get_now();
5265 } else {
5266 ___setErrNo(ERRNO_CODES.EINVAL);
5267 return -1;
5268 }
5269 HEAP32[((tp)>>2)]=(now/1000)|0; // seconds
5270 HEAP32[(((tp)+(4))>>2)]=((now % 1000)*1000*1000)|0; // nanoseconds
5271 return 0;
5272 }
5273
5274
5275 function __exit(status) {
5276 // void _exit(int status);
5277 // http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html
5278 Module['exit'](status);
5279 }function _exit(status) {
5280 __exit(status);
5281 }
5282
5283 var _fabs=Math_abs;
5284
5285
5286
5287
5288
5289 var _environ=STATICTOP; STATICTOP += 16;;var ___environ=_environ;function ___buildEnvironment(env) {
5290 // WARNING: Arbitrary limit!
5291 var MAX_ENV_VALUES = 64;
5292 var TOTAL_ENV_SIZE = 1024;
5293
5294 // Statically allocate memory for the environment.
5295 var poolPtr;
5296 var envPtr;
5297 if (!___buildEnvironment.called) {
5298 ___buildEnvironment.called = true;
5299 // Set default values. Use string keys for Closure Compiler compatibility.
5300 ENV['USER'] = ENV['LOGNAME'] = 'web_user';
5301 ENV['PATH'] = '/';
5302 ENV['PWD'] = '/';
5303 ENV['HOME'] = '/home/web_user';
5304 ENV['LANG'] = 'C.UTF-8';
5305 ENV['_'] = Module['thisProgram'];
5306 // Allocate memory.
5307 poolPtr = staticAlloc(TOTAL_ENV_SIZE);
5308 envPtr = staticAlloc(MAX_ENV_VALUES * 4);
5309 HEAP32[((envPtr)>>2)]=poolPtr;
5310 HEAP32[((_environ)>>2)]=envPtr;
5311 } else {
5312 envPtr = HEAP32[((_environ)>>2)];
5313 poolPtr = HEAP32[((envPtr)>>2)];
5314 }
5315
5316 // Collect key=value lines.
5317 var strings = [];
5318 var totalSize = 0;
5319 for (var key in env) {
5320 if (typeof env[key] === 'string') {
5321 var line = key + '=' + env[key];
5322 strings.push(line);
5323 totalSize += line.length;
5324 }
5325 }
5326 if (totalSize > TOTAL_ENV_SIZE) {
5327 throw new Error('Environment size exceeded TOTAL_ENV_SIZE!');
5328 }
5329
5330 // Make new.
5331 var ptrSize = 4;
5332 for (var i = 0; i < strings.length; i++) {
5333 var line = strings[i];
5334 writeAsciiToMemory(line, poolPtr);
5335 HEAP32[(((envPtr)+(i * ptrSize))>>2)]=poolPtr;
5336 poolPtr += line.length + 1;
5337 }
5338 HEAP32[(((envPtr)+(strings.length * ptrSize))>>2)]=0;
5339 }var ENV={};function _getenv(name) {
5340 // char *getenv(const char *name);
5341 // http://pubs.opengroup.org/onlinepubs/009695399/functions/getenv.html
5342 if (name === 0) return 0;
5343 name = Pointer_stringify(name);
5344 if (!ENV.hasOwnProperty(name)) return 0;
5345
5346 if (_getenv.ret) _free(_getenv.ret);
5347 _getenv.ret = allocateUTF8(ENV[name]);
5348 return _getenv.ret;
5349 }
5350
5351 function _gettimeofday(ptr) {
5352 var now = Date.now();
5353 HEAP32[((ptr)>>2)]=(now/1000)|0; // seconds
5354 HEAP32[(((ptr)+(4))>>2)]=((now % 1000)*1000)|0; // microseconds
5355 return 0;
5356 }
5357
5358
5359 var ___tm_timezone=allocate(intArrayFromString("GMT"), "i8", ALLOC_STATIC);function _gmtime_r(time, tmPtr) {
5360 var date = new Date(HEAP32[((time)>>2)]*1000);
5361 HEAP32[((tmPtr)>>2)]=date.getUTCSeconds();
5362 HEAP32[(((tmPtr)+(4))>>2)]=date.getUTCMinutes();
5363 HEAP32[(((tmPtr)+(8))>>2)]=date.getUTCHours();
5364 HEAP32[(((tmPtr)+(12))>>2)]=date.getUTCDate();
5365 HEAP32[(((tmPtr)+(16))>>2)]=date.getUTCMonth();
5366 HEAP32[(((tmPtr)+(20))>>2)]=date.getUTCFullYear()-1900;
5367 HEAP32[(((tmPtr)+(24))>>2)]=date.getUTCDay();
5368 HEAP32[(((tmPtr)+(36))>>2)]=0;
5369 HEAP32[(((tmPtr)+(32))>>2)]=0;
5370 var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
5371 var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0;
5372 HEAP32[(((tmPtr)+(28))>>2)]=yday;
5373 HEAP32[(((tmPtr)+(40))>>2)]=___tm_timezone;
5374
5375 return tmPtr;
5376 }
5377
5378
5379
5380
5381
5382 var _llvm_ceil_f32=Math_ceil;
5383
5384 var _llvm_ceil_f64=Math_ceil;
5385
5386 var _llvm_ctlz_i32=true;
5387
5388 var cttz_i8 = allocate([8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0], "i8", ALLOC_STATIC);function _llvm_cttz_i32(x) {
5389 x = x|0;
5390 var ret = 0;
5391 ret = ((HEAP8[(((cttz_i8)+(x & 0xff))>>0)])|0);
5392 if ((ret|0) < 8) return ret|0;
5393 ret = ((HEAP8[(((cttz_i8)+((x >> 8)&0xff))>>0)])|0);
5394 if ((ret|0) < 8) return (ret + 8)|0;
5395 ret = ((HEAP8[(((cttz_i8)+((x >> 16)&0xff))>>0)])|0);
5396 if ((ret|0) < 8) return (ret + 16)|0;
5397 return (((HEAP8[(((cttz_i8)+(x >>> 24))>>0)])|0) + 24)|0;
5398 }
5399
5400 function _llvm_exp2_f32(x) {
5401 return Math.pow(2, x);
5402 }
5403
5404 function _llvm_exp2_f64() {
5405 return _llvm_exp2_f32.apply(null, arguments)
5406 }
5407
5408 var _llvm_fabs_f32=Math_abs;
5409
5410 var _llvm_fabs_f64=Math_abs;
5411
5412 var _llvm_floor_f32=Math_floor;
5413
5414 var _llvm_floor_f64=Math_floor;
5415
5416 var _llvm_pow_f32=Math_pow;
5417
5418 var _llvm_pow_f64=Math_pow;
5419
5420
5421
5422
5423
5424
5425
5426
5427 var _llvm_sqrt_f32=Math_sqrt;
5428
5429 var _llvm_sqrt_f64=Math_sqrt;
5430
5431 var _llvm_trunc_f64=Math_trunc;
5432
5433
5434
5435 var _tzname=STATICTOP; STATICTOP += 16;;
5436
5437 var _daylight=STATICTOP; STATICTOP += 16;;
5438
5439 var _timezone=STATICTOP; STATICTOP += 16;;function _tzset() {
5440 // TODO: Use (malleable) environment variables instead of system settings.
5441 if (_tzset.called) return;
5442 _tzset.called = true;
5443
5444 // timezone is specified as seconds west of UTC ("The external variable
5445 // `timezone` shall be set to the difference, in seconds, between
5446 // Coordinated Universal Time (UTC) and local standard time."), the same
5447 // as returned by getTimezoneOffset().
5448 // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html
5449 HEAP32[((_timezone)>>2)]=(new Date()).getTimezoneOffset() * 60;
5450
5451 var winter = new Date(2000, 0, 1);
5452 var summer = new Date(2000, 6, 1);
5453 HEAP32[((_daylight)>>2)]=Number(winter.getTimezoneOffset() != summer.getTimezoneOffset());
5454
5455 function extractZone(date) {
5456 var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
5457 return match ? match[1] : "GMT";
5458 };
5459 var winterName = extractZone(winter);
5460 var summerName = extractZone(summer);
5461 var winterNamePtr = allocate(intArrayFromString(winterName), 'i8', ALLOC_NORMAL);
5462 var summerNamePtr = allocate(intArrayFromString(summerName), 'i8', ALLOC_NORMAL);
5463 if (summer.getTimezoneOffset() < winter.getTimezoneOffset()) {
5464 // Northern hemisphere
5465 HEAP32[((_tzname)>>2)]=winterNamePtr;
5466 HEAP32[(((_tzname)+(4))>>2)]=summerNamePtr;
5467 } else {
5468 HEAP32[((_tzname)>>2)]=summerNamePtr;
5469 HEAP32[(((_tzname)+(4))>>2)]=winterNamePtr;
5470 }
5471 }function _localtime_r(time, tmPtr) {
5472 _tzset();
5473 var date = new Date(HEAP32[((time)>>2)]*1000);
5474 HEAP32[((tmPtr)>>2)]=date.getSeconds();
5475 HEAP32[(((tmPtr)+(4))>>2)]=date.getMinutes();
5476 HEAP32[(((tmPtr)+(8))>>2)]=date.getHours();
5477 HEAP32[(((tmPtr)+(12))>>2)]=date.getDate();
5478 HEAP32[(((tmPtr)+(16))>>2)]=date.getMonth();
5479 HEAP32[(((tmPtr)+(20))>>2)]=date.getFullYear()-1900;
5480 HEAP32[(((tmPtr)+(24))>>2)]=date.getDay();
5481
5482 var start = new Date(date.getFullYear(), 0, 1);
5483 var yday = ((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))|0;
5484 HEAP32[(((tmPtr)+(28))>>2)]=yday;
5485 HEAP32[(((tmPtr)+(36))>>2)]=-(date.getTimezoneOffset() * 60);
5486
5487 // Attention: DST is in December in South, and some regions don't have DST at all.
5488 var summerOffset = new Date(2000, 6, 1).getTimezoneOffset();
5489 var winterOffset = start.getTimezoneOffset();
5490 var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0;
5491 HEAP32[(((tmPtr)+(32))>>2)]=dst;
5492
5493 var zonePtr = HEAP32[(((_tzname)+(dst ? 4 : 0))>>2)];
5494 HEAP32[(((tmPtr)+(40))>>2)]=zonePtr;
5495
5496 return tmPtr;
5497 }
5498
5499
5500 function _emscripten_memcpy_big(dest, src, num) {
5501 HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
5502 return dest;
5503 }
5504
5505
5506
5507
5508
5509 function _mktime(tmPtr) {
5510 _tzset();
5511 var date = new Date(HEAP32[(((tmPtr)+(20))>>2)] + 1900,
5512 HEAP32[(((tmPtr)+(16))>>2)],
5513 HEAP32[(((tmPtr)+(12))>>2)],
5514 HEAP32[(((tmPtr)+(8))>>2)],
5515 HEAP32[(((tmPtr)+(4))>>2)],
5516 HEAP32[((tmPtr)>>2)],
5517 0);
5518
5519 // There's an ambiguous hour when the time goes back; the tm_isdst field is
5520 // used to disambiguate it. Date() basically guesses, so we fix it up if it
5521 // guessed wrong, or fill in tm_isdst with the guess if it's -1.
5522 var dst = HEAP32[(((tmPtr)+(32))>>2)];
5523 var guessedOffset = date.getTimezoneOffset();
5524 var start = new Date(date.getFullYear(), 0, 1);
5525 var summerOffset = new Date(2000, 6, 1).getTimezoneOffset();
5526 var winterOffset = start.getTimezoneOffset();
5527 var dstOffset = Math.min(winterOffset, summerOffset); // DST is in December in South
5528 if (dst < 0) {
5529 // Attention: some regions don't have DST at all.
5530 HEAP32[(((tmPtr)+(32))>>2)]=Number(summerOffset != winterOffset && dstOffset == guessedOffset);
5531 } else if ((dst > 0) != (dstOffset == guessedOffset)) {
5532 var nonDstOffset = Math.max(winterOffset, summerOffset);
5533 var trueOffset = dst > 0 ? dstOffset : nonDstOffset;
5534 // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.
5535 date.setTime(date.getTime() + (trueOffset - guessedOffset)*60000);
5536 }
5537
5538 HEAP32[(((tmPtr)+(24))>>2)]=date.getDay();
5539 var yday = ((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))|0;
5540 HEAP32[(((tmPtr)+(28))>>2)]=yday;
5541
5542 return (date.getTime() / 1000)|0;
5543 }
5544
5545
5546 function _usleep(useconds) {
5547 // int usleep(useconds_t useconds);
5548 // http://pubs.opengroup.org/onlinepubs/000095399/functions/usleep.html
5549 // We're single-threaded, so use a busy loop. Super-ugly.
5550 var msec = useconds / 1000;
5551 if ((ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && self['performance'] && self['performance']['now']) {
5552 var start = self['performance']['now']();
5553 while (self['performance']['now']() - start < msec) {
5554 // Do nothing.
5555 }
5556 } else {
5557 var start = Date.now();
5558 while (Date.now() - start < msec) {
5559 // Do nothing.
5560 }
5561 }
5562 return 0;
5563 }function _nanosleep(rqtp, rmtp) {
5564 // int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
5565 var seconds = HEAP32[((rqtp)>>2)];
5566 var nanoseconds = HEAP32[(((rqtp)+(4))>>2)];
5567 if (rmtp !== 0) {
5568 HEAP32[((rmtp)>>2)]=0;
5569 HEAP32[(((rmtp)+(4))>>2)]=0;
5570 }
5571 return _usleep((seconds * 1e6) + (nanoseconds / 1000));
5572 }
5573
5574
5575
5576
5577
5578
5579 function __isLeapYear(year) {
5580 return year%4 === 0 && (year%100 !== 0 || year%400 === 0);
5581 }
5582
5583 function __arraySum(array, index) {
5584 var sum = 0;
5585 for (var i = 0; i <= index; sum += array[i++]);
5586 return sum;
5587 }
5588
5589
5590 var __MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];
5591
5592 var __MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];function __addDays(date, days) {
5593 var newDate = new Date(date.getTime());
5594 while(days > 0) {
5595 var leap = __isLeapYear(newDate.getFullYear());
5596 var currentMonth = newDate.getMonth();
5597 var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth];
5598
5599 if (days > daysInCurrentMonth-newDate.getDate()) {
5600 // we spill over to next month
5601 days -= (daysInCurrentMonth-newDate.getDate()+1);
5602 newDate.setDate(1);
5603 if (currentMonth < 11) {
5604 newDate.setMonth(currentMonth+1)
5605 } else {
5606 newDate.setMonth(0);
5607 newDate.setFullYear(newDate.getFullYear()+1);
5608 }
5609 } else {
5610 // we stay in current month
5611 newDate.setDate(newDate.getDate()+days);
5612 return newDate;
5613 }
5614 }
5615
5616 return newDate;
5617 }function _strftime(s, maxsize, format, tm) {
5618 // size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr);
5619 // http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
5620
5621 var tm_zone = HEAP32[(((tm)+(40))>>2)];
5622
5623 var date = {
5624 tm_sec: HEAP32[((tm)>>2)],
5625 tm_min: HEAP32[(((tm)+(4))>>2)],
5626 tm_hour: HEAP32[(((tm)+(8))>>2)],
5627 tm_mday: HEAP32[(((tm)+(12))>>2)],
5628 tm_mon: HEAP32[(((tm)+(16))>>2)],
5629 tm_year: HEAP32[(((tm)+(20))>>2)],
5630 tm_wday: HEAP32[(((tm)+(24))>>2)],
5631 tm_yday: HEAP32[(((tm)+(28))>>2)],
5632 tm_isdst: HEAP32[(((tm)+(32))>>2)],
5633 tm_gmtoff: HEAP32[(((tm)+(36))>>2)],
5634 tm_zone: tm_zone ? Pointer_stringify(tm_zone) : ''
5635 };
5636
5637 var pattern = Pointer_stringify(format);
5638
5639 // expand format
5640 var EXPANSION_RULES_1 = {
5641 '%c': '%a %b %d %H:%M:%S %Y', // Replaced by the locale's appropriate date and time representation - e.g., Mon Aug 3 14:02:01 2013
5642 '%D': '%m/%d/%y', // Equivalent to %m / %d / %y
5643 '%F': '%Y-%m-%d', // Equivalent to %Y - %m - %d
5644 '%h': '%b', // Equivalent to %b
5645 '%r': '%I:%M:%S %p', // Replaced by the time in a.m. and p.m. notation
5646 '%R': '%H:%M', // Replaced by the time in 24-hour notation
5647 '%T': '%H:%M:%S', // Replaced by the time
5648 '%x': '%m/%d/%y', // Replaced by the locale's appropriate date representation
5649 '%X': '%H:%M:%S' // Replaced by the locale's appropriate date representation
5650 };
5651 for (var rule in EXPANSION_RULES_1) {
5652 pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_1[rule]);
5653 }
5654
5655 var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
5656 var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
5657
5658 function leadingSomething(value, digits, character) {
5659 var str = typeof value === 'number' ? value.toString() : (value || '');
5660 while (str.length < digits) {
5661 str = character[0]+str;
5662 }
5663 return str;
5664 };
5665
5666 function leadingNulls(value, digits) {
5667 return leadingSomething(value, digits, '0');
5668 };
5669
5670 function compareByDay(date1, date2) {
5671 function sgn(value) {
5672 return value < 0 ? -1 : (value > 0 ? 1 : 0);
5673 };
5674
5675 var compare;
5676 if ((compare = sgn(date1.getFullYear()-date2.getFullYear())) === 0) {
5677 if ((compare = sgn(date1.getMonth()-date2.getMonth())) === 0) {
5678 compare = sgn(date1.getDate()-date2.getDate());
5679 }
5680 }
5681 return compare;
5682 };
5683
5684 function getFirstWeekStartDate(janFourth) {
5685 switch (janFourth.getDay()) {
5686 case 0: // Sunday
5687 return new Date(janFourth.getFullYear()-1, 11, 29);
5688 case 1: // Monday
5689 return janFourth;
5690 case 2: // Tuesday
5691 return new Date(janFourth.getFullYear(), 0, 3);
5692 case 3: // Wednesday
5693 return new Date(janFourth.getFullYear(), 0, 2);
5694 case 4: // Thursday
5695 return new Date(janFourth.getFullYear(), 0, 1);
5696 case 5: // Friday
5697 return new Date(janFourth.getFullYear()-1, 11, 31);
5698 case 6: // Saturday
5699 return new Date(janFourth.getFullYear()-1, 11, 30);
5700 }
5701 };
5702
5703 function getWeekBasedYear(date) {
5704 var thisDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday);
5705
5706 var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4);
5707 var janFourthNextYear = new Date(thisDate.getFullYear()+1, 0, 4);
5708
5709 var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
5710 var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
5711
5712 if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) {
5713 // this date is after the start of the first week of this year
5714 if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) {
5715 return thisDate.getFullYear()+1;
5716 } else {
5717 return thisDate.getFullYear();
5718 }
5719 } else {
5720 return thisDate.getFullYear()-1;
5721 }
5722 };
5723
5724 var EXPANSION_RULES_2 = {
5725 '%a': function(date) {
5726 return WEEKDAYS[date.tm_wday].substring(0,3);
5727 },
5728 '%A': function(date) {
5729 return WEEKDAYS[date.tm_wday];
5730 },
5731 '%b': function(date) {
5732 return MONTHS[date.tm_mon].substring(0,3);
5733 },
5734 '%B': function(date) {
5735 return MONTHS[date.tm_mon];
5736 },
5737 '%C': function(date) {
5738 var year = date.tm_year+1900;
5739 return leadingNulls((year/100)|0,2);
5740 },
5741 '%d': function(date) {
5742 return leadingNulls(date.tm_mday, 2);
5743 },
5744 '%e': function(date) {
5745 return leadingSomething(date.tm_mday, 2, ' ');
5746 },
5747 '%g': function(date) {
5748 // %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year.
5749 // In this system, weeks begin on a Monday and week 1 of the year is the week that includes
5750 // January 4th, which is also the week that includes the first Thursday of the year, and
5751 // is also the first week that contains at least four days in the year.
5752 // If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of
5753 // the last week of the preceding year; thus, for Saturday 2nd January 1999,
5754 // %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th,
5755 // or 31st is a Monday, it and any following days are part of week 1 of the following year.
5756 // Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.
5757
5758 return getWeekBasedYear(date).toString().substring(2);
5759 },
5760 '%G': function(date) {
5761 return getWeekBasedYear(date);
5762 },
5763 '%H': function(date) {
5764 return leadingNulls(date.tm_hour, 2);
5765 },
5766 '%I': function(date) {
5767 var twelveHour = date.tm_hour;
5768 if (twelveHour == 0) twelveHour = 12;
5769 else if (twelveHour > 12) twelveHour -= 12;
5770 return leadingNulls(twelveHour, 2);
5771 },
5772 '%j': function(date) {
5773 // Day of the year (001-366)
5774 return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon-1), 3);
5775 },
5776 '%m': function(date) {
5777 return leadingNulls(date.tm_mon+1, 2);
5778 },
5779 '%M': function(date) {
5780 return leadingNulls(date.tm_min, 2);
5781 },
5782 '%n': function() {
5783 return '\n';
5784 },
5785 '%p': function(date) {
5786 if (date.tm_hour >= 0 && date.tm_hour < 12) {
5787 return 'AM';
5788 } else {
5789 return 'PM';
5790 }
5791 },
5792 '%S': function(date) {
5793 return leadingNulls(date.tm_sec, 2);
5794 },
5795 '%t': function() {
5796 return '\t';
5797 },
5798 '%u': function(date) {
5799 var day = new Date(date.tm_year+1900, date.tm_mon+1, date.tm_mday, 0, 0, 0, 0);
5800 return day.getDay() || 7;
5801 },
5802 '%U': function(date) {
5803 // Replaced by the week number of the year as a decimal number [00,53].
5804 // The first Sunday of January is the first day of week 1;
5805 // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
5806 var janFirst = new Date(date.tm_year+1900, 0, 1);
5807 var firstSunday = janFirst.getDay() === 0 ? janFirst : __addDays(janFirst, 7-janFirst.getDay());
5808 var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday);
5809
5810 // is target date after the first Sunday?
5811 if (compareByDay(firstSunday, endDate) < 0) {
5812 // calculate difference in days between first Sunday and endDate
5813 var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31;
5814 var firstSundayUntilEndJanuary = 31-firstSunday.getDate();
5815 var days = firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();
5816 return leadingNulls(Math.ceil(days/7), 2);
5817 }
5818
5819 return compareByDay(firstSunday, janFirst) === 0 ? '01': '00';
5820 },
5821 '%V': function(date) {
5822 // Replaced by the week number of the year (Monday as the first day of the week)
5823 // as a decimal number [01,53]. If the week containing 1 January has four
5824 // or more days in the new year, then it is considered week 1.
5825 // Otherwise, it is the last week of the previous year, and the next week is week 1.
5826 // Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]
5827 var janFourthThisYear = new Date(date.tm_year+1900, 0, 4);
5828 var janFourthNextYear = new Date(date.tm_year+1901, 0, 4);
5829
5830 var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
5831 var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
5832
5833 var endDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday);
5834
5835 if (compareByDay(endDate, firstWeekStartThisYear) < 0) {
5836 // if given date is before this years first week, then it belongs to the 53rd week of last year
5837 return '53';
5838 }
5839
5840 if (compareByDay(firstWeekStartNextYear, endDate) <= 0) {
5841 // if given date is after next years first week, then it belongs to the 01th week of next year
5842 return '01';
5843 }
5844
5845 // given date is in between CW 01..53 of this calendar year
5846 var daysDifference;
5847 if (firstWeekStartThisYear.getFullYear() < date.tm_year+1900) {
5848 // first CW of this year starts last year
5849 daysDifference = date.tm_yday+32-firstWeekStartThisYear.getDate()
5850 } else {
5851 // first CW of this year starts this year
5852 daysDifference = date.tm_yday+1-firstWeekStartThisYear.getDate();
5853 }
5854 return leadingNulls(Math.ceil(daysDifference/7), 2);
5855 },
5856 '%w': function(date) {
5857 var day = new Date(date.tm_year+1900, date.tm_mon+1, date.tm_mday, 0, 0, 0, 0);
5858 return day.getDay();
5859 },
5860 '%W': function(date) {
5861 // Replaced by the week number of the year as a decimal number [00,53].
5862 // The first Monday of January is the first day of week 1;
5863 // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
5864 var janFirst = new Date(date.tm_year, 0, 1);
5865 var firstMonday = janFirst.getDay() === 1 ? janFirst : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7-janFirst.getDay()+1);
5866 var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday);
5867
5868 // is target date after the first Monday?
5869 if (compareByDay(firstMonday, endDate) < 0) {
5870 var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31;
5871 var firstMondayUntilEndJanuary = 31-firstMonday.getDate();
5872 var days = firstMondayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();
5873 return leadingNulls(Math.ceil(days/7), 2);
5874 }
5875 return compareByDay(firstMonday, janFirst) === 0 ? '01': '00';
5876 },
5877 '%y': function(date) {
5878 // Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]
5879 return (date.tm_year+1900).toString().substring(2);
5880 },
5881 '%Y': function(date) {
5882 // Replaced by the year as a decimal number (for example, 1997). [ tm_year]
5883 return date.tm_year+1900;
5884 },
5885 '%z': function(date) {
5886 // Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ).
5887 // For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich).
5888 var off = date.tm_gmtoff;
5889 var ahead = off >= 0;
5890 off = Math.abs(off) / 60;
5891 // convert from minutes into hhmm format (which means 60 minutes = 100 units)
5892 off = (off / 60)*100 + (off % 60);
5893 return (ahead ? '+' : '-') + String("0000" + off).slice(-4);
5894 },
5895 '%Z': function(date) {
5896 return date.tm_zone;
5897 },
5898 '%%': function() {
5899 return '%';
5900 }
5901 };
5902 for (var rule in EXPANSION_RULES_2) {
5903 if (pattern.indexOf(rule) >= 0) {
5904 pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_2[rule](date));
5905 }
5906 }
5907
5908 var bytes = intArrayFromString(pattern, false);
5909 if (bytes.length > maxsize) {
5910 return 0;
5911 }
5912
5913 writeArrayToMemory(bytes, s);
5914 return bytes.length-1;
5915 }
5916FS.staticInit();__ATINIT__.unshift(function() { if (!Module["noFSInit"] && !FS.init.initialized) FS.init() });__ATMAIN__.push(function() { FS.ignorePermissions = false });__ATEXIT__.push(function() { FS.quit() });;
5917__ATINIT__.unshift(function() { TTY.init() });__ATEXIT__.push(function() { TTY.shutdown() });;
5918if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); var NODEJS_PATH = require("path"); NODEFS.staticInit(); };
5919if (ENVIRONMENT_IS_NODE) {
5920 _emscripten_get_now = function _emscripten_get_now_actual() {
5921 var t = process['hrtime']();
5922 return t[0] * 1e3 + t[1] / 1e6;
5923 };
5924 } else if (typeof dateNow !== 'undefined') {
5925 _emscripten_get_now = dateNow;
5926 } else if (typeof self === 'object' && self['performance'] && typeof self['performance']['now'] === 'function') {
5927 _emscripten_get_now = function() { return self['performance']['now'](); };
5928 } else if (typeof performance === 'object' && typeof performance['now'] === 'function') {
5929 _emscripten_get_now = function() { return performance['now'](); };
5930 } else {
5931 _emscripten_get_now = Date.now;
5932 };
5933___buildEnvironment(ENV);;
5934DYNAMICTOP_PTR = staticAlloc(4);
5935
5936STACK_BASE = STACKTOP = alignMemory(STATICTOP);
5937
5938STACK_MAX = STACK_BASE + TOTAL_STACK;
5939
5940DYNAMIC_BASE = alignMemory(STACK_MAX);
5941
5942HEAP32[DYNAMICTOP_PTR>>2] = DYNAMIC_BASE;
5943
5944staticSealed = true; // seal the static portion of memory
5945
5946assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
5947
5948var ASSERTIONS = true;
5949
5950/** @type {function(string, boolean=, number=)} */
5951function intArrayFromString(stringy, dontAddNull, length) {
5952 var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
5953 var u8array = new Array(len);
5954 var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
5955 if (dontAddNull) u8array.length = numBytesWritten;
5956 return u8array;
5957}
5958
5959function intArrayToString(array) {
5960 var ret = [];
5961 for (var i = 0; i < array.length; i++) {
5962 var chr = array[i];
5963 if (chr > 0xFF) {
5964 if (ASSERTIONS) {
5965 assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
5966 }
5967 chr &= 0xFF;
5968 }
5969 ret.push(String.fromCharCode(chr));
5970 }
5971 return ret.join('');
5972}
5973
5974
5975
5976function nullFunc_dd(x) { Module["printErr"]("Invalid function pointer called with signature 'dd'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5977
5978function nullFunc_did(x) { Module["printErr"]("Invalid function pointer called with signature 'did'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5979
5980function nullFunc_didd(x) { Module["printErr"]("Invalid function pointer called with signature 'didd'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5981
5982function nullFunc_fiii(x) { Module["printErr"]("Invalid function pointer called with signature 'fiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5983
5984function nullFunc_ii(x) { Module["printErr"]("Invalid function pointer called with signature 'ii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5985
5986function nullFunc_iii(x) { Module["printErr"]("Invalid function pointer called with signature 'iii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5987
5988function nullFunc_iiifii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiifii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5989
5990function nullFunc_iiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5991
5992function nullFunc_iiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5993
5994function nullFunc_iiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5995
5996function nullFunc_iiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5997
5998function nullFunc_iiiiiiidiiddii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiiiidiiddii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
5999
6000function nullFunc_iiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6001
6002function nullFunc_iiiiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6003
6004function nullFunc_iiiiij(x) { Module["printErr"]("Invalid function pointer called with signature 'iiiiij'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6005
6006function nullFunc_iij(x) { Module["printErr"]("Invalid function pointer called with signature 'iij'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6007
6008function nullFunc_jii(x) { Module["printErr"]("Invalid function pointer called with signature 'jii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6009
6010function nullFunc_jiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'jiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6011
6012function nullFunc_jiiji(x) { Module["printErr"]("Invalid function pointer called with signature 'jiiji'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6013
6014function nullFunc_jij(x) { Module["printErr"]("Invalid function pointer called with signature 'jij'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6015
6016function nullFunc_jiji(x) { Module["printErr"]("Invalid function pointer called with signature 'jiji'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6017
6018function nullFunc_vi(x) { Module["printErr"]("Invalid function pointer called with signature 'vi'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6019
6020function nullFunc_vii(x) { Module["printErr"]("Invalid function pointer called with signature 'vii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6021
6022function nullFunc_viidi(x) { Module["printErr"]("Invalid function pointer called with signature 'viidi'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6023
6024function nullFunc_viifi(x) { Module["printErr"]("Invalid function pointer called with signature 'viifi'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6025
6026function nullFunc_viii(x) { Module["printErr"]("Invalid function pointer called with signature 'viii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6027
6028function nullFunc_viiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6029
6030function nullFunc_viiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6031
6032function nullFunc_viiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6033
6034function nullFunc_viiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6035
6036function nullFunc_viiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6037
6038function nullFunc_viiiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6039
6040function nullFunc_viiiiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6041
6042function nullFunc_viiiiiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6043
6044function nullFunc_viiiiiiiiiiii(x) { Module["printErr"]("Invalid function pointer called with signature 'viiiiiiiiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6045
6046function nullFunc_viiijj(x) { Module["printErr"]("Invalid function pointer called with signature 'viiijj'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)"); Module["printErr"]("Build with ASSERTIONS=2 for more info.");abort(x) }
6047
6048Module['wasmTableSize'] = 44932;
6049
6050Module['wasmMaxTableSize'] = 44932;
6051
6052function invoke_dd(index,a1) {
6053 try {
6054 return Module["dynCall_dd"](index,a1);
6055 } catch(e) {
6056 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6057 Module["setThrew"](1, 0);
6058 }
6059}
6060
6061function invoke_did(index,a1,a2) {
6062 try {
6063 return Module["dynCall_did"](index,a1,a2);
6064 } catch(e) {
6065 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6066 Module["setThrew"](1, 0);
6067 }
6068}
6069
6070function invoke_didd(index,a1,a2,a3) {
6071 try {
6072 return Module["dynCall_didd"](index,a1,a2,a3);
6073 } catch(e) {
6074 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6075 Module["setThrew"](1, 0);
6076 }
6077}
6078
6079function invoke_fiii(index,a1,a2,a3) {
6080 try {
6081 return Module["dynCall_fiii"](index,a1,a2,a3);
6082 } catch(e) {
6083 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6084 Module["setThrew"](1, 0);
6085 }
6086}
6087
6088function invoke_ii(index,a1) {
6089 try {
6090 return Module["dynCall_ii"](index,a1);
6091 } catch(e) {
6092 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6093 Module["setThrew"](1, 0);
6094 }
6095}
6096
6097function invoke_iii(index,a1,a2) {
6098 try {
6099 return Module["dynCall_iii"](index,a1,a2);
6100 } catch(e) {
6101 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6102 Module["setThrew"](1, 0);
6103 }
6104}
6105
6106function invoke_iiifii(index,a1,a2,a3,a4,a5) {
6107 try {
6108 return Module["dynCall_iiifii"](index,a1,a2,a3,a4,a5);
6109 } catch(e) {
6110 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6111 Module["setThrew"](1, 0);
6112 }
6113}
6114
6115function invoke_iiii(index,a1,a2,a3) {
6116 try {
6117 return Module["dynCall_iiii"](index,a1,a2,a3);
6118 } catch(e) {
6119 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6120 Module["setThrew"](1, 0);
6121 }
6122}
6123
6124function invoke_iiiii(index,a1,a2,a3,a4) {
6125 try {
6126 return Module["dynCall_iiiii"](index,a1,a2,a3,a4);
6127 } catch(e) {
6128 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6129 Module["setThrew"](1, 0);
6130 }
6131}
6132
6133function invoke_iiiiii(index,a1,a2,a3,a4,a5) {
6134 try {
6135 return Module["dynCall_iiiiii"](index,a1,a2,a3,a4,a5);
6136 } catch(e) {
6137 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6138 Module["setThrew"](1, 0);
6139 }
6140}
6141
6142function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6) {
6143 try {
6144 return Module["dynCall_iiiiiii"](index,a1,a2,a3,a4,a5,a6);
6145 } catch(e) {
6146 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6147 Module["setThrew"](1, 0);
6148 }
6149}
6150
6151function invoke_iiiiiiidiiddii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13) {
6152 try {
6153 return Module["dynCall_iiiiiiidiiddii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13);
6154 } catch(e) {
6155 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6156 Module["setThrew"](1, 0);
6157 }
6158}
6159
6160function invoke_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7) {
6161 try {
6162 return Module["dynCall_iiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7);
6163 } catch(e) {
6164 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6165 Module["setThrew"](1, 0);
6166 }
6167}
6168
6169function invoke_iiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9) {
6170 try {
6171 return Module["dynCall_iiiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9);
6172 } catch(e) {
6173 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6174 Module["setThrew"](1, 0);
6175 }
6176}
6177
6178function invoke_iiiiij(index,a1,a2,a3,a4,a5,a6) {
6179 try {
6180 return Module["dynCall_iiiiij"](index,a1,a2,a3,a4,a5,a6);
6181 } catch(e) {
6182 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6183 Module["setThrew"](1, 0);
6184 }
6185}
6186
6187function invoke_iij(index,a1,a2,a3) {
6188 try {
6189 return Module["dynCall_iij"](index,a1,a2,a3);
6190 } catch(e) {
6191 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6192 Module["setThrew"](1, 0);
6193 }
6194}
6195
6196function invoke_jii(index,a1,a2) {
6197 try {
6198 return Module["dynCall_jii"](index,a1,a2);
6199 } catch(e) {
6200 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6201 Module["setThrew"](1, 0);
6202 }
6203}
6204
6205function invoke_jiiii(index,a1,a2,a3,a4) {
6206 try {
6207 return Module["dynCall_jiiii"](index,a1,a2,a3,a4);
6208 } catch(e) {
6209 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6210 Module["setThrew"](1, 0);
6211 }
6212}
6213
6214function invoke_jiiji(index,a1,a2,a3,a4,a5) {
6215 try {
6216 return Module["dynCall_jiiji"](index,a1,a2,a3,a4,a5);
6217 } catch(e) {
6218 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6219 Module["setThrew"](1, 0);
6220 }
6221}
6222
6223function invoke_jij(index,a1,a2,a3) {
6224 try {
6225 return Module["dynCall_jij"](index,a1,a2,a3);
6226 } catch(e) {
6227 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6228 Module["setThrew"](1, 0);
6229 }
6230}
6231
6232function invoke_jiji(index,a1,a2,a3,a4) {
6233 try {
6234 return Module["dynCall_jiji"](index,a1,a2,a3,a4);
6235 } catch(e) {
6236 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6237 Module["setThrew"](1, 0);
6238 }
6239}
6240
6241function invoke_vi(index,a1) {
6242 try {
6243 Module["dynCall_vi"](index,a1);
6244 } catch(e) {
6245 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6246 Module["setThrew"](1, 0);
6247 }
6248}
6249
6250function invoke_vii(index,a1,a2) {
6251 try {
6252 Module["dynCall_vii"](index,a1,a2);
6253 } catch(e) {
6254 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6255 Module["setThrew"](1, 0);
6256 }
6257}
6258
6259function invoke_viidi(index,a1,a2,a3,a4) {
6260 try {
6261 Module["dynCall_viidi"](index,a1,a2,a3,a4);
6262 } catch(e) {
6263 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6264 Module["setThrew"](1, 0);
6265 }
6266}
6267
6268function invoke_viifi(index,a1,a2,a3,a4) {
6269 try {
6270 Module["dynCall_viifi"](index,a1,a2,a3,a4);
6271 } catch(e) {
6272 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6273 Module["setThrew"](1, 0);
6274 }
6275}
6276
6277function invoke_viii(index,a1,a2,a3) {
6278 try {
6279 Module["dynCall_viii"](index,a1,a2,a3);
6280 } catch(e) {
6281 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6282 Module["setThrew"](1, 0);
6283 }
6284}
6285
6286function invoke_viiii(index,a1,a2,a3,a4) {
6287 try {
6288 Module["dynCall_viiii"](index,a1,a2,a3,a4);
6289 } catch(e) {
6290 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6291 Module["setThrew"](1, 0);
6292 }
6293}
6294
6295function invoke_viiiii(index,a1,a2,a3,a4,a5) {
6296 try {
6297 Module["dynCall_viiiii"](index,a1,a2,a3,a4,a5);
6298 } catch(e) {
6299 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6300 Module["setThrew"](1, 0);
6301 }
6302}
6303
6304function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6) {
6305 try {
6306 Module["dynCall_viiiiii"](index,a1,a2,a3,a4,a5,a6);
6307 } catch(e) {
6308 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6309 Module["setThrew"](1, 0);
6310 }
6311}
6312
6313function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7) {
6314 try {
6315 Module["dynCall_viiiiiii"](index,a1,a2,a3,a4,a5,a6,a7);
6316 } catch(e) {
6317 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6318 Module["setThrew"](1, 0);
6319 }
6320}
6321
6322function invoke_viiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8) {
6323 try {
6324 Module["dynCall_viiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8);
6325 } catch(e) {
6326 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6327 Module["setThrew"](1, 0);
6328 }
6329}
6330
6331function invoke_viiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9) {
6332 try {
6333 Module["dynCall_viiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9);
6334 } catch(e) {
6335 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6336 Module["setThrew"](1, 0);
6337 }
6338}
6339
6340function invoke_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) {
6341 try {
6342 Module["dynCall_viiiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10);
6343 } catch(e) {
6344 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6345 Module["setThrew"](1, 0);
6346 }
6347}
6348
6349function invoke_viiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) {
6350 try {
6351 Module["dynCall_viiiiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11);
6352 } catch(e) {
6353 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6354 Module["setThrew"](1, 0);
6355 }
6356}
6357
6358function invoke_viiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12) {
6359 try {
6360 Module["dynCall_viiiiiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12);
6361 } catch(e) {
6362 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6363 Module["setThrew"](1, 0);
6364 }
6365}
6366
6367function invoke_viiijj(index,a1,a2,a3,a4,a5,a6,a7) {
6368 try {
6369 Module["dynCall_viiijj"](index,a1,a2,a3,a4,a5,a6,a7);
6370 } catch(e) {
6371 if (typeof e !== 'number' && e !== 'longjmp') throw e;
6372 Module["setThrew"](1, 0);
6373 }
6374}
6375
6376Module.asmGlobalArg = {};
6377
6378Module.asmLibraryArg = { "abort": abort, "assert": assert, "enlargeMemory": enlargeMemory, "getTotalMemory": getTotalMemory, "abortOnCannotGrowMemory": abortOnCannotGrowMemory, "abortStackOverflow": abortStackOverflow, "nullFunc_dd": nullFunc_dd, "nullFunc_did": nullFunc_did, "nullFunc_didd": nullFunc_didd, "nullFunc_fiii": nullFunc_fiii, "nullFunc_ii": nullFunc_ii, "nullFunc_iii": nullFunc_iii, "nullFunc_iiifii": nullFunc_iiifii, "nullFunc_iiii": nullFunc_iiii, "nullFunc_iiiii": nullFunc_iiiii, "nullFunc_iiiiii": nullFunc_iiiiii, "nullFunc_iiiiiii": nullFunc_iiiiiii, "nullFunc_iiiiiiidiiddii": nullFunc_iiiiiiidiiddii, "nullFunc_iiiiiiii": nullFunc_iiiiiiii, "nullFunc_iiiiiiiiii": nullFunc_iiiiiiiiii, "nullFunc_iiiiij": nullFunc_iiiiij, "nullFunc_iij": nullFunc_iij, "nullFunc_jii": nullFunc_jii, "nullFunc_jiiii": nullFunc_jiiii, "nullFunc_jiiji": nullFunc_jiiji, "nullFunc_jij": nullFunc_jij, "nullFunc_jiji": nullFunc_jiji, "nullFunc_vi": nullFunc_vi, "nullFunc_vii": nullFunc_vii, "nullFunc_viidi": nullFunc_viidi, "nullFunc_viifi": nullFunc_viifi, "nullFunc_viii": nullFunc_viii, "nullFunc_viiii": nullFunc_viiii, "nullFunc_viiiii": nullFunc_viiiii, "nullFunc_viiiiii": nullFunc_viiiiii, "nullFunc_viiiiiii": nullFunc_viiiiiii, "nullFunc_viiiiiiii": nullFunc_viiiiiiii, "nullFunc_viiiiiiiii": nullFunc_viiiiiiiii, "nullFunc_viiiiiiiiii": nullFunc_viiiiiiiiii, "nullFunc_viiiiiiiiiii": nullFunc_viiiiiiiiiii, "nullFunc_viiiiiiiiiiii": nullFunc_viiiiiiiiiiii, "nullFunc_viiijj": nullFunc_viiijj, "invoke_dd": invoke_dd, "invoke_did": invoke_did, "invoke_didd": invoke_didd, "invoke_fiii": invoke_fiii, "invoke_ii": invoke_ii, "invoke_iii": invoke_iii, "invoke_iiifii": invoke_iiifii, "invoke_iiii": invoke_iiii, "invoke_iiiii": invoke_iiiii, "invoke_iiiiii": invoke_iiiiii, "invoke_iiiiiii": invoke_iiiiiii, "invoke_iiiiiiidiiddii": invoke_iiiiiiidiiddii, "invoke_iiiiiiii": invoke_iiiiiiii, "invoke_iiiiiiiiii": invoke_iiiiiiiiii, "invoke_iiiiij": invoke_iiiiij, "invoke_iij": invoke_iij, "invoke_jii": invoke_jii, "invoke_jiiii": invoke_jiiii, "invoke_jiiji": invoke_jiiji, "invoke_jij": invoke_jij, "invoke_jiji": invoke_jiji, "invoke_vi": invoke_vi, "invoke_vii": invoke_vii, "invoke_viidi": invoke_viidi, "invoke_viifi": invoke_viifi, "invoke_viii": invoke_viii, "invoke_viiii": invoke_viiii, "invoke_viiiii": invoke_viiiii, "invoke_viiiiii": invoke_viiiiii, "invoke_viiiiiii": invoke_viiiiiii, "invoke_viiiiiiii": invoke_viiiiiiii, "invoke_viiiiiiiii": invoke_viiiiiiiii, "invoke_viiiiiiiiii": invoke_viiiiiiiiii, "invoke_viiiiiiiiiii": invoke_viiiiiiiiiii, "invoke_viiiiiiiiiiii": invoke_viiiiiiiiiiii, "invoke_viiijj": invoke_viiijj, "___assert_fail": ___assert_fail, "___buildEnvironment": ___buildEnvironment, "___lock": ___lock, "___setErrNo": ___setErrNo, "___syscall10": ___syscall10, "___syscall140": ___syscall140, "___syscall145": ___syscall145, "___syscall146": ___syscall146, "___syscall195": ___syscall195, "___syscall196": ___syscall196, "___syscall197": ___syscall197, "___syscall219": ___syscall219, "___syscall220": ___syscall220, "___syscall221": ___syscall221, "___syscall3": ___syscall3, "___syscall33": ___syscall33, "___syscall38": ___syscall38, "___syscall4": ___syscall4, "___syscall40": ___syscall40, "___syscall5": ___syscall5, "___syscall54": ___syscall54, "___syscall6": ___syscall6, "___unlock": ___unlock, "__addDays": __addDays, "__arraySum": __arraySum, "__exit": __exit, "__isLeapYear": __isLeapYear, "_abort": _abort, "_clock": _clock, "_clock_gettime": _clock_gettime, "_emscripten_get_now": _emscripten_get_now, "_emscripten_get_now_is_monotonic": _emscripten_get_now_is_monotonic, "_emscripten_memcpy_big": _emscripten_memcpy_big, "_exit": _exit, "_fabs": _fabs, "_getenv": _getenv, "_gettimeofday": _gettimeofday, "_gmtime_r": _gmtime_r, "_llvm_ceil_f32": _llvm_ceil_f32, "_llvm_ceil_f64": _llvm_ceil_f64, "_llvm_cttz_i32": _llvm_cttz_i32, "_llvm_exp2_f32": _llvm_exp2_f32, "_llvm_exp2_f64": _llvm_exp2_f64, "_llvm_fabs_f32": _llvm_fabs_f32, "_llvm_fabs_f64": _llvm_fabs_f64, "_llvm_floor_f32": _llvm_floor_f32, "_llvm_floor_f64": _llvm_floor_f64, "_llvm_pow_f32": _llvm_pow_f32, "_llvm_pow_f64": _llvm_pow_f64, "_llvm_sqrt_f32": _llvm_sqrt_f32, "_llvm_sqrt_f64": _llvm_sqrt_f64, "_llvm_trunc_f64": _llvm_trunc_f64, "_localtime_r": _localtime_r, "_mktime": _mktime, "_nanosleep": _nanosleep, "_strftime": _strftime, "_tzset": _tzset, "_usleep": _usleep, "DYNAMICTOP_PTR": DYNAMICTOP_PTR, "tempDoublePtr": tempDoublePtr, "ABORT": ABORT, "STACKTOP": STACKTOP, "STACK_MAX": STACK_MAX, "cttz_i8": cttz_i8 };
6379// EMSCRIPTEN_START_ASM
6380var asm =Module["asm"]// EMSCRIPTEN_END_ASM
6381(Module.asmGlobalArg, Module.asmLibraryArg, buffer);
6382
6383var real____errno_location = asm["___errno_location"]; asm["___errno_location"] = function() {
6384 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6385 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6386 return real____errno_location.apply(null, arguments);
6387};
6388
6389var real__add_frame = asm["_add_frame"]; asm["_add_frame"] = function() {
6390 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6391 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6392 return real__add_frame.apply(null, arguments);
6393};
6394
6395var real__close_stream = asm["_close_stream"]; asm["_close_stream"] = function() {
6396 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6397 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6398 return real__close_stream.apply(null, arguments);
6399};
6400
6401var real__fflush = asm["_fflush"]; asm["_fflush"] = function() {
6402 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6403 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6404 return real__fflush.apply(null, arguments);
6405};
6406
6407var real__free = asm["_free"]; asm["_free"] = function() {
6408 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6409 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6410 return real__free.apply(null, arguments);
6411};
6412
6413var real__free_buffer = asm["_free_buffer"]; asm["_free_buffer"] = function() {
6414 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6415 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6416 return real__free_buffer.apply(null, arguments);
6417};
6418
6419var real__get_buffer = asm["_get_buffer"]; asm["_get_buffer"] = function() {
6420 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6421 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6422 return real__get_buffer.apply(null, arguments);
6423};
6424
6425var real__llvm_bswap_i16 = asm["_llvm_bswap_i16"]; asm["_llvm_bswap_i16"] = function() {
6426 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6427 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6428 return real__llvm_bswap_i16.apply(null, arguments);
6429};
6430
6431var real__llvm_bswap_i32 = asm["_llvm_bswap_i32"]; asm["_llvm_bswap_i32"] = function() {
6432 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6433 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6434 return real__llvm_bswap_i32.apply(null, arguments);
6435};
6436
6437var real__llvm_rint_f64 = asm["_llvm_rint_f64"]; asm["_llvm_rint_f64"] = function() {
6438 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6439 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6440 return real__llvm_rint_f64.apply(null, arguments);
6441};
6442
6443var real__llvm_round_f32 = asm["_llvm_round_f32"]; asm["_llvm_round_f32"] = function() {
6444 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6445 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6446 return real__llvm_round_f32.apply(null, arguments);
6447};
6448
6449var real__llvm_round_f64 = asm["_llvm_round_f64"]; asm["_llvm_round_f64"] = function() {
6450 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6451 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6452 return real__llvm_round_f64.apply(null, arguments);
6453};
6454
6455var real__malloc = asm["_malloc"]; asm["_malloc"] = function() {
6456 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6457 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6458 return real__malloc.apply(null, arguments);
6459};
6460
6461var real__memmove = asm["_memmove"]; asm["_memmove"] = function() {
6462 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6463 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6464 return real__memmove.apply(null, arguments);
6465};
6466
6467var real__open_audio = asm["_open_audio"]; asm["_open_audio"] = function() {
6468 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6469 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6470 return real__open_audio.apply(null, arguments);
6471};
6472
6473var real__open_video = asm["_open_video"]; asm["_open_video"] = function() {
6474 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6475 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6476 return real__open_video.apply(null, arguments);
6477};
6478
6479var real__rintf = asm["_rintf"]; asm["_rintf"] = function() {
6480 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6481 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6482 return real__rintf.apply(null, arguments);
6483};
6484
6485var real__sbrk = asm["_sbrk"]; asm["_sbrk"] = function() {
6486 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6487 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6488 return real__sbrk.apply(null, arguments);
6489};
6490
6491var real__write_audio_frame = asm["_write_audio_frame"]; asm["_write_audio_frame"] = function() {
6492 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6493 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6494 return real__write_audio_frame.apply(null, arguments);
6495};
6496
6497var real__write_header = asm["_write_header"]; asm["_write_header"] = function() {
6498 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6499 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6500 return real__write_header.apply(null, arguments);
6501};
6502
6503var real_establishStackSpace = asm["establishStackSpace"]; asm["establishStackSpace"] = function() {
6504 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6505 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6506 return real_establishStackSpace.apply(null, arguments);
6507};
6508
6509var real_getTempRet0 = asm["getTempRet0"]; asm["getTempRet0"] = function() {
6510 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6511 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6512 return real_getTempRet0.apply(null, arguments);
6513};
6514
6515var real_setTempRet0 = asm["setTempRet0"]; asm["setTempRet0"] = function() {
6516 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6517 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6518 return real_setTempRet0.apply(null, arguments);
6519};
6520
6521var real_setThrew = asm["setThrew"]; asm["setThrew"] = function() {
6522 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6523 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6524 return real_setThrew.apply(null, arguments);
6525};
6526
6527var real_stackAlloc = asm["stackAlloc"]; asm["stackAlloc"] = function() {
6528 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6529 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6530 return real_stackAlloc.apply(null, arguments);
6531};
6532
6533var real_stackRestore = asm["stackRestore"]; asm["stackRestore"] = function() {
6534 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6535 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6536 return real_stackRestore.apply(null, arguments);
6537};
6538
6539var real_stackSave = asm["stackSave"]; asm["stackSave"] = function() {
6540 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6541 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6542 return real_stackSave.apply(null, arguments);
6543};
6544Module["asm"] = asm;
6545var ___errno_location = Module["___errno_location"] = function() {
6546 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6547 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6548 return Module["asm"]["___errno_location"].apply(null, arguments) };
6549var _add_frame = Module["_add_frame"] = function() {
6550 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6551 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6552 return Module["asm"]["_add_frame"].apply(null, arguments) };
6553var _close_stream = Module["_close_stream"] = function() {
6554 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6555 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6556 return Module["asm"]["_close_stream"].apply(null, arguments) };
6557var _emscripten_replace_memory = Module["_emscripten_replace_memory"] = function() {
6558 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6559 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6560 return Module["asm"]["_emscripten_replace_memory"].apply(null, arguments) };
6561var _fflush = Module["_fflush"] = function() {
6562 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6563 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6564 return Module["asm"]["_fflush"].apply(null, arguments) };
6565var _free = Module["_free"] = function() {
6566 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6567 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6568 return Module["asm"]["_free"].apply(null, arguments) };
6569var _free_buffer = Module["_free_buffer"] = function() {
6570 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6571 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6572 return Module["asm"]["_free_buffer"].apply(null, arguments) };
6573var _get_buffer = Module["_get_buffer"] = function() {
6574 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6575 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6576 return Module["asm"]["_get_buffer"].apply(null, arguments) };
6577var _llvm_bswap_i16 = Module["_llvm_bswap_i16"] = function() {
6578 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6579 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6580 return Module["asm"]["_llvm_bswap_i16"].apply(null, arguments) };
6581var _llvm_bswap_i32 = Module["_llvm_bswap_i32"] = function() {
6582 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6583 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6584 return Module["asm"]["_llvm_bswap_i32"].apply(null, arguments) };
6585var _llvm_rint_f64 = Module["_llvm_rint_f64"] = function() {
6586 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6587 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6588 return Module["asm"]["_llvm_rint_f64"].apply(null, arguments) };
6589var _llvm_round_f32 = Module["_llvm_round_f32"] = function() {
6590 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6591 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6592 return Module["asm"]["_llvm_round_f32"].apply(null, arguments) };
6593var _llvm_round_f64 = Module["_llvm_round_f64"] = function() {
6594 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6595 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6596 return Module["asm"]["_llvm_round_f64"].apply(null, arguments) };
6597var _malloc = Module["_malloc"] = function() {
6598 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6599 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6600 return Module["asm"]["_malloc"].apply(null, arguments) };
6601var _memcpy = Module["_memcpy"] = function() {
6602 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6603 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6604 return Module["asm"]["_memcpy"].apply(null, arguments) };
6605var _memmove = Module["_memmove"] = function() {
6606 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6607 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6608 return Module["asm"]["_memmove"].apply(null, arguments) };
6609var _memset = Module["_memset"] = function() {
6610 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6611 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6612 return Module["asm"]["_memset"].apply(null, arguments) };
6613var _open_audio = Module["_open_audio"] = function() {
6614 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6615 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6616 return Module["asm"]["_open_audio"].apply(null, arguments) };
6617var _open_video = Module["_open_video"] = function() {
6618 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6619 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6620 return Module["asm"]["_open_video"].apply(null, arguments) };
6621var _rintf = Module["_rintf"] = function() {
6622 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6623 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6624 return Module["asm"]["_rintf"].apply(null, arguments) };
6625var _sbrk = Module["_sbrk"] = function() {
6626 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6627 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6628 return Module["asm"]["_sbrk"].apply(null, arguments) };
6629var _write_audio_frame = Module["_write_audio_frame"] = function() {
6630 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6631 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6632 return Module["asm"]["_write_audio_frame"].apply(null, arguments) };
6633var _write_header = Module["_write_header"] = function() {
6634 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6635 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6636 return Module["asm"]["_write_header"].apply(null, arguments) };
6637var establishStackSpace = Module["establishStackSpace"] = function() {
6638 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6639 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6640 return Module["asm"]["establishStackSpace"].apply(null, arguments) };
6641var getTempRet0 = Module["getTempRet0"] = function() {
6642 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6643 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6644 return Module["asm"]["getTempRet0"].apply(null, arguments) };
6645var runPostSets = Module["runPostSets"] = function() {
6646 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6647 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6648 return Module["asm"]["runPostSets"].apply(null, arguments) };
6649var setTempRet0 = Module["setTempRet0"] = function() {
6650 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6651 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6652 return Module["asm"]["setTempRet0"].apply(null, arguments) };
6653var setThrew = Module["setThrew"] = function() {
6654 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6655 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6656 return Module["asm"]["setThrew"].apply(null, arguments) };
6657var stackAlloc = Module["stackAlloc"] = function() {
6658 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6659 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6660 return Module["asm"]["stackAlloc"].apply(null, arguments) };
6661var stackRestore = Module["stackRestore"] = function() {
6662 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6663 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6664 return Module["asm"]["stackRestore"].apply(null, arguments) };
6665var stackSave = Module["stackSave"] = function() {
6666 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6667 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6668 return Module["asm"]["stackSave"].apply(null, arguments) };
6669var dynCall_dd = Module["dynCall_dd"] = function() {
6670 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6671 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6672 return Module["asm"]["dynCall_dd"].apply(null, arguments) };
6673var dynCall_did = Module["dynCall_did"] = function() {
6674 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6675 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6676 return Module["asm"]["dynCall_did"].apply(null, arguments) };
6677var dynCall_didd = Module["dynCall_didd"] = function() {
6678 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6679 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6680 return Module["asm"]["dynCall_didd"].apply(null, arguments) };
6681var dynCall_fiii = Module["dynCall_fiii"] = function() {
6682 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6683 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6684 return Module["asm"]["dynCall_fiii"].apply(null, arguments) };
6685var dynCall_ii = Module["dynCall_ii"] = function() {
6686 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6687 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6688 return Module["asm"]["dynCall_ii"].apply(null, arguments) };
6689var dynCall_iii = Module["dynCall_iii"] = function() {
6690 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6691 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6692 return Module["asm"]["dynCall_iii"].apply(null, arguments) };
6693var dynCall_iiifii = Module["dynCall_iiifii"] = function() {
6694 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6695 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6696 return Module["asm"]["dynCall_iiifii"].apply(null, arguments) };
6697var dynCall_iiii = Module["dynCall_iiii"] = function() {
6698 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6699 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6700 return Module["asm"]["dynCall_iiii"].apply(null, arguments) };
6701var dynCall_iiiii = Module["dynCall_iiiii"] = function() {
6702 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6703 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6704 return Module["asm"]["dynCall_iiiii"].apply(null, arguments) };
6705var dynCall_iiiiii = Module["dynCall_iiiiii"] = function() {
6706 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6707 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6708 return Module["asm"]["dynCall_iiiiii"].apply(null, arguments) };
6709var dynCall_iiiiiii = Module["dynCall_iiiiiii"] = function() {
6710 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6711 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6712 return Module["asm"]["dynCall_iiiiiii"].apply(null, arguments) };
6713var dynCall_iiiiiiidiiddii = Module["dynCall_iiiiiiidiiddii"] = function() {
6714 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6715 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6716 return Module["asm"]["dynCall_iiiiiiidiiddii"].apply(null, arguments) };
6717var dynCall_iiiiiiii = Module["dynCall_iiiiiiii"] = function() {
6718 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6719 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6720 return Module["asm"]["dynCall_iiiiiiii"].apply(null, arguments) };
6721var dynCall_iiiiiiiiii = Module["dynCall_iiiiiiiiii"] = function() {
6722 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6723 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6724 return Module["asm"]["dynCall_iiiiiiiiii"].apply(null, arguments) };
6725var dynCall_iiiiij = Module["dynCall_iiiiij"] = function() {
6726 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6727 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6728 return Module["asm"]["dynCall_iiiiij"].apply(null, arguments) };
6729var dynCall_iij = Module["dynCall_iij"] = function() {
6730 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6731 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6732 return Module["asm"]["dynCall_iij"].apply(null, arguments) };
6733var dynCall_jii = Module["dynCall_jii"] = function() {
6734 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6735 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6736 return Module["asm"]["dynCall_jii"].apply(null, arguments) };
6737var dynCall_jiiii = Module["dynCall_jiiii"] = function() {
6738 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6739 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6740 return Module["asm"]["dynCall_jiiii"].apply(null, arguments) };
6741var dynCall_jiiji = Module["dynCall_jiiji"] = function() {
6742 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6743 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6744 return Module["asm"]["dynCall_jiiji"].apply(null, arguments) };
6745var dynCall_jij = Module["dynCall_jij"] = function() {
6746 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6747 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6748 return Module["asm"]["dynCall_jij"].apply(null, arguments) };
6749var dynCall_jiji = Module["dynCall_jiji"] = function() {
6750 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6751 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6752 return Module["asm"]["dynCall_jiji"].apply(null, arguments) };
6753var dynCall_vi = Module["dynCall_vi"] = function() {
6754 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6755 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6756 return Module["asm"]["dynCall_vi"].apply(null, arguments) };
6757var dynCall_vii = Module["dynCall_vii"] = function() {
6758 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6759 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6760 return Module["asm"]["dynCall_vii"].apply(null, arguments) };
6761var dynCall_viidi = Module["dynCall_viidi"] = function() {
6762 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6763 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6764 return Module["asm"]["dynCall_viidi"].apply(null, arguments) };
6765var dynCall_viifi = Module["dynCall_viifi"] = function() {
6766 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6767 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6768 return Module["asm"]["dynCall_viifi"].apply(null, arguments) };
6769var dynCall_viii = Module["dynCall_viii"] = function() {
6770 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6771 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6772 return Module["asm"]["dynCall_viii"].apply(null, arguments) };
6773var dynCall_viiii = Module["dynCall_viiii"] = function() {
6774 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6775 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6776 return Module["asm"]["dynCall_viiii"].apply(null, arguments) };
6777var dynCall_viiiii = Module["dynCall_viiiii"] = function() {
6778 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6779 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6780 return Module["asm"]["dynCall_viiiii"].apply(null, arguments) };
6781var dynCall_viiiiii = Module["dynCall_viiiiii"] = function() {
6782 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6783 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6784 return Module["asm"]["dynCall_viiiiii"].apply(null, arguments) };
6785var dynCall_viiiiiii = Module["dynCall_viiiiiii"] = function() {
6786 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6787 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6788 return Module["asm"]["dynCall_viiiiiii"].apply(null, arguments) };
6789var dynCall_viiiiiiii = Module["dynCall_viiiiiiii"] = function() {
6790 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6791 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6792 return Module["asm"]["dynCall_viiiiiiii"].apply(null, arguments) };
6793var dynCall_viiiiiiiii = Module["dynCall_viiiiiiiii"] = function() {
6794 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6795 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6796 return Module["asm"]["dynCall_viiiiiiiii"].apply(null, arguments) };
6797var dynCall_viiiiiiiiii = Module["dynCall_viiiiiiiiii"] = function() {
6798 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6799 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6800 return Module["asm"]["dynCall_viiiiiiiiii"].apply(null, arguments) };
6801var dynCall_viiiiiiiiiii = Module["dynCall_viiiiiiiiiii"] = function() {
6802 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6803 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6804 return Module["asm"]["dynCall_viiiiiiiiiii"].apply(null, arguments) };
6805var dynCall_viiiiiiiiiiii = Module["dynCall_viiiiiiiiiiii"] = function() {
6806 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6807 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6808 return Module["asm"]["dynCall_viiiiiiiiiiii"].apply(null, arguments) };
6809var dynCall_viiijj = Module["dynCall_viiijj"] = function() {
6810 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
6811 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
6812 return Module["asm"]["dynCall_viiijj"].apply(null, arguments) };
6813;
6814
6815
6816
6817// === Auto-generated postamble setup entry stuff ===
6818
6819Module['asm'] = asm;
6820
6821if (!Module["intArrayFromString"]) Module["intArrayFromString"] = function() { abort("'intArrayFromString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6822if (!Module["intArrayToString"]) Module["intArrayToString"] = function() { abort("'intArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6823if (!Module["ccall"]) Module["ccall"] = function() { abort("'ccall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6824if (!Module["cwrap"]) Module["cwrap"] = function() { abort("'cwrap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6825if (!Module["setValue"]) Module["setValue"] = function() { abort("'setValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6826if (!Module["getValue"]) Module["getValue"] = function() { abort("'getValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6827if (!Module["allocate"]) Module["allocate"] = function() { abort("'allocate' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6828if (!Module["getMemory"]) Module["getMemory"] = function() { abort("'getMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6829if (!Module["Pointer_stringify"]) Module["Pointer_stringify"] = function() { abort("'Pointer_stringify' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6830if (!Module["AsciiToString"]) Module["AsciiToString"] = function() { abort("'AsciiToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6831if (!Module["stringToAscii"]) Module["stringToAscii"] = function() { abort("'stringToAscii' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6832if (!Module["UTF8ArrayToString"]) Module["UTF8ArrayToString"] = function() { abort("'UTF8ArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6833if (!Module["UTF8ToString"]) Module["UTF8ToString"] = function() { abort("'UTF8ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6834if (!Module["stringToUTF8Array"]) Module["stringToUTF8Array"] = function() { abort("'stringToUTF8Array' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6835if (!Module["stringToUTF8"]) Module["stringToUTF8"] = function() { abort("'stringToUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6836if (!Module["lengthBytesUTF8"]) Module["lengthBytesUTF8"] = function() { abort("'lengthBytesUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6837if (!Module["UTF16ToString"]) Module["UTF16ToString"] = function() { abort("'UTF16ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6838if (!Module["stringToUTF16"]) Module["stringToUTF16"] = function() { abort("'stringToUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6839if (!Module["lengthBytesUTF16"]) Module["lengthBytesUTF16"] = function() { abort("'lengthBytesUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6840if (!Module["UTF32ToString"]) Module["UTF32ToString"] = function() { abort("'UTF32ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6841if (!Module["stringToUTF32"]) Module["stringToUTF32"] = function() { abort("'stringToUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6842if (!Module["lengthBytesUTF32"]) Module["lengthBytesUTF32"] = function() { abort("'lengthBytesUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6843if (!Module["allocateUTF8"]) Module["allocateUTF8"] = function() { abort("'allocateUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6844if (!Module["stackTrace"]) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6845if (!Module["addOnPreRun"]) Module["addOnPreRun"] = function() { abort("'addOnPreRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6846if (!Module["addOnInit"]) Module["addOnInit"] = function() { abort("'addOnInit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6847if (!Module["addOnPreMain"]) Module["addOnPreMain"] = function() { abort("'addOnPreMain' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6848if (!Module["addOnExit"]) Module["addOnExit"] = function() { abort("'addOnExit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6849if (!Module["addOnPostRun"]) Module["addOnPostRun"] = function() { abort("'addOnPostRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6850if (!Module["writeStringToMemory"]) Module["writeStringToMemory"] = function() { abort("'writeStringToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6851if (!Module["writeArrayToMemory"]) Module["writeArrayToMemory"] = function() { abort("'writeArrayToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6852if (!Module["writeAsciiToMemory"]) Module["writeAsciiToMemory"] = function() { abort("'writeAsciiToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6853if (!Module["addRunDependency"]) Module["addRunDependency"] = function() { abort("'addRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6854if (!Module["removeRunDependency"]) Module["removeRunDependency"] = function() { abort("'removeRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6855if (!Module["FS"]) Module["FS"] = function() { abort("'FS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6856if (!Module["FS_createFolder"]) Module["FS_createFolder"] = function() { abort("'FS_createFolder' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6857if (!Module["FS_createPath"]) Module["FS_createPath"] = function() { abort("'FS_createPath' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6858if (!Module["FS_createDataFile"]) Module["FS_createDataFile"] = function() { abort("'FS_createDataFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6859if (!Module["FS_createPreloadedFile"]) Module["FS_createPreloadedFile"] = function() { abort("'FS_createPreloadedFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6860if (!Module["FS_createLazyFile"]) Module["FS_createLazyFile"] = function() { abort("'FS_createLazyFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6861if (!Module["FS_createLink"]) Module["FS_createLink"] = function() { abort("'FS_createLink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6862if (!Module["FS_createDevice"]) Module["FS_createDevice"] = function() { abort("'FS_createDevice' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6863if (!Module["FS_unlink"]) Module["FS_unlink"] = function() { abort("'FS_unlink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
6864if (!Module["GL"]) Module["GL"] = function() { abort("'GL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6865if (!Module["staticAlloc"]) Module["staticAlloc"] = function() { abort("'staticAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6866if (!Module["dynamicAlloc"]) Module["dynamicAlloc"] = function() { abort("'dynamicAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6867if (!Module["warnOnce"]) Module["warnOnce"] = function() { abort("'warnOnce' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6868if (!Module["loadDynamicLibrary"]) Module["loadDynamicLibrary"] = function() { abort("'loadDynamicLibrary' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6869if (!Module["loadWebAssemblyModule"]) Module["loadWebAssemblyModule"] = function() { abort("'loadWebAssemblyModule' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6870if (!Module["getLEB"]) Module["getLEB"] = function() { abort("'getLEB' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6871if (!Module["getFunctionTables"]) Module["getFunctionTables"] = function() { abort("'getFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6872if (!Module["alignFunctionTables"]) Module["alignFunctionTables"] = function() { abort("'alignFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6873if (!Module["registerFunctions"]) Module["registerFunctions"] = function() { abort("'registerFunctions' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6874if (!Module["addFunction"]) Module["addFunction"] = function() { abort("'addFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6875if (!Module["removeFunction"]) Module["removeFunction"] = function() { abort("'removeFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6876if (!Module["getFuncWrapper"]) Module["getFuncWrapper"] = function() { abort("'getFuncWrapper' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6877if (!Module["prettyPrint"]) Module["prettyPrint"] = function() { abort("'prettyPrint' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6878if (!Module["makeBigInt"]) Module["makeBigInt"] = function() { abort("'makeBigInt' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6879if (!Module["dynCall"]) Module["dynCall"] = function() { abort("'dynCall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
6880if (!Module["getCompilerSetting"]) Module["getCompilerSetting"] = function() { abort("'getCompilerSetting' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };if (!Module["ALLOC_NORMAL"]) Object.defineProperty(Module, "ALLOC_NORMAL", { get: function() { abort("'ALLOC_NORMAL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
6881if (!Module["ALLOC_STACK"]) Object.defineProperty(Module, "ALLOC_STACK", { get: function() { abort("'ALLOC_STACK' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
6882if (!Module["ALLOC_STATIC"]) Object.defineProperty(Module, "ALLOC_STATIC", { get: function() { abort("'ALLOC_STATIC' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
6883if (!Module["ALLOC_DYNAMIC"]) Object.defineProperty(Module, "ALLOC_DYNAMIC", { get: function() { abort("'ALLOC_DYNAMIC' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
6884if (!Module["ALLOC_NONE"]) Object.defineProperty(Module, "ALLOC_NONE", { get: function() { abort("'ALLOC_NONE' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
6885
6886
6887
6888// Modularize mode returns a function, which can be called to
6889// create instances. The instances provide a then() method,
6890// must like a Promise, that receives a callback. The callback
6891// is called when the module is ready to run, with the module
6892// as a parameter. (Like a Promise, it also returns the module
6893// so you can use the output of .then(..)).
6894Module['then'] = function(func) {
6895 // We may already be ready to run code at this time. if
6896 // so, just queue a call to the callback.
6897 if (Module['calledRun']) {
6898 func(Module);
6899 } else {
6900 // we are not ready to call then() yet. we must call it
6901 // at the same time we would call onRuntimeInitialized.
6902 var old = Module['onRuntimeInitialized'];
6903 Module['onRuntimeInitialized'] = function() {
6904 if (old) old();
6905 func(Module);
6906 };
6907 }
6908 return Module;
6909};
6910
6911/**
6912 * @constructor
6913 * @extends {Error}
6914 * @this {ExitStatus}
6915 */
6916function ExitStatus(status) {
6917 this.name = "ExitStatus";
6918 this.message = "Program terminated with exit(" + status + ")";
6919 this.status = status;
6920};
6921ExitStatus.prototype = new Error();
6922ExitStatus.prototype.constructor = ExitStatus;
6923
6924var initialStackTop;
6925var calledMain = false;
6926
6927dependenciesFulfilled = function runCaller() {
6928 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
6929 if (!Module['calledRun']) run();
6930 if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
6931}
6932
6933
6934
6935
6936
6937/** @type {function(Array=)} */
6938function run(args) {
6939 args = args || Module['arguments'];
6940
6941 if (runDependencies > 0) {
6942 return;
6943 }
6944
6945 writeStackCookie();
6946
6947 preRun();
6948
6949 if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
6950 if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
6951
6952 function doRun() {
6953 if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
6954 Module['calledRun'] = true;
6955
6956 if (ABORT) return;
6957
6958 ensureInitRuntime();
6959
6960 preMain();
6961
6962 if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
6963
6964 assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
6965
6966 postRun();
6967 }
6968
6969 if (Module['setStatus']) {
6970 Module['setStatus']('Running...');
6971 setTimeout(function() {
6972 setTimeout(function() {
6973 Module['setStatus']('');
6974 }, 1);
6975 doRun();
6976 }, 1);
6977 } else {
6978 doRun();
6979 }
6980 checkStackCookie();
6981}
6982Module['run'] = run;
6983
6984function checkUnflushedContent() {
6985 // Compiler settings do not allow exiting the runtime, so flushing
6986 // the streams is not possible. but in ASSERTIONS mode we check
6987 // if there was something to flush, and if so tell the user they
6988 // should request that the runtime be exitable.
6989 // Normally we would not even include flush() at all, but in ASSERTIONS
6990 // builds we do so just for this check, and here we see if there is any
6991 // content to flush, that is, we check if there would have been
6992 // something a non-ASSERTIONS build would have not seen.
6993 // How we flush the streams depends on whether we are in NO_FILESYSTEM
6994 // mode (which has its own special function for this; otherwise, all
6995 // the code is inside libc)
6996 var print = Module['print'];
6997 var printErr = Module['printErr'];
6998 var has = false;
6999 Module['print'] = Module['printErr'] = function(x) {
7000 has = true;
7001 }
7002 try { // it doesn't matter if it fails
7003 var flush = Module['_fflush'];
7004 if (flush) flush(0);
7005 // also flush in the JS FS layer
7006 var hasFS = true;
7007 if (hasFS) {
7008 ['stdout', 'stderr'].forEach(function(name) {
7009 var info = FS.analyzePath('/dev/' + name);
7010 if (!info) return;
7011 var stream = info.object;
7012 var rdev = stream.rdev;
7013 var tty = TTY.ttys[rdev];
7014 if (tty && tty.output && tty.output.length) {
7015 has = true;
7016 }
7017 });
7018 }
7019 } catch(e) {}
7020 Module['print'] = print;
7021 Module['printErr'] = printErr;
7022 if (has) {
7023 warnOnce('stdio streams had content in them that was not flushed. you should set NO_EXIT_RUNTIME to 0 (see the FAQ), or make sure to emit a newline when you printf etc.');
7024 }
7025}
7026
7027function exit(status, implicit) {
7028 checkUnflushedContent();
7029
7030 // if this is just main exit-ing implicitly, and the status is 0, then we
7031 // don't need to do anything here and can just leave. if the status is
7032 // non-zero, though, then we need to report it.
7033 // (we may have warned about this earlier, if a situation justifies doing so)
7034 if (implicit && Module['noExitRuntime'] && status === 0) {
7035 return;
7036 }
7037
7038 if (Module['noExitRuntime']) {
7039 // if exit() was called, we may warn the user if the runtime isn't actually being shut down
7040 if (!implicit) {
7041 Module.printErr('exit(' + status + ') called, but NO_EXIT_RUNTIME is set, so halting execution but not exiting the runtime or preventing further async execution (build with NO_EXIT_RUNTIME=0, if you want a true shutdown)');
7042 }
7043 } else {
7044
7045 ABORT = true;
7046 EXITSTATUS = status;
7047 STACKTOP = initialStackTop;
7048
7049 exitRuntime();
7050
7051 if (Module['onExit']) Module['onExit'](status);
7052 }
7053
7054 if (ENVIRONMENT_IS_NODE) {
7055 process['exit'](status);
7056 }
7057 Module['quit'](status, new ExitStatus(status));
7058}
7059Module['exit'] = exit;
7060
7061var abortDecorators = [];
7062
7063function abort(what) {
7064 if (Module['onAbort']) {
7065 Module['onAbort'](what);
7066 }
7067
7068 if (what !== undefined) {
7069 Module.print(what);
7070 Module.printErr(what);
7071 what = JSON.stringify(what)
7072 } else {
7073 what = '';
7074 }
7075
7076 ABORT = true;
7077 EXITSTATUS = 1;
7078
7079 var extra = '';
7080 var output = 'abort(' + what + ') at ' + stackTrace() + extra;
7081 if (abortDecorators) {
7082 abortDecorators.forEach(function(decorator) {
7083 output = decorator(output, what);
7084 });
7085 }
7086 throw output;
7087}
7088Module['abort'] = abort;
7089
7090// {{PRE_RUN_ADDITIONS}}
7091
7092if (Module['preInit']) {
7093 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
7094 while (Module['preInit'].length > 0) {
7095 Module['preInit'].pop()();
7096 }
7097}
7098
7099
7100Module["noExitRuntime"] = true;
7101
7102run();
7103
7104// {{POST_RUN_ADDITIONS}}
7105
7106
7107
7108
7109
7110// {{MODULE_ADDITIONS}}
7111
7112
7113
7114
7115
7116 return WasmVideoEncoderProd;
7117};
7118if (typeof exports === 'object' && typeof module === 'object')
7119 module.exports = WasmVideoEncoderProd;
7120else if (typeof define === 'function' && define['amd'])
7121 define([], function() { return WasmVideoEncoderProd; });
7122else if (typeof exports === 'object')
7123 exports["WasmVideoEncoderProd"] = WasmVideoEncoderProd;