1 var EXPECTED_OUTPUT = 'final: 40006013:58243.\n';
4 print: function(x) {Module.printBuffer += x + '\n';},
5 preRun: [function() {Module.printBuffer = ''}],
7 assertEquals(EXPECTED_OUTPUT, Module.printBuffer);
10 // The Module object: Our interface to the outside world. We import
11 // and export values on it, and do the work to get that through
12 // closure compiler if necessary. There are various ways Module can be used:
13 // 1. Not defined. We create it here
14 // 2. A function parameter, function(Module) { ..generated code.. }
15 // 3. pre-run appended it, var Module = {}; ..generated code..
16 // 4. External script tag defines var Module.
17 // We need to do an eval in order to handle the closure compiler
18 // case, where this code here is minified but Module was defined
19 // elsewhere (e.g. case 4 above). We also need to check if Module
20 // already exists (e.g. case 3 above).
21 // Note that if you want to run closure, and also to use Module
22 // after the generated code, you will need to define var Module = {};
23 // before the code. Then that object will be used in the code, and you
24 // can continue to use Module afterwards as well.
26 if (!Module) Module = (typeof Module !== 'undefined' ? Module : null) || {};
28 // Sometimes an existing Module object exists with properties
29 // meant to overwrite the default module functionality. Here
30 // we collect those properties and reapply _after_ we configure
31 // the current environment's defaults to avoid having to be so
32 // defensive during initialization.
33 var moduleOverrides = {};
34 for (var key in Module) {
35 if (Module.hasOwnProperty(key)) {
36 moduleOverrides[key] = Module[key];
40 // The environment setup code below is customized to use Module.
41 // *** Environment setup code ***
42 var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
43 var ENVIRONMENT_IS_WEB = typeof window === 'object';
44 var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
45 var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
47 if (ENVIRONMENT_IS_NODE) {
48 // Expose functionality in the same simple way that the shells work
49 // Note that we pollute the global namespace here, otherwise we break in node
50 if (!Module['print']) Module['print'] = function print(x) {
51 process['stdout'].write(x + '\n');
53 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
54 process['stderr'].write(x + '\n');
57 var nodeFS = require('fs');
58 var nodePath = require('path');
60 Module['read'] = function read(filename, binary) {
61 filename = nodePath['normalize'](filename);
62 var ret = nodeFS['readFileSync'](filename);
63 // The path is absolute if the normalized version is the same as the resolved.
64 if (!ret && filename != nodePath['resolve'](filename)) {
65 filename = path.join(__dirname, '..', 'src', filename);
66 ret = nodeFS['readFileSync'](filename);
68 if (ret && !binary) ret = ret.toString();
72 Module['readBinary'] = function readBinary(filename) { return Module['read'](filename, true) };
74 Module['load'] = function load(f) {
78 Module['arguments'] = process['argv'].slice(2);
80 module['exports'] = Module;
82 else if (ENVIRONMENT_IS_SHELL) {
83 if (!Module['print']) Module['print'] = print;
84 if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not present in v8 or older sm
86 if (typeof read != 'undefined') {
87 Module['read'] = read;
89 Module['read'] = function read() { throw 'no read() available (jsc?)' };
92 Module['readBinary'] = function readBinary(f) {
93 return read(f, 'binary');
96 if (typeof scriptArgs != 'undefined') {
97 Module['arguments'] = scriptArgs;
98 } else if (typeof arguments != 'undefined') {
99 Module['arguments'] = arguments;
102 this['Module'] = Module;
104 eval("if (typeof gc === 'function' && gc.toString().indexOf('[native code]') > 0) var gc = undefined"); // wipe out the SpiderMonkey shell 'gc' function, which can confuse closure (uses it as a minified name, and it is then initted to a non-falsey value unexpectedly)
106 else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
107 Module['read'] = function read(url) {
108 var xhr = new XMLHttpRequest();
109 xhr.open('GET', url, false);
111 return xhr.responseText;
114 if (typeof arguments != 'undefined') {
115 Module['arguments'] = arguments;
118 if (typeof console !== 'undefined') {
119 if (!Module['print']) Module['print'] = function print(x) {
122 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
126 // Probably a worker, and without console.log. We can do very little here...
127 var TRY_USE_DUMP = false;
128 if (!Module['print']) Module['print'] = (TRY_USE_DUMP && (typeof(dump) !== "undefined") ? (function(x) {
131 // self.postMessage(x); // enable this if you want stdout to be sent as messages
135 if (ENVIRONMENT_IS_WEB) {
136 window['Module'] = Module;
138 Module['load'] = importScripts;
142 // Unreachable because SHELL is dependant on the others
143 throw 'Unknown runtime environment. Where are we?';
146 function globalEval(x) {
149 if (!Module['load'] == 'undefined' && Module['read']) {
150 Module['load'] = function load(f) {
151 globalEval(Module['read'](f));
154 if (!Module['print']) {
155 Module['print'] = function(){};
157 if (!Module['printErr']) {
158 Module['printErr'] = Module['print'];
160 if (!Module['arguments']) {
161 Module['arguments'] = [];
163 // *** Environment setup code ***
166 Module.print = Module['print'];
167 Module.printErr = Module['printErr'];
170 Module['preRun'] = [];
171 Module['postRun'] = [];
173 // Merge back in the overrides
174 for (var key in moduleOverrides) {
175 if (moduleOverrides.hasOwnProperty(key)) {
176 Module[key] = moduleOverrides[key];
182 // === Auto-generated preamble library stuff ===
184 //========================================
185 // Runtime code shared with compiler
186 //========================================
189 stackSave: function () {
192 stackRestore: function (stackTop) {
195 forceAlign: function (target, quantum) {
196 quantum = quantum || 4;
197 if (quantum == 1) return target;
198 if (isNumber(target) && isNumber(quantum)) {
199 return Math.ceil(target/quantum)*quantum;
200 } else if (isNumber(quantum) && isPowerOfTwo(quantum)) {
201 return '(((' +target + ')+' + (quantum-1) + ')&' + -quantum + ')';
203 return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
205 isNumberType: function (type) {
206 return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
208 isPointerType: function isPointerType(type) {
209 return type[type.length-1] == '*';
211 isStructType: function isStructType(type) {
212 if (isPointerType(type)) return false;
213 if (isArrayType(type)) return true;
214 if (/<?\{ ?[^}]* ?\}>?/.test(type)) return true; // { i32, i8 } etc. - anonymous struct types
215 // See comment in isStructPointerType()
216 return type[0] == '%';
218 INT_TYPES: {"i1":0,"i8":0,"i16":0,"i32":0,"i64":0},
219 FLOAT_TYPES: {"float":0,"double":0},
220 or64: function (x, y) {
221 var l = (x | 0) | (y | 0);
222 var h = (Math.round(x / 4294967296) | Math.round(y / 4294967296)) * 4294967296;
225 and64: function (x, y) {
226 var l = (x | 0) & (y | 0);
227 var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 4294967296;
230 xor64: function (x, y) {
231 var l = (x | 0) ^ (y | 0);
232 var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 4294967296;
235 getNativeTypeSize: function (type) {
237 case 'i1': case 'i8': return 1;
238 case 'i16': return 2;
239 case 'i32': return 4;
240 case 'i64': return 8;
241 case 'float': return 4;
242 case 'double': return 8;
244 if (type[type.length-1] === '*') {
245 return Runtime.QUANTUM_SIZE; // A pointer
246 } else if (type[0] === 'i') {
247 var bits = parseInt(type.substr(1));
248 assert(bits % 8 === 0);
256 getNativeFieldSize: function (type) {
257 return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
259 dedup: function dedup(items, ident) {
262 return items.filter(function(item) {
263 if (seen[item[ident]]) return false;
264 seen[item[ident]] = true;
268 return items.filter(function(item) {
269 if (seen[item]) return false;
275 set: function set() {
276 var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
278 for (var i = 0; i < args.length; i++) {
284 getAlignSize: function (type, size, vararg) {
285 // we align i64s and doubles on 64-bit boundaries, unlike x86
286 if (!vararg && (type == 'i64' || type == 'double')) return 8;
287 if (!type) return Math.min(size, 8); // align structures internally to 64 bits
288 return Math.min(size || (type ? Runtime.getNativeFieldSize(type) : 0), Runtime.QUANTUM_SIZE);
290 calculateStructAlignment: function calculateStructAlignment(type) {
296 type.flatIndexes = type.fields.map(function(field) {
299 if (Runtime.isNumberType(field) || Runtime.isPointerType(field)) {
300 size = Runtime.getNativeTypeSize(field); // pack char; char; in structs, also char[X]s.
301 alignSize = Runtime.getAlignSize(field, size);
302 } else if (Runtime.isStructType(field)) {
303 if (field[1] === '0') {
304 // this is [0 x something]. When inside another structure like here, it must be at the end,
305 // and it adds no size
306 // XXX this happens in java-nbody for example... assert(index === type.fields.length, 'zero-length in the middle!');
308 if (Types.types[field]) {
309 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
311 alignSize = type.alignSize || QUANTUM_SIZE;
314 size = Types.types[field].flatSize;
315 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
317 } else if (field[0] == 'b') {
318 // bN, large number field, like a [N x i8]
319 size = field.substr(1)|0;
321 } else if (field[0] === '<') {
323 size = alignSize = Types.types[field].flatSize; // fully aligned
324 } else if (field[0] === 'i') {
325 // illegal integer field, that could not be legalized because it is an internal structure field
326 // it is ok to have such fields, if we just use them as markers of field size and nothing more complex
327 size = alignSize = parseInt(field.substr(1))/8;
328 assert(size % 1 === 0, 'cannot handle non-byte-size field ' + field);
330 assert(false, 'invalid type for calculateStructAlignment');
332 if (type.packed) alignSize = 1;
333 type.alignSize = Math.max(type.alignSize, alignSize);
334 var curr = Runtime.alignMemory(type.flatSize, alignSize); // if necessary, place this on aligned memory
335 type.flatSize = curr + size;
337 diffs.push(curr-prev);
342 if (type.name_ && type.name_[0] === '[') {
343 // arrays have 2 elements, so we get the proper difference. then we scale here. that way we avoid
344 // allocating a potentially huge array for [999999 x i8] etc.
345 type.flatSize = parseInt(type.name_.substr(1))*type.flatSize/2;
347 type.flatSize = Runtime.alignMemory(type.flatSize, type.alignSize);
348 if (diffs.length == 0) {
349 type.flatFactor = type.flatSize;
350 } else if (Runtime.dedup(diffs).length == 1) {
351 type.flatFactor = diffs[0];
353 type.needsFlattening = (type.flatFactor != 1);
354 return type.flatIndexes;
356 generateStructInfo: function (struct, typeName, offset) {
359 offset = offset || 0;
360 type = (typeof Types === 'undefined' ? Runtime.typeInfo : Types.types)[typeName];
361 if (!type) return null;
362 if (type.fields.length != struct.length) {
363 printErr('Number of named fields must match the type for ' + typeName + ': possibly duplicate struct names. Cannot return structInfo');
366 alignment = type.flatIndexes;
368 var type = { fields: struct.map(function(item) { return item[0] }) };
369 alignment = Runtime.calculateStructAlignment(type);
372 __size__: type.flatSize
375 struct.forEach(function(item, i) {
376 if (typeof item === 'string') {
377 ret[item] = alignment[i] + offset;
381 for (var k in item) key = k;
382 ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], alignment[i]);
386 struct.forEach(function(item, i) {
387 ret[item[1]] = alignment[i];
392 dynCall: function (sig, ptr, args) {
393 if (args && args.length) {
394 if (!args.splice) args = Array.prototype.slice.call(args);
395 args.splice(0, 0, ptr);
396 return Module['dynCall_' + sig].apply(null, args);
398 return Module['dynCall_' + sig].call(null, ptr);
401 functionPointers: [],
402 addFunction: function (func) {
403 for (var i = 0; i < Runtime.functionPointers.length; i++) {
404 if (!Runtime.functionPointers[i]) {
405 Runtime.functionPointers[i] = func;
409 throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
411 removeFunction: function (index) {
412 Runtime.functionPointers[(index-2)/2] = null;
414 getAsmConst: function (code, numArgs) {
415 // code is a constant string on the heap, so we can cache these
416 if (!Runtime.asmConstCache) Runtime.asmConstCache = {};
417 var func = Runtime.asmConstCache[code];
418 if (func) return func;
420 for (var i = 0; i < numArgs; i++) {
421 args.push(String.fromCharCode(36) + i); // $0, $1 etc
423 var source = Pointer_stringify(code);
424 if (source[0] === '"') {
425 // tolerate EM_ASM("..code..") even though EM_ASM(..code..) is correct
426 if (source.indexOf('"', 1) === source.length-1) {
427 source = source.substr(1, source.length-2);
429 // something invalid happened, e.g. EM_ASM("..code($0)..", input)
430 abort('invalid EM_ASM input |' + source + '|. Please use EM_ASM(..code..) (no quotes) or EM_ASM({ ..code($0).. }, input) (to input values)');
434 var evalled = eval('(function(' + args.join(',') + '){ ' + source + ' })'); // new Function does not allow upvars in node
436 Module.printErr('error in executing inline EM_ASM code: ' + e + ' on: \n\n' + source + '\n\nwith args |' + args + '| (make sure to use the right one out of EM_ASM, EM_ASM_ARGS, etc.)');
439 return Runtime.asmConstCache[code] = evalled;
441 warnOnce: function (text) {
442 if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
443 if (!Runtime.warnOnce.shown[text]) {
444 Runtime.warnOnce.shown[text] = 1;
445 Module.printErr(text);
449 getFuncWrapper: function (func, sig) {
451 if (!Runtime.funcWrappers[func]) {
452 Runtime.funcWrappers[func] = function dynCall_wrapper() {
453 return Runtime.dynCall(sig, func, arguments);
456 return Runtime.funcWrappers[func];
458 UTF8Processor: function () {
461 this.processCChar = function (code) {
464 if (buffer.length == 0) {
465 if ((code & 0x80) == 0x00) { // 0xxxxxxx
466 return String.fromCharCode(code);
469 if ((code & 0xE0) == 0xC0) { // 110xxxxx
471 } else if ((code & 0xF0) == 0xE0) { // 1110xxxx
482 if (needed > 0) return '';
490 if (buffer.length == 2) {
491 ret = String.fromCharCode(((c1 & 0x1F) << 6) | (c2 & 0x3F));
492 } else if (buffer.length == 3) {
493 ret = String.fromCharCode(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
495 // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
496 var codePoint = ((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) |
497 ((c3 & 0x3F) << 6) | (c4 & 0x3F);
498 ret = String.fromCharCode(
499 Math.floor((codePoint - 0x10000) / 0x400) + 0xD800,
500 (codePoint - 0x10000) % 0x400 + 0xDC00);
505 this.processJSString = function processJSString(string) {
506 /* TODO: use TextEncoder when present,
507 var encoder = new TextEncoder();
508 encoder['encoding'] = "utf-8";
509 var utf8Array = encoder['encode'](aMsg.data);
511 string = unescape(encodeURIComponent(string));
513 for (var i = 0; i < string.length; i++) {
514 ret.push(string.charCodeAt(i));
519 getCompilerSetting: function (name) {
520 throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work';
522 stackAlloc: function (size) { var ret = STACKTOP;STACKTOP = (STACKTOP + size)|0;STACKTOP = (((STACKTOP)+7)&-8); return ret; },
523 staticAlloc: function (size) { var ret = STATICTOP;STATICTOP = (STATICTOP + size)|0;STATICTOP = (((STATICTOP)+7)&-8); return ret; },
524 dynamicAlloc: function (size) { var ret = DYNAMICTOP;DYNAMICTOP = (DYNAMICTOP + size)|0;DYNAMICTOP = (((DYNAMICTOP)+7)&-8); if (DYNAMICTOP >= TOTAL_MEMORY) enlargeMemory();; return ret; },
525 alignMemory: function (size,quantum) { var ret = size = Math.ceil((size)/(quantum ? quantum : 8))*(quantum ? quantum : 8); return ret; },
526 makeBigInt: function (low,high,unsigned) { var ret = (unsigned ? ((+((low>>>0)))+((+((high>>>0)))*(+4294967296))) : ((+((low>>>0)))+((+((high|0)))*(+4294967296)))); return ret; },
533 Module['Runtime'] = Runtime;
543 //========================================
544 // Runtime essentials
545 //========================================
547 var __THREW__ = 0; // Used in checking for thrown exceptions.
549 var ABORT = false; // whether we are quitting the application. no code should run after this. set in exit() and abort()
553 // tempInt is used for 32-bit signed values or smaller. tempBigInt is used
554 // for 32-bit unsigned values or more than 32 bits. TODO: audit all uses of tempInt
555 var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI, tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD, tempDouble, tempFloat;
556 var tempI64, tempI64b;
557 var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRet7, tempRet8, tempRet9;
559 function assert(condition, text) {
561 abort('Assertion failed: ' + text);
565 var globalScope = this;
567 // C calling interface. A convenient way to call C functions (in C files, or
568 // defined with extern "C").
570 // Note: LLVM optimizations can inline and remove functions, after which you will not be
571 // able to call them. Closure can also do so. To avoid that, add your function to
572 // the exports using something like
574 // -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
576 // @param ident The name of the C function (note that C++ functions will be name-mangled - use extern "C")
577 // @param returnType The return type of the function, one of the JS types 'number', 'string' or 'array' (use 'number' for any C pointer, and
578 // 'array' for JavaScript arrays and typed arrays; note that arrays are 8-bit).
579 // @param argTypes An array of the types of arguments for the function (if there are no arguments, this can be ommitted). Types are as in returnType,
580 // except that 'array' is not possible (there is no way for us to know the length of the array)
581 // @param args An array of the arguments to the function, as native JS values (as in returnType)
582 // Note that string arguments will be stored on the stack (the JS string will become a C string on the stack).
583 // @return The return value, as a native JS value (as in returnType)
584 function ccall(ident, returnType, argTypes, args) {
585 return ccallFunc(getCFunc(ident), returnType, argTypes, args);
587 Module["ccall"] = ccall;
589 // Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
590 function getCFunc(ident) {
592 var func = Module['_' + ident]; // closure exported function
593 if (!func) func = eval('_' + ident); // explicit lookup
596 assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
600 // Internal function that does a C call using a function, not an identifier
601 function ccallFunc(func, returnType, argTypes, args) {
603 function toC(value, type) {
604 if (type == 'string') {
605 if (value === null || value === undefined || value === 0) return 0; // null string
606 value = intArrayFromString(value);
609 if (type == 'array') {
610 if (!stack) stack = Runtime.stackSave();
611 var ret = Runtime.stackAlloc(value.length);
612 writeArrayToMemory(value, ret);
617 function fromC(value, type) {
618 if (type == 'string') {
619 return Pointer_stringify(value);
621 assert(type != 'array');
625 var cArgs = args ? args.map(function(arg) {
626 return toC(arg, argTypes[i++]);
628 var ret = fromC(func.apply(null, cArgs), returnType);
629 if (stack) Runtime.stackRestore(stack);
633 // Returns a native JS wrapper for a C function. This is similar to ccall, but
634 // returns a function you can call repeatedly in a normal way. For example:
636 // var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
637 // alert(my_function(5, 22));
638 // alert(my_function(99, 12));
640 function cwrap(ident, returnType, argTypes) {
641 var func = getCFunc(ident);
643 return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(arguments));
646 Module["cwrap"] = cwrap;
648 // Sets a value in memory in a dynamic way at run-time. Uses the
649 // type data. This is the same as makeSetValue, except that
650 // makeSetValue is done at compile-time and generates the needed
651 // code then, whereas this function picks the right code at
653 // Note that setValue and getValue only do *aligned* writes and reads!
654 // Note that ccall uses JS types as for defining types, while setValue and
655 // getValue need LLVM types ('i8', 'i32') - this is a lower-level operation
656 function setValue(ptr, value, type, noSafe) {
658 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
660 case 'i1': HEAP8[(ptr)]=value; break;
661 case 'i8': HEAP8[(ptr)]=value; break;
662 case 'i16': HEAP16[((ptr)>>1)]=value; break;
663 case 'i32': HEAP32[((ptr)>>2)]=value; break;
664 case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= (+1) ? (tempDouble > (+0) ? ((Math_min((+(Math_floor((tempDouble)/(+4294967296)))), (+4294967295)))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/(+4294967296))))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
665 case 'float': HEAPF32[((ptr)>>2)]=value; break;
666 case 'double': HEAPF64[((ptr)>>3)]=value; break;
667 default: abort('invalid type for setValue: ' + type);
670 Module['setValue'] = setValue;
672 // Parallel to setValue.
673 function getValue(ptr, type, noSafe) {
675 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
677 case 'i1': return HEAP8[(ptr)];
678 case 'i8': return HEAP8[(ptr)];
679 case 'i16': return HEAP16[((ptr)>>1)];
680 case 'i32': return HEAP32[((ptr)>>2)];
681 case 'i64': return HEAP32[((ptr)>>2)];
682 case 'float': return HEAPF32[((ptr)>>2)];
683 case 'double': return HEAPF64[((ptr)>>3)];
684 default: abort('invalid type for setValue: ' + type);
688 Module['getValue'] = getValue;
690 var ALLOC_NORMAL = 0; // Tries to use _malloc()
691 var ALLOC_STACK = 1; // Lives for the duration of the current function call
692 var ALLOC_STATIC = 2; // Cannot be freed
693 var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
694 var ALLOC_NONE = 4; // Do not allocate
695 Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
696 Module['ALLOC_STACK'] = ALLOC_STACK;
697 Module['ALLOC_STATIC'] = ALLOC_STATIC;
698 Module['ALLOC_DYNAMIC'] = ALLOC_DYNAMIC;
699 Module['ALLOC_NONE'] = ALLOC_NONE;
701 // allocate(): This is for internal use. You can use it yourself as well, but the interface
702 // is a little tricky (see docs right below). The reason is that it is optimized
703 // for multiple syntaxes to save space in generated code. So you should
704 // normally not use allocate(), and instead allocate memory using _malloc(),
705 // initialize it with setValue(), and so forth.
706 // @slab: An array of data, or a number. If a number, then the size of the block to allocate,
707 // in *bytes* (note that this is sometimes confusing: the next parameter does not
709 // @types: Either an array of types, one for each byte (or 0 if no type at that position),
710 // or a single type which is used for the entire block. This only matters if there
711 // is initial data - if @slab is a number, then this does not matter at all and is
713 // @allocator: How to allocate memory, see ALLOC_*
714 function allocate(slab, types, allocator, ptr) {
716 if (typeof slab === 'number') {
724 var singleType = typeof types === 'string' ? types : null;
727 if (allocator == ALLOC_NONE) {
730 ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
735 assert((ret & 3) == 0);
736 stop = ret + (size & ~3);
737 for (; ptr < stop; ptr += 4) {
738 HEAP32[((ptr)>>2)]=0;
742 HEAP8[((ptr++)|0)]=0;
747 if (singleType === 'i8') {
748 if (slab.subarray || slab.slice) {
749 HEAPU8.set(slab, ret);
751 HEAPU8.set(new Uint8Array(slab), ret);
756 var i = 0, type, typeSize, previousType;
760 if (typeof curr === 'function') {
761 curr = Runtime.getFunctionIndex(curr);
764 type = singleType || types[i];
770 if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
772 setValue(ret+i, curr, type);
774 // no need to look up size unless type changes, so cache it
775 if (previousType !== type) {
776 typeSize = Runtime.getNativeTypeSize(type);
784 Module['allocate'] = allocate;
786 function Pointer_stringify(ptr, /* optional */ length) {
787 // TODO: use TextDecoder
788 // Find the length, and check for UTF while doing so
793 t = HEAPU8[(((ptr)+(i))|0)];
794 if (t >= 128) hasUtf = true;
795 else if (t == 0 && !length) break;
797 if (length && i == length) break;
799 if (!length) length = i;
804 var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
807 curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
808 ret = ret ? ret + curr : curr;
815 var utf8 = new Runtime.UTF8Processor();
816 for (i = 0; i < length; i++) {
817 t = HEAPU8[(((ptr)+(i))|0)];
818 ret += utf8.processCChar(t);
822 Module['Pointer_stringify'] = Pointer_stringify;
824 // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
825 // a copy of that string as a Javascript String object.
826 function UTF16ToString(ptr) {
831 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
835 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
836 str += String.fromCharCode(codeUnit);
839 Module['UTF16ToString'] = UTF16ToString;
841 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
842 // null-terminated and encoded in UTF16LE form. The copy will require at most (str.length*2+1)*2 bytes of space in the HEAP.
843 function stringToUTF16(str, outPtr) {
844 for(var i = 0; i < str.length; ++i) {
845 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
846 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
847 HEAP16[(((outPtr)+(i*2))>>1)]=codeUnit;
849 // Null-terminate the pointer to the HEAP.
850 HEAP16[(((outPtr)+(str.length*2))>>1)]=0;
852 Module['stringToUTF16'] = stringToUTF16;
854 // Given a pointer 'ptr' to a null-terminated UTF32LE-encoded string in the emscripten HEAP, returns
855 // a copy of that string as a Javascript String object.
856 function UTF32ToString(ptr) {
861 var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
865 // 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.
866 if (utf32 >= 0x10000) {
867 var ch = utf32 - 0x10000;
868 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
870 str += String.fromCharCode(utf32);
874 Module['UTF32ToString'] = UTF32ToString;
876 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
877 // null-terminated and encoded in UTF32LE form. The copy will require at most (str.length+1)*4 bytes of space in the HEAP,
878 // but can use less, since str.length does not return the number of characters in the string, but the number of UTF-16 code units in the string.
879 function stringToUTF32(str, outPtr) {
881 for(var iCodeUnit = 0; iCodeUnit < str.length; ++iCodeUnit) {
882 // 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.
883 var codeUnit = str.charCodeAt(iCodeUnit); // possibly a lead surrogate
884 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
885 var trailSurrogate = str.charCodeAt(++iCodeUnit);
886 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
888 HEAP32[(((outPtr)+(iChar*4))>>2)]=codeUnit;
891 // Null-terminate the pointer to the HEAP.
892 HEAP32[(((outPtr)+(iChar*4))>>2)]=0;
894 Module['stringToUTF32'] = stringToUTF32;
896 function demangle(func) {
910 'h': 'unsigned char',
911 't': 'unsigned short',
913 'm': 'unsigned long',
915 'y': 'unsigned long long',
922 if (x) Module.print(x);
925 for (var a = 0; a < i; a++) pre += ' ';
926 Module.print (pre + '^');
928 function parseNested() {
930 if (func[i] === 'K') i++; // ignore const
932 while (func[i] !== 'E') {
933 if (func[i] === 'S') { // substitution
935 var next = func.indexOf('_', i);
936 var num = func.substring(i, next) || 0;
937 parts.push(subs[num] || '?');
941 if (func[i] === 'C') { // constructor
942 parts.push(parts[parts.length-1]);
946 var size = parseInt(func.substr(i));
947 var pre = size.toString().length;
948 if (!size || !pre) { i--; break; } // counter i++ below us
949 var curr = func.substr(i + pre, size);
957 function parse(rawList, limit, allowVoid) { // main parser
958 limit = limit || Infinity;
959 var ret = '', list = [];
960 function flushList() {
961 return '(' + list.join(', ') + ')';
964 if (func[i] === 'N') {
966 name = parseNested().join('::');
968 if (limit === 0) return rawList ? [name] : name;
971 if (func[i] === 'K' || (first && func[i] === 'L')) i++; // ignore const and first 'L'
972 var size = parseInt(func.substr(i));
974 var pre = size.toString().length;
975 name = func.substr(i + pre, size);
980 if (func[i] === 'I') {
982 var iList = parse(true);
983 var iRet = parse(true, 1, true);
984 ret += iRet[0] + ' ' + name + '<' + iList.join(', ') + '>';
988 paramLoop: while (i < func.length && limit-- > 0) {
991 if (c in basicTypes) {
992 list.push(basicTypes[c]);
995 case 'P': list.push(parse(true, 1, true)[0] + '*'); break; // pointer
996 case 'R': list.push(parse(true, 1, true)[0] + '&'); break; // reference
997 case 'L': { // literal
998 i++; // skip basic type
999 var end = func.indexOf('E', i);
1001 list.push(func.substr(i, size));
1002 i += size + 2; // size + 'EE'
1005 case 'A': { // array
1006 var size = parseInt(func.substr(i));
1007 i += size.toString().length;
1008 if (func[i] !== '_') throw '?';
1010 list.push(parse(true, 1, true)[0] + ' [' + size + ']');
1013 case 'E': break paramLoop;
1014 default: ret += '?' + c; break paramLoop;
1018 if (!allowVoid && list.length === 1 && list[0] === 'void') list = []; // avoid (void)
1021 list.push(ret + '?');
1025 return ret + flushList();
1029 // Special-case the entry point, since its name differs from other name mangling.
1030 if (func == 'Object._main' || func == '_main') {
1033 if (typeof func === 'number') func = Pointer_stringify(func);
1034 if (func[0] !== '_') return func;
1035 if (func[1] !== '_') return func; // C function
1036 if (func[2] !== 'Z') return func;
1038 case 'n': return 'operator new()';
1039 case 'd': return 'operator delete()';
1047 function demangleAll(text) {
1048 return text.replace(/__Z[\w\d_]+/g, function(x) { var y = demangle(x); return x === y ? x : (x + ' [' + y + ']') });
1051 function stackTrace() {
1052 var stack = new Error().stack;
1053 return stack ? demangleAll(stack) : '(no stack trace available)'; // Stack trace is not available at least on IE10 and Safari 6.
1056 // Memory management
1058 var PAGE_SIZE = 4096;
1059 function alignMemoryPage(x) {
1060 return (x+4095)&-4096;
1064 var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
1066 var STATIC_BASE = 0, STATICTOP = 0, staticSealed = false; // static area
1067 var STACK_BASE = 0, STACKTOP = 0, STACK_MAX = 0; // stack area
1068 var DYNAMIC_BASE = 0, DYNAMICTOP = 0; // dynamic area handled by sbrk
1070 function enlargeMemory() {
1071 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 ALLOW_MEMORY_GROWTH which adjusts the size at runtime but prevents some optimizations, or (3) set Module.TOTAL_MEMORY before the program runs.');
1074 var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
1075 var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 134217728;
1076 var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
1078 var totalMemory = 4096;
1079 while (totalMemory < TOTAL_MEMORY || totalMemory < 2*TOTAL_STACK) {
1080 if (totalMemory < 16*1024*1024) {
1083 totalMemory += 16*1024*1024
1086 if (totalMemory !== TOTAL_MEMORY) {
1087 Module.printErr('increasing TOTAL_MEMORY to ' + totalMemory + ' to be more reasonable');
1088 TOTAL_MEMORY = totalMemory;
1091 // Initialize the runtime's memory
1092 // check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1093 assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
1094 'JS engine does not provide full typed array support');
1096 var buffer = new ArrayBuffer(TOTAL_MEMORY);
1097 HEAP8 = new Int8Array(buffer);
1098 HEAP16 = new Int16Array(buffer);
1099 HEAP32 = new Int32Array(buffer);
1100 HEAPU8 = new Uint8Array(buffer);
1101 HEAPU16 = new Uint16Array(buffer);
1102 HEAPU32 = new Uint32Array(buffer);
1103 HEAPF32 = new Float32Array(buffer);
1104 HEAPF64 = new Float64Array(buffer);
1106 // Endianness check (note: assumes compiler arch was little-endian)
1108 assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a little-endian system');
1110 Module['HEAP'] = HEAP;
1111 Module['HEAP8'] = HEAP8;
1112 Module['HEAP16'] = HEAP16;
1113 Module['HEAP32'] = HEAP32;
1114 Module['HEAPU8'] = HEAPU8;
1115 Module['HEAPU16'] = HEAPU16;
1116 Module['HEAPU32'] = HEAPU32;
1117 Module['HEAPF32'] = HEAPF32;
1118 Module['HEAPF64'] = HEAPF64;
1120 function callRuntimeCallbacks(callbacks) {
1121 while(callbacks.length > 0) {
1122 var callback = callbacks.shift();
1123 if (typeof callback == 'function') {
1127 var func = callback.func;
1128 if (typeof func === 'number') {
1129 if (callback.arg === undefined) {
1130 Runtime.dynCall('v', func);
1132 Runtime.dynCall('vi', func, [callback.arg]);
1135 func(callback.arg === undefined ? null : callback.arg);
1140 var __ATPRERUN__ = []; // functions called before the runtime is initialized
1141 var __ATINIT__ = []; // functions called during startup
1142 var __ATMAIN__ = []; // functions called when main() is to be run
1143 var __ATEXIT__ = []; // functions called during shutdown
1144 var __ATPOSTRUN__ = []; // functions called after the runtime has exited
1146 var runtimeInitialized = false;
1149 // compatibility - merge in anything from Module['preRun'] at this time
1150 if (Module['preRun']) {
1151 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1152 while (Module['preRun'].length) {
1153 addOnPreRun(Module['preRun'].shift());
1156 callRuntimeCallbacks(__ATPRERUN__);
1159 function ensureInitRuntime() {
1160 if (runtimeInitialized) return;
1161 runtimeInitialized = true;
1162 callRuntimeCallbacks(__ATINIT__);
1165 function preMain() {
1166 callRuntimeCallbacks(__ATMAIN__);
1169 function exitRuntime() {
1170 callRuntimeCallbacks(__ATEXIT__);
1173 function postRun() {
1174 // compatibility - merge in anything from Module['postRun'] at this time
1175 if (Module['postRun']) {
1176 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1177 while (Module['postRun'].length) {
1178 addOnPostRun(Module['postRun'].shift());
1181 callRuntimeCallbacks(__ATPOSTRUN__);
1184 function addOnPreRun(cb) {
1185 __ATPRERUN__.unshift(cb);
1187 Module['addOnPreRun'] = Module.addOnPreRun = addOnPreRun;
1189 function addOnInit(cb) {
1190 __ATINIT__.unshift(cb);
1192 Module['addOnInit'] = Module.addOnInit = addOnInit;
1194 function addOnPreMain(cb) {
1195 __ATMAIN__.unshift(cb);
1197 Module['addOnPreMain'] = Module.addOnPreMain = addOnPreMain;
1199 function addOnExit(cb) {
1200 __ATEXIT__.unshift(cb);
1202 Module['addOnExit'] = Module.addOnExit = addOnExit;
1204 function addOnPostRun(cb) {
1205 __ATPOSTRUN__.unshift(cb);
1207 Module['addOnPostRun'] = Module.addOnPostRun = addOnPostRun;
1211 // This processes a JS string into a C-line array of numbers, 0-terminated.
1212 // For LLVM-originating strings, see parser.js:parseLLVMString function
1213 function intArrayFromString(stringy, dontAddNull, length /* optional */) {
1214 var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
1216 ret.length = length;
1223 Module['intArrayFromString'] = intArrayFromString;
1225 function intArrayToString(array) {
1227 for (var i = 0; i < array.length; i++) {
1232 ret.push(String.fromCharCode(chr));
1234 return ret.join('');
1236 Module['intArrayToString'] = intArrayToString;
1238 // Write a Javascript array to somewhere in the heap
1239 function writeStringToMemory(string, buffer, dontAddNull) {
1240 var array = intArrayFromString(string, dontAddNull);
1242 while (i < array.length) {
1244 HEAP8[(((buffer)+(i))|0)]=chr;
1248 Module['writeStringToMemory'] = writeStringToMemory;
1250 function writeArrayToMemory(array, buffer) {
1251 for (var i = 0; i < array.length; i++) {
1252 HEAP8[(((buffer)+(i))|0)]=array[i];
1255 Module['writeArrayToMemory'] = writeArrayToMemory;
1257 function writeAsciiToMemory(str, buffer, dontAddNull) {
1258 for (var i = 0; i < str.length; i++) {
1259 HEAP8[(((buffer)+(i))|0)]=str.charCodeAt(i);
1261 if (!dontAddNull) HEAP8[(((buffer)+(str.length))|0)]=0;
1263 Module['writeAsciiToMemory'] = writeAsciiToMemory;
1265 function unSign(value, bits, ignore) {
1269 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
1270 : Math.pow(2, bits) + value;
1272 function reSign(value, bits, ignore) {
1276 var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1277 : Math.pow(2, bits-1);
1278 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
1279 // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1280 // TODO: In i64 mode 1, resign the two parts separately and safely
1281 value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1286 // check for imul support, and also for correctness ( https://bugs.webkit.org/show_bug.cgi?id=126345 )
1287 if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
1289 var al = a & 0xffff;
1291 var bl = b & 0xffff;
1292 return (al*bl + ((ah*bl + al*bh) << 16))|0;
1294 Math.imul = Math['imul'];
1297 var Math_abs = Math.abs;
1298 var Math_cos = Math.cos;
1299 var Math_sin = Math.sin;
1300 var Math_tan = Math.tan;
1301 var Math_acos = Math.acos;
1302 var Math_asin = Math.asin;
1303 var Math_atan = Math.atan;
1304 var Math_atan2 = Math.atan2;
1305 var Math_exp = Math.exp;
1306 var Math_log = Math.log;
1307 var Math_sqrt = Math.sqrt;
1308 var Math_ceil = Math.ceil;
1309 var Math_floor = Math.floor;
1310 var Math_pow = Math.pow;
1311 var Math_imul = Math.imul;
1312 var Math_fround = Math.fround;
1313 var Math_min = Math.min;
1315 // A counter of dependencies for calling run(). If we need to
1316 // do asynchronous work before running, increment this and
1317 // decrement it. Incrementing must happen in a place like
1318 // PRE_RUN_ADDITIONS (used by emcc to add file preloading).
1319 // Note that you can add dependencies in preRun, even though
1320 // it happens right before run - run will be postponed until
1321 // the dependencies are met.
1322 var runDependencies = 0;
1323 var runDependencyWatcher = null;
1324 var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1326 function addRunDependency(id) {
1328 if (Module['monitorRunDependencies']) {
1329 Module['monitorRunDependencies'](runDependencies);
1332 Module['addRunDependency'] = addRunDependency;
1333 function removeRunDependency(id) {
1335 if (Module['monitorRunDependencies']) {
1336 Module['monitorRunDependencies'](runDependencies);
1338 if (runDependencies == 0) {
1339 if (runDependencyWatcher !== null) {
1340 clearInterval(runDependencyWatcher);
1341 runDependencyWatcher = null;
1343 if (dependenciesFulfilled) {
1344 var callback = dependenciesFulfilled;
1345 dependenciesFulfilled = null;
1346 callback(); // can add another dependenciesFulfilled
1350 Module['removeRunDependency'] = removeRunDependency;
1352 Module["preloadedImages"] = {}; // maps url to image data
1353 Module["preloadedAudios"] = {}; // maps url to audio data
1356 var memoryInitializer = null;
1366 STATICTOP = STATIC_BASE + Runtime.alignMemory(35);
1367 /* global initializers */ __ATINIT__.push();
1370 /* memory initializer */ allocate([101,114,114,111,114,58,32,37,100,92,110,0,0,0,0,0,102,105,110,97,108,58,32,37,100,58,37,100,46,10,0,0], "i8", ALLOC_NONE, Runtime.GLOBAL_BASE);
1375 var tempDoublePtr = Runtime.alignMemory(allocate(12, "i8", ALLOC_STATIC), 8);
1377 assert(tempDoublePtr % 8 == 0);
1379 function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1381 HEAP8[tempDoublePtr] = HEAP8[ptr];
1383 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1385 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1387 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1391 function copyTempDouble(ptr) {
1393 HEAP8[tempDoublePtr] = HEAP8[ptr];
1395 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1397 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1399 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1401 HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1403 HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1405 HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1407 HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1412 function _malloc(bytes) {
1413 /* Over-allocate to make sure it is byte-aligned by 8.
1414 * This will leak memory, but this is only the dummy
1415 * implementation (replaced by dlmalloc normally) so
1418 var ptr = Runtime.dynamicAlloc(bytes + 8);
1419 return (ptr+8) & 0xFFFFFFF8;
1421 Module["_malloc"] = _malloc;
1426 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};
1428 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"};
1431 var ___errno_state=0;function ___setErrNo(value) {
1432 // For convenient setting and returning of errno.
1433 HEAP32[((___errno_state)>>2)]=value;
1437 var TTY={ttys:[],init:function () {
1438 // https://github.com/kripken/emscripten/pull/1555
1439 // if (ENVIRONMENT_IS_NODE) {
1440 // // currently, FS.init does not distinguish if process.stdin is a file or TTY
1441 // // device, it always assumes it's a TTY device. because of this, we're forcing
1442 // // process.stdin to UTF8 encoding to at least make stdin reading compatible
1443 // // with text files until FS.init can be refactored.
1444 // process['stdin']['setEncoding']('utf8');
1446 },shutdown:function () {
1447 // https://github.com/kripken/emscripten/pull/1555
1448 // if (ENVIRONMENT_IS_NODE) {
1449 // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
1450 // // 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
1451 // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
1452 // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
1453 // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
1454 // process['stdin']['pause']();
1456 },register:function (dev, ops) {
1457 TTY.ttys[dev] = { input: [], output: [], ops: ops };
1458 FS.registerDevice(dev, TTY.stream_ops);
1459 },stream_ops:{open:function (stream) {
1460 var tty = TTY.ttys[stream.node.rdev];
1462 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1465 stream.seekable = false;
1466 },close:function (stream) {
1467 // flush any pending line data
1468 if (stream.tty.output.length) {
1469 stream.tty.ops.put_char(stream.tty, 10);
1471 },read:function (stream, buffer, offset, length, pos /* ignored */) {
1472 if (!stream.tty || !stream.tty.ops.get_char) {
1473 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1476 for (var i = 0; i < length; i++) {
1479 result = stream.tty.ops.get_char(stream.tty);
1481 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1483 if (result === undefined && bytesRead === 0) {
1484 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
1486 if (result === null || result === undefined) break;
1488 buffer[offset+i] = result;
1491 stream.node.timestamp = Date.now();
1494 },write:function (stream, buffer, offset, length, pos) {
1495 if (!stream.tty || !stream.tty.ops.put_char) {
1496 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1498 for (var i = 0; i < length; i++) {
1500 stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
1502 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1506 stream.node.timestamp = Date.now();
1509 }},default_tty_ops:{get_char:function (tty) {
1510 if (!tty.input.length) {
1512 if (ENVIRONMENT_IS_NODE) {
1513 result = process['stdin']['read']();
1515 if (process['stdin']['_readableState'] && process['stdin']['_readableState']['ended']) {
1518 return undefined; // no data available
1520 } else if (typeof window != 'undefined' &&
1521 typeof window.prompt == 'function') {
1523 result = window.prompt('Input: '); // returns null on cancel
1524 if (result !== null) {
1527 } else if (typeof readline == 'function') {
1529 result = readline();
1530 if (result !== null) {
1537 tty.input = intArrayFromString(result, true);
1539 return tty.input.shift();
1540 },put_char:function (tty, val) {
1541 if (val === null || val === 10) {
1542 Module['print'](tty.output.join(''));
1545 tty.output.push(TTY.utf8.processCChar(val));
1547 }},default_tty1_ops:{put_char:function (tty, val) {
1548 if (val === null || val === 10) {
1549 Module['printErr'](tty.output.join(''));
1552 tty.output.push(TTY.utf8.processCChar(val));
1556 var MEMFS={ops_table:null,CONTENT_OWNING:1,CONTENT_FLEXIBLE:2,CONTENT_FIXED:3,mount:function (mount) {
1557 return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
1558 },createNode:function (parent, name, mode, dev) {
1559 if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
1561 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
1563 if (!MEMFS.ops_table) {
1567 getattr: MEMFS.node_ops.getattr,
1568 setattr: MEMFS.node_ops.setattr,
1569 lookup: MEMFS.node_ops.lookup,
1570 mknod: MEMFS.node_ops.mknod,
1571 rename: MEMFS.node_ops.rename,
1572 unlink: MEMFS.node_ops.unlink,
1573 rmdir: MEMFS.node_ops.rmdir,
1574 readdir: MEMFS.node_ops.readdir,
1575 symlink: MEMFS.node_ops.symlink
1578 llseek: MEMFS.stream_ops.llseek
1583 getattr: MEMFS.node_ops.getattr,
1584 setattr: MEMFS.node_ops.setattr
1587 llseek: MEMFS.stream_ops.llseek,
1588 read: MEMFS.stream_ops.read,
1589 write: MEMFS.stream_ops.write,
1590 allocate: MEMFS.stream_ops.allocate,
1591 mmap: MEMFS.stream_ops.mmap
1596 getattr: MEMFS.node_ops.getattr,
1597 setattr: MEMFS.node_ops.setattr,
1598 readlink: MEMFS.node_ops.readlink
1604 getattr: MEMFS.node_ops.getattr,
1605 setattr: MEMFS.node_ops.setattr
1607 stream: FS.chrdev_stream_ops
1611 var node = FS.createNode(parent, name, mode, dev);
1612 if (FS.isDir(node.mode)) {
1613 node.node_ops = MEMFS.ops_table.dir.node;
1614 node.stream_ops = MEMFS.ops_table.dir.stream;
1616 } else if (FS.isFile(node.mode)) {
1617 node.node_ops = MEMFS.ops_table.file.node;
1618 node.stream_ops = MEMFS.ops_table.file.stream;
1620 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1621 } else if (FS.isLink(node.mode)) {
1622 node.node_ops = MEMFS.ops_table.link.node;
1623 node.stream_ops = MEMFS.ops_table.link.stream;
1624 } else if (FS.isChrdev(node.mode)) {
1625 node.node_ops = MEMFS.ops_table.chrdev.node;
1626 node.stream_ops = MEMFS.ops_table.chrdev.stream;
1628 node.timestamp = Date.now();
1629 // add the new node to the parent
1631 parent.contents[name] = node;
1634 },ensureFlexible:function (node) {
1635 if (node.contentMode !== MEMFS.CONTENT_FLEXIBLE) {
1636 var contents = node.contents;
1637 node.contents = Array.prototype.slice.call(contents);
1638 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1640 },node_ops:{getattr:function (node) {
1642 // device numbers reuse inode numbers.
1643 attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1645 attr.mode = node.mode;
1649 attr.rdev = node.rdev;
1650 if (FS.isDir(node.mode)) {
1652 } else if (FS.isFile(node.mode)) {
1653 attr.size = node.contents.length;
1654 } else if (FS.isLink(node.mode)) {
1655 attr.size = node.link.length;
1659 attr.atime = new Date(node.timestamp);
1660 attr.mtime = new Date(node.timestamp);
1661 attr.ctime = new Date(node.timestamp);
1662 // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
1663 // but this is not required by the standard.
1664 attr.blksize = 4096;
1665 attr.blocks = Math.ceil(attr.size / attr.blksize);
1667 },setattr:function (node, attr) {
1668 if (attr.mode !== undefined) {
1669 node.mode = attr.mode;
1671 if (attr.timestamp !== undefined) {
1672 node.timestamp = attr.timestamp;
1674 if (attr.size !== undefined) {
1675 MEMFS.ensureFlexible(node);
1676 var contents = node.contents;
1677 if (attr.size < contents.length) contents.length = attr.size;
1678 else while (attr.size > contents.length) contents.push(0);
1680 },lookup:function (parent, name) {
1681 throw FS.genericErrors[ERRNO_CODES.ENOENT];
1682 },mknod:function (parent, name, mode, dev) {
1683 return MEMFS.createNode(parent, name, mode, dev);
1684 },rename:function (old_node, new_dir, new_name) {
1685 // if we're overwriting a directory at new_name, make sure it's empty.
1686 if (FS.isDir(old_node.mode)) {
1689 new_node = FS.lookupNode(new_dir, new_name);
1693 for (var i in new_node.contents) {
1694 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1698 // do the internal rewiring
1699 delete old_node.parent.contents[old_node.name];
1700 old_node.name = new_name;
1701 new_dir.contents[new_name] = old_node;
1702 old_node.parent = new_dir;
1703 },unlink:function (parent, name) {
1704 delete parent.contents[name];
1705 },rmdir:function (parent, name) {
1706 var node = FS.lookupNode(parent, name);
1707 for (var i in node.contents) {
1708 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1710 delete parent.contents[name];
1711 },readdir:function (node) {
1712 var entries = ['.', '..']
1713 for (var key in node.contents) {
1714 if (!node.contents.hasOwnProperty(key)) {
1720 },symlink:function (parent, newname, oldpath) {
1721 var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
1722 node.link = oldpath;
1724 },readlink:function (node) {
1725 if (!FS.isLink(node.mode)) {
1726 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1729 }},stream_ops:{read:function (stream, buffer, offset, length, position) {
1730 var contents = stream.node.contents;
1731 if (position >= contents.length)
1733 var size = Math.min(contents.length - position, length);
1735 if (size > 8 && contents.subarray) { // non-trivial, and typed array
1736 buffer.set(contents.subarray(position, position + size), offset);
1739 for (var i = 0; i < size; i++) {
1740 buffer[offset + i] = contents[position + i];
1744 },write:function (stream, buffer, offset, length, position, canOwn) {
1745 var node = stream.node;
1746 node.timestamp = Date.now();
1747 var contents = node.contents;
1748 if (length && contents.length === 0 && position === 0 && buffer.subarray) {
1749 // just replace it with the new data
1750 if (canOwn && offset === 0) {
1751 node.contents = buffer; // this could be a subarray of Emscripten HEAP, or allocated from some other source.
1752 node.contentMode = (buffer.buffer === HEAP8.buffer) ? MEMFS.CONTENT_OWNING : MEMFS.CONTENT_FIXED;
1754 node.contents = new Uint8Array(buffer.subarray(offset, offset+length));
1755 node.contentMode = MEMFS.CONTENT_FIXED;
1759 MEMFS.ensureFlexible(node);
1760 var contents = node.contents;
1761 while (contents.length < position) contents.push(0);
1762 for (var i = 0; i < length; i++) {
1763 contents[position + i] = buffer[offset + i];
1766 },llseek:function (stream, offset, whence) {
1767 var position = offset;
1768 if (whence === 1) { // SEEK_CUR.
1769 position += stream.position;
1770 } else if (whence === 2) { // SEEK_END.
1771 if (FS.isFile(stream.node.mode)) {
1772 position += stream.node.contents.length;
1776 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1778 stream.ungotten = [];
1779 stream.position = position;
1781 },allocate:function (stream, offset, length) {
1782 MEMFS.ensureFlexible(stream.node);
1783 var contents = stream.node.contents;
1784 var limit = offset + length;
1785 while (limit > contents.length) contents.push(0);
1786 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
1787 if (!FS.isFile(stream.node.mode)) {
1788 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1792 var contents = stream.node.contents;
1793 // Only make a new copy when MAP_PRIVATE is specified.
1794 if ( !(flags & 2) &&
1795 (contents.buffer === buffer || contents.buffer === buffer.buffer) ) {
1796 // We can't emulate MAP_SHARED when the file is not backed by the buffer
1797 // we're mapping to (e.g. the HEAP buffer).
1799 ptr = contents.byteOffset;
1801 // Try to avoid unnecessary slices.
1802 if (position > 0 || position + length < contents.length) {
1803 if (contents.subarray) {
1804 contents = contents.subarray(position, position + length);
1806 contents = Array.prototype.slice.call(contents, position, position + length);
1810 ptr = _malloc(length);
1812 throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
1814 buffer.set(contents, ptr);
1816 return { ptr: ptr, allocated: allocated };
1819 var IDBFS={dbs:{},indexedDB:function () {
1820 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
1821 },DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function (mount) {
1822 // reuse all of the core MEMFS functionality
1823 return MEMFS.mount.apply(null, arguments);
1824 },syncfs:function (mount, populate, callback) {
1825 IDBFS.getLocalSet(mount, function(err, local) {
1826 if (err) return callback(err);
1828 IDBFS.getRemoteSet(mount, function(err, remote) {
1829 if (err) return callback(err);
1831 var src = populate ? remote : local;
1832 var dst = populate ? local : remote;
1834 IDBFS.reconcile(src, dst, callback);
1837 },getDB:function (name, callback) {
1838 // check the cache first
1839 var db = IDBFS.dbs[name];
1841 return callback(null, db);
1846 req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
1850 req.onupgradeneeded = function(e) {
1851 var db = e.target.result;
1852 var transaction = e.target.transaction;
1856 if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
1857 fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
1859 fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
1862 fileStore.createIndex('timestamp', 'timestamp', { unique: false });
1864 req.onsuccess = function() {
1868 IDBFS.dbs[name] = db;
1871 req.onerror = function() {
1872 callback(this.error);
1874 },getLocalSet:function (mount, callback) {
1877 function isRealDir(p) {
1878 return p !== '.' && p !== '..';
1880 function toAbsolute(root) {
1881 return function(p) {
1882 return PATH.join2(root, p);
1886 var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
1888 while (check.length) {
1889 var path = check.pop();
1893 stat = FS.stat(path);
1898 if (FS.isDir(stat.mode)) {
1899 check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
1902 entries[path] = { timestamp: stat.mtime };
1905 return callback(null, { type: 'local', entries: entries });
1906 },getRemoteSet:function (mount, callback) {
1909 IDBFS.getDB(mount.mountpoint, function(err, db) {
1910 if (err) return callback(err);
1912 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
1913 transaction.onerror = function() { callback(this.error); };
1915 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
1916 var index = store.index('timestamp');
1918 index.openKeyCursor().onsuccess = function(event) {
1919 var cursor = event.target.result;
1922 return callback(null, { type: 'remote', db: db, entries: entries });
1925 entries[cursor.primaryKey] = { timestamp: cursor.key };
1930 },loadLocalEntry:function (path, callback) {
1934 var lookup = FS.lookupPath(path);
1936 stat = FS.stat(path);
1941 if (FS.isDir(stat.mode)) {
1942 return callback(null, { timestamp: stat.mtime, mode: stat.mode });
1943 } else if (FS.isFile(stat.mode)) {
1944 return callback(null, { timestamp: stat.mtime, mode: stat.mode, contents: node.contents });
1946 return callback(new Error('node type not supported'));
1948 },storeLocalEntry:function (path, entry, callback) {
1950 if (FS.isDir(entry.mode)) {
1951 FS.mkdir(path, entry.mode);
1952 } else if (FS.isFile(entry.mode)) {
1953 FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: true });
1955 return callback(new Error('node type not supported'));
1958 FS.utime(path, entry.timestamp, entry.timestamp);
1964 },removeLocalEntry:function (path, callback) {
1966 var lookup = FS.lookupPath(path);
1967 var stat = FS.stat(path);
1969 if (FS.isDir(stat.mode)) {
1971 } else if (FS.isFile(stat.mode)) {
1979 },loadRemoteEntry:function (store, path, callback) {
1980 var req = store.get(path);
1981 req.onsuccess = function(event) { callback(null, event.target.result); };
1982 req.onerror = function() { callback(this.error); };
1983 },storeRemoteEntry:function (store, path, entry, callback) {
1984 var req = store.put(entry, path);
1985 req.onsuccess = function() { callback(null); };
1986 req.onerror = function() { callback(this.error); };
1987 },removeRemoteEntry:function (store, path, callback) {
1988 var req = store.delete(path);
1989 req.onsuccess = function() { callback(null); };
1990 req.onerror = function() { callback(this.error); };
1991 },reconcile:function (src, dst, callback) {
1995 Object.keys(src.entries).forEach(function (key) {
1996 var e = src.entries[key];
1997 var e2 = dst.entries[key];
1998 if (!e2 || e.timestamp > e2.timestamp) {
2005 Object.keys(dst.entries).forEach(function (key) {
2006 var e = dst.entries[key];
2007 var e2 = src.entries[key];
2015 return callback(null);
2018 var errored = false;
2020 var db = src.type === 'remote' ? src.db : dst.db;
2021 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
2022 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2024 function done(err) {
2026 if (!done.errored) {
2027 done.errored = true;
2028 return callback(err);
2032 if (++completed >= total) {
2033 return callback(null);
2037 transaction.onerror = function() { done(this.error); };
2039 // sort paths in ascending order so directory entries are created
2040 // before the files inside them
2041 create.sort().forEach(function (path) {
2042 if (dst.type === 'local') {
2043 IDBFS.loadRemoteEntry(store, path, function (err, entry) {
2044 if (err) return done(err);
2045 IDBFS.storeLocalEntry(path, entry, done);
2048 IDBFS.loadLocalEntry(path, function (err, entry) {
2049 if (err) return done(err);
2050 IDBFS.storeRemoteEntry(store, path, entry, done);
2055 // sort paths in descending order so files are deleted before their
2056 // parent directories
2057 remove.sort().reverse().forEach(function(path) {
2058 if (dst.type === 'local') {
2059 IDBFS.removeLocalEntry(path, done);
2061 IDBFS.removeRemoteEntry(store, path, done);
2066 var NODEFS={isWindows:false,staticInit:function () {
2067 NODEFS.isWindows = !!process.platform.match(/^win/);
2068 },mount:function (mount) {
2069 assert(ENVIRONMENT_IS_NODE);
2070 return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
2071 },createNode:function (parent, name, mode, dev) {
2072 if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
2073 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2075 var node = FS.createNode(parent, name, mode);
2076 node.node_ops = NODEFS.node_ops;
2077 node.stream_ops = NODEFS.stream_ops;
2079 },getMode:function (path) {
2082 stat = fs.lstatSync(path);
2083 if (NODEFS.isWindows) {
2084 // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
2085 // propagate write bits to execute bits.
2086 stat.mode = stat.mode | ((stat.mode & 146) >> 1);
2089 if (!e.code) throw e;
2090 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2093 },realPath:function (node) {
2095 while (node.parent !== node) {
2096 parts.push(node.name);
2099 parts.push(node.mount.opts.root);
2101 return PATH.join.apply(null, parts);
2102 },flagsToPermissionStringMap:{0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"},flagsToPermissionString:function (flags) {
2103 if (flags in NODEFS.flagsToPermissionStringMap) {
2104 return NODEFS.flagsToPermissionStringMap[flags];
2108 },node_ops:{getattr:function (node) {
2109 var path = NODEFS.realPath(node);
2112 stat = fs.lstatSync(path);
2114 if (!e.code) throw e;
2115 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2117 // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
2118 // See http://support.microsoft.com/kb/140365
2119 if (NODEFS.isWindows && !stat.blksize) {
2120 stat.blksize = 4096;
2122 if (NODEFS.isWindows && !stat.blocks) {
2123 stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
2137 blksize: stat.blksize,
2140 },setattr:function (node, attr) {
2141 var path = NODEFS.realPath(node);
2143 if (attr.mode !== undefined) {
2144 fs.chmodSync(path, attr.mode);
2145 // update the common node structure mode as well
2146 node.mode = attr.mode;
2148 if (attr.timestamp !== undefined) {
2149 var date = new Date(attr.timestamp);
2150 fs.utimesSync(path, date, date);
2152 if (attr.size !== undefined) {
2153 fs.truncateSync(path, attr.size);
2156 if (!e.code) throw e;
2157 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2159 },lookup:function (parent, name) {
2160 var path = PATH.join2(NODEFS.realPath(parent), name);
2161 var mode = NODEFS.getMode(path);
2162 return NODEFS.createNode(parent, name, mode);
2163 },mknod:function (parent, name, mode, dev) {
2164 var node = NODEFS.createNode(parent, name, mode, dev);
2165 // create the backing node for this in the fs root as well
2166 var path = NODEFS.realPath(node);
2168 if (FS.isDir(node.mode)) {
2169 fs.mkdirSync(path, node.mode);
2171 fs.writeFileSync(path, '', { mode: node.mode });
2174 if (!e.code) throw e;
2175 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2178 },rename:function (oldNode, newDir, newName) {
2179 var oldPath = NODEFS.realPath(oldNode);
2180 var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
2182 fs.renameSync(oldPath, newPath);
2184 if (!e.code) throw e;
2185 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2187 },unlink:function (parent, name) {
2188 var path = PATH.join2(NODEFS.realPath(parent), name);
2190 fs.unlinkSync(path);
2192 if (!e.code) throw e;
2193 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2195 },rmdir:function (parent, name) {
2196 var path = PATH.join2(NODEFS.realPath(parent), name);
2200 if (!e.code) throw e;
2201 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2203 },readdir:function (node) {
2204 var path = NODEFS.realPath(node);
2206 return fs.readdirSync(path);
2208 if (!e.code) throw e;
2209 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2211 },symlink:function (parent, newName, oldPath) {
2212 var newPath = PATH.join2(NODEFS.realPath(parent), newName);
2214 fs.symlinkSync(oldPath, newPath);
2216 if (!e.code) throw e;
2217 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2219 },readlink:function (node) {
2220 var path = NODEFS.realPath(node);
2222 return fs.readlinkSync(path);
2224 if (!e.code) throw e;
2225 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2227 }},stream_ops:{open:function (stream) {
2228 var path = NODEFS.realPath(stream.node);
2230 if (FS.isFile(stream.node.mode)) {
2231 stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
2234 if (!e.code) throw e;
2235 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2237 },close:function (stream) {
2239 if (FS.isFile(stream.node.mode) && stream.nfd) {
2240 fs.closeSync(stream.nfd);
2243 if (!e.code) throw e;
2244 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2246 },read:function (stream, buffer, offset, length, position) {
2247 // FIXME this is terrible.
2248 var nbuffer = new Buffer(length);
2251 res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
2253 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2256 for (var i = 0; i < res; i++) {
2257 buffer[offset + i] = nbuffer[i];
2261 },write:function (stream, buffer, offset, length, position) {
2262 // FIXME this is terrible.
2263 var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
2266 res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
2268 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2271 },llseek:function (stream, offset, whence) {
2272 var position = offset;
2273 if (whence === 1) { // SEEK_CUR.
2274 position += stream.position;
2275 } else if (whence === 2) { // SEEK_END.
2276 if (FS.isFile(stream.node.mode)) {
2278 var stat = fs.fstatSync(stream.nfd);
2279 position += stat.size;
2281 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2287 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2290 stream.position = position;
2294 var _stdin=allocate(1, "i32*", ALLOC_STATIC);
2296 var _stdout=allocate(1, "i32*", ALLOC_STATIC);
2298 var _stderr=allocate(1, "i32*", ALLOC_STATIC);
2300 function _fflush(stream) {
2301 // int fflush(FILE *stream);
2302 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fflush.html
2303 // we don't currently perform any user-space buffering of data
2304 }var FS={root:null,mounts:[],devices:[null],streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},handleFSError:function (e) {
2305 if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
2306 return ___setErrNo(e.errno);
2307 },lookupPath:function (path, opts) {
2308 path = PATH.resolve(FS.cwd(), path);
2315 for (var key in defaults) {
2316 if (opts[key] === undefined) {
2317 opts[key] = defaults[key];
2321 if (opts.recurse_count > 8) { // max recursive lookup of 8
2322 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2326 var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2330 // start at the root
2331 var current = FS.root;
2332 var current_path = '/';
2334 for (var i = 0; i < parts.length; i++) {
2335 var islast = (i === parts.length-1);
2336 if (islast && opts.parent) {
2341 current = FS.lookupNode(current, parts[i]);
2342 current_path = PATH.join2(current_path, parts[i]);
2344 // jump to the mount's root node if this is a mountpoint
2345 if (FS.isMountpoint(current)) {
2346 if (!islast || (islast && opts.follow_mount)) {
2347 current = current.mounted.root;
2351 // by default, lookupPath will not follow a symlink if it is the final path component.
2352 // setting opts.follow = true will override this behavior.
2353 if (!islast || opts.follow) {
2355 while (FS.isLink(current.mode)) {
2356 var link = FS.readlink(current_path);
2357 current_path = PATH.resolve(PATH.dirname(current_path), link);
2359 var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
2360 current = lookup.node;
2362 if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
2363 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2369 return { path: current_path, node: current };
2370 },getPath:function (node) {
2373 if (FS.isRoot(node)) {
2374 var mount = node.mount.mountpoint;
2375 if (!path) return mount;
2376 return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
2378 path = path ? node.name + '/' + path : node.name;
2381 },hashName:function (parentid, name) {
2385 for (var i = 0; i < name.length; i++) {
2386 hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2388 return ((parentid + hash) >>> 0) % FS.nameTable.length;
2389 },hashAddNode:function (node) {
2390 var hash = FS.hashName(node.parent.id, node.name);
2391 node.name_next = FS.nameTable[hash];
2392 FS.nameTable[hash] = node;
2393 },hashRemoveNode:function (node) {
2394 var hash = FS.hashName(node.parent.id, node.name);
2395 if (FS.nameTable[hash] === node) {
2396 FS.nameTable[hash] = node.name_next;
2398 var current = FS.nameTable[hash];
2400 if (current.name_next === node) {
2401 current.name_next = node.name_next;
2404 current = current.name_next;
2407 },lookupNode:function (parent, name) {
2408 var err = FS.mayLookup(parent);
2410 throw new FS.ErrnoError(err);
2412 var hash = FS.hashName(parent.id, name);
2413 for (var node = FS.nameTable[hash]; node; node = node.name_next) {
2414 var nodeName = node.name;
2415 if (node.parent.id === parent.id && nodeName === name) {
2419 // if we failed to find it in the cache, call into the VFS
2420 return FS.lookup(parent, name);
2421 },createNode:function (parent, name, mode, rdev) {
2423 FS.FSNode = function(parent, name, mode, rdev) {
2425 parent = this; // root node sets parent to itself
2427 this.parent = parent;
2428 this.mount = parent.mount;
2429 this.mounted = null;
2430 this.id = FS.nextInode++;
2434 this.stream_ops = {};
2438 FS.FSNode.prototype = {};
2441 var readMode = 292 | 73;
2442 var writeMode = 146;
2444 // NOTE we must use Object.defineProperties instead of individual calls to
2445 // Object.defineProperty in order to make closure compiler happy
2446 Object.defineProperties(FS.FSNode.prototype, {
2448 get: function() { return (this.mode & readMode) === readMode; },
2449 set: function(val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
2452 get: function() { return (this.mode & writeMode) === writeMode; },
2453 set: function(val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
2456 get: function() { return FS.isDir(this.mode); },
2459 get: function() { return FS.isChrdev(this.mode); },
2464 var node = new FS.FSNode(parent, name, mode, rdev);
2466 FS.hashAddNode(node);
2469 },destroyNode:function (node) {
2470 FS.hashRemoveNode(node);
2471 },isRoot:function (node) {
2472 return node === node.parent;
2473 },isMountpoint:function (node) {
2474 return !!node.mounted;
2475 },isFile:function (mode) {
2476 return (mode & 61440) === 32768;
2477 },isDir:function (mode) {
2478 return (mode & 61440) === 16384;
2479 },isLink:function (mode) {
2480 return (mode & 61440) === 40960;
2481 },isChrdev:function (mode) {
2482 return (mode & 61440) === 8192;
2483 },isBlkdev:function (mode) {
2484 return (mode & 61440) === 24576;
2485 },isFIFO:function (mode) {
2486 return (mode & 61440) === 4096;
2487 },isSocket:function (mode) {
2488 return (mode & 49152) === 49152;
2489 },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) {
2490 var flags = FS.flagModes[str];
2491 if (typeof flags === 'undefined') {
2492 throw new Error('Unknown file open mode: ' + str);
2495 },flagsToPermissionString:function (flag) {
2496 var accmode = flag & 2097155;
2497 var perms = ['r', 'w', 'rw'][accmode];
2502 },nodePermissions:function (node, perms) {
2503 if (FS.ignorePermissions) {
2506 // return 0 if any user, group or owner bits are set.
2507 if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
2508 return ERRNO_CODES.EACCES;
2509 } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
2510 return ERRNO_CODES.EACCES;
2511 } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
2512 return ERRNO_CODES.EACCES;
2515 },mayLookup:function (dir) {
2516 return FS.nodePermissions(dir, 'x');
2517 },mayCreate:function (dir, name) {
2519 var node = FS.lookupNode(dir, name);
2520 return ERRNO_CODES.EEXIST;
2523 return FS.nodePermissions(dir, 'wx');
2524 },mayDelete:function (dir, name, isdir) {
2527 node = FS.lookupNode(dir, name);
2531 var err = FS.nodePermissions(dir, 'wx');
2536 if (!FS.isDir(node.mode)) {
2537 return ERRNO_CODES.ENOTDIR;
2539 if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2540 return ERRNO_CODES.EBUSY;
2543 if (FS.isDir(node.mode)) {
2544 return ERRNO_CODES.EISDIR;
2548 },mayOpen:function (node, flags) {
2550 return ERRNO_CODES.ENOENT;
2552 if (FS.isLink(node.mode)) {
2553 return ERRNO_CODES.ELOOP;
2554 } else if (FS.isDir(node.mode)) {
2555 if ((flags & 2097155) !== 0 || // opening for write
2557 return ERRNO_CODES.EISDIR;
2560 return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
2561 },MAX_OPEN_FDS:4096,nextfd:function (fd_start, fd_end) {
2562 fd_start = fd_start || 0;
2563 fd_end = fd_end || FS.MAX_OPEN_FDS;
2564 for (var fd = fd_start; fd <= fd_end; fd++) {
2565 if (!FS.streams[fd]) {
2569 throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
2570 },getStream:function (fd) {
2571 return FS.streams[fd];
2572 },createStream:function (stream, fd_start, fd_end) {
2574 FS.FSStream = function(){};
2575 FS.FSStream.prototype = {};
2577 Object.defineProperties(FS.FSStream.prototype, {
2579 get: function() { return this.node; },
2580 set: function(val) { this.node = val; }
2583 get: function() { return (this.flags & 2097155) !== 1; }
2586 get: function() { return (this.flags & 2097155) !== 0; }
2589 get: function() { return (this.flags & 1024); }
2595 stream.__proto__ = FS.FSStream.prototype;
2597 var newStream = new FS.FSStream();
2598 for (var p in stream) {
2599 newStream[p] = stream[p];
2603 var fd = FS.nextfd(fd_start, fd_end);
2605 FS.streams[fd] = stream;
2607 },closeStream:function (fd) {
2608 FS.streams[fd] = null;
2609 },getStreamFromPtr:function (ptr) {
2610 return FS.streams[ptr - 1];
2611 },getPtrForStream:function (stream) {
2612 return stream ? stream.fd + 1 : 0;
2613 },chrdev_stream_ops:{open:function (stream) {
2614 var device = FS.getDevice(stream.node.rdev);
2615 // override node's stream ops with the device's
2616 stream.stream_ops = device.stream_ops;
2617 // forward the open call
2618 if (stream.stream_ops.open) {
2619 stream.stream_ops.open(stream);
2621 },llseek:function () {
2622 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
2623 }},major:function (dev) {
2624 return ((dev) >> 8);
2625 },minor:function (dev) {
2626 return ((dev) & 0xff);
2627 },makedev:function (ma, mi) {
2628 return ((ma) << 8 | (mi));
2629 },registerDevice:function (dev, ops) {
2630 FS.devices[dev] = { stream_ops: ops };
2631 },getDevice:function (dev) {
2632 return FS.devices[dev];
2633 },getMounts:function (mount) {
2635 var check = [mount];
2637 while (check.length) {
2638 var m = check.pop();
2642 check.push.apply(check, m.mounts);
2646 },syncfs:function (populate, callback) {
2647 if (typeof(populate) === 'function') {
2648 callback = populate;
2652 var mounts = FS.getMounts(FS.root.mount);
2655 function done(err) {
2657 if (!done.errored) {
2658 done.errored = true;
2659 return callback(err);
2663 if (++completed >= mounts.length) {
2669 mounts.forEach(function (mount) {
2670 if (!mount.type.syncfs) {
2673 mount.type.syncfs(mount, populate, done);
2675 },mount:function (type, opts, mountpoint) {
2676 var root = mountpoint === '/';
2677 var pseudo = !mountpoint;
2680 if (root && FS.root) {
2681 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2682 } else if (!root && !pseudo) {
2683 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2685 mountpoint = lookup.path; // use the absolute path
2688 if (FS.isMountpoint(node)) {
2689 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2692 if (!FS.isDir(node.mode)) {
2693 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2700 mountpoint: mountpoint,
2704 // create a root node for the fs
2705 var mountRoot = type.mount(mount);
2706 mountRoot.mount = mount;
2707 mount.root = mountRoot;
2710 FS.root = mountRoot;
2712 // set as a mountpoint
2713 node.mounted = mount;
2715 // add the new mount to the current mount's children
2717 node.mount.mounts.push(mount);
2722 },unmount:function (mountpoint) {
2723 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2725 if (!FS.isMountpoint(lookup.node)) {
2726 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2729 // destroy the nodes for this mount, and all its child mounts
2730 var node = lookup.node;
2731 var mount = node.mounted;
2732 var mounts = FS.getMounts(mount);
2734 Object.keys(FS.nameTable).forEach(function (hash) {
2735 var current = FS.nameTable[hash];
2738 var next = current.name_next;
2740 if (mounts.indexOf(current.mount) !== -1) {
2741 FS.destroyNode(current);
2748 // no longer a mountpoint
2749 node.mounted = null;
2751 // remove this mount from the child mounts
2752 var idx = node.mount.mounts.indexOf(mount);
2754 node.mount.mounts.splice(idx, 1);
2755 },lookup:function (parent, name) {
2756 return parent.node_ops.lookup(parent, name);
2757 },mknod:function (path, mode, dev) {
2758 var lookup = FS.lookupPath(path, { parent: true });
2759 var parent = lookup.node;
2760 var name = PATH.basename(path);
2761 var err = FS.mayCreate(parent, name);
2763 throw new FS.ErrnoError(err);
2765 if (!parent.node_ops.mknod) {
2766 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2768 return parent.node_ops.mknod(parent, name, mode, dev);
2769 },create:function (path, mode) {
2770 mode = mode !== undefined ? mode : 438 /* 0666 */;
2773 return FS.mknod(path, mode, 0);
2774 },mkdir:function (path, mode) {
2775 mode = mode !== undefined ? mode : 511 /* 0777 */;
2778 return FS.mknod(path, mode, 0);
2779 },mkdev:function (path, mode, dev) {
2780 if (typeof(dev) === 'undefined') {
2782 mode = 438 /* 0666 */;
2785 return FS.mknod(path, mode, dev);
2786 },symlink:function (oldpath, newpath) {
2787 var lookup = FS.lookupPath(newpath, { parent: true });
2788 var parent = lookup.node;
2789 var newname = PATH.basename(newpath);
2790 var err = FS.mayCreate(parent, newname);
2792 throw new FS.ErrnoError(err);
2794 if (!parent.node_ops.symlink) {
2795 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2797 return parent.node_ops.symlink(parent, newname, oldpath);
2798 },rename:function (old_path, new_path) {
2799 var old_dirname = PATH.dirname(old_path);
2800 var new_dirname = PATH.dirname(new_path);
2801 var old_name = PATH.basename(old_path);
2802 var new_name = PATH.basename(new_path);
2803 // parents must exist
2804 var lookup, old_dir, new_dir;
2806 lookup = FS.lookupPath(old_path, { parent: true });
2807 old_dir = lookup.node;
2808 lookup = FS.lookupPath(new_path, { parent: true });
2809 new_dir = lookup.node;
2811 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2813 // need to be part of the same mount
2814 if (old_dir.mount !== new_dir.mount) {
2815 throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
2817 // source must exist
2818 var old_node = FS.lookupNode(old_dir, old_name);
2819 // old path should not be an ancestor of the new path
2820 var relative = PATH.relative(old_path, new_dirname);
2821 if (relative.charAt(0) !== '.') {
2822 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2824 // new path should not be an ancestor of the old path
2825 relative = PATH.relative(new_path, old_dirname);
2826 if (relative.charAt(0) !== '.') {
2827 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
2829 // see if the new path already exists
2832 new_node = FS.lookupNode(new_dir, new_name);
2836 // early out if nothing needs to change
2837 if (old_node === new_node) {
2840 // we'll need to delete the old entry
2841 var isdir = FS.isDir(old_node.mode);
2842 var err = FS.mayDelete(old_dir, old_name, isdir);
2844 throw new FS.ErrnoError(err);
2846 // need delete permissions if we'll be overwriting.
2847 // need create permissions if new doesn't already exist.
2849 FS.mayDelete(new_dir, new_name, isdir) :
2850 FS.mayCreate(new_dir, new_name);
2852 throw new FS.ErrnoError(err);
2854 if (!old_dir.node_ops.rename) {
2855 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2857 if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
2858 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2860 // if we are going to change the parent, check write permissions
2861 if (new_dir !== old_dir) {
2862 err = FS.nodePermissions(old_dir, 'w');
2864 throw new FS.ErrnoError(err);
2867 // remove the node from the lookup hash
2868 FS.hashRemoveNode(old_node);
2869 // do the underlying fs rename
2871 old_dir.node_ops.rename(old_node, new_dir, new_name);
2875 // add the node back to the hash (in case node_ops.rename
2876 // changed its name)
2877 FS.hashAddNode(old_node);
2879 },rmdir:function (path) {
2880 var lookup = FS.lookupPath(path, { parent: true });
2881 var parent = lookup.node;
2882 var name = PATH.basename(path);
2883 var node = FS.lookupNode(parent, name);
2884 var err = FS.mayDelete(parent, name, true);
2886 throw new FS.ErrnoError(err);
2888 if (!parent.node_ops.rmdir) {
2889 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2891 if (FS.isMountpoint(node)) {
2892 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2894 parent.node_ops.rmdir(parent, name);
2895 FS.destroyNode(node);
2896 },readdir:function (path) {
2897 var lookup = FS.lookupPath(path, { follow: true });
2898 var node = lookup.node;
2899 if (!node.node_ops.readdir) {
2900 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2902 return node.node_ops.readdir(node);
2903 },unlink:function (path) {
2904 var lookup = FS.lookupPath(path, { parent: true });
2905 var parent = lookup.node;
2906 var name = PATH.basename(path);
2907 var node = FS.lookupNode(parent, name);
2908 var err = FS.mayDelete(parent, name, false);
2910 // POSIX says unlink should set EPERM, not EISDIR
2911 if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
2912 throw new FS.ErrnoError(err);
2914 if (!parent.node_ops.unlink) {
2915 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2917 if (FS.isMountpoint(node)) {
2918 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2920 parent.node_ops.unlink(parent, name);
2921 FS.destroyNode(node);
2922 },readlink:function (path) {
2923 var lookup = FS.lookupPath(path);
2924 var link = lookup.node;
2925 if (!link.node_ops.readlink) {
2926 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2928 return link.node_ops.readlink(link);
2929 },stat:function (path, dontFollow) {
2930 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2931 var node = lookup.node;
2932 if (!node.node_ops.getattr) {
2933 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2935 return node.node_ops.getattr(node);
2936 },lstat:function (path) {
2937 return FS.stat(path, true);
2938 },chmod:function (path, mode, dontFollow) {
2940 if (typeof path === 'string') {
2941 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2946 if (!node.node_ops.setattr) {
2947 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2949 node.node_ops.setattr(node, {
2950 mode: (mode & 4095) | (node.mode & ~4095),
2951 timestamp: Date.now()
2953 },lchmod:function (path, mode) {
2954 FS.chmod(path, mode, true);
2955 },fchmod:function (fd, mode) {
2956 var stream = FS.getStream(fd);
2958 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2960 FS.chmod(stream.node, mode);
2961 },chown:function (path, uid, gid, dontFollow) {
2963 if (typeof path === 'string') {
2964 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2969 if (!node.node_ops.setattr) {
2970 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2972 node.node_ops.setattr(node, {
2973 timestamp: Date.now()
2974 // we ignore the uid / gid for now
2976 },lchown:function (path, uid, gid) {
2977 FS.chown(path, uid, gid, true);
2978 },fchown:function (fd, uid, gid) {
2979 var stream = FS.getStream(fd);
2981 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2983 FS.chown(stream.node, uid, gid);
2984 },truncate:function (path, len) {
2986 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2989 if (typeof path === 'string') {
2990 var lookup = FS.lookupPath(path, { follow: true });
2995 if (!node.node_ops.setattr) {
2996 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2998 if (FS.isDir(node.mode)) {
2999 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3001 if (!FS.isFile(node.mode)) {
3002 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3004 var err = FS.nodePermissions(node, 'w');
3006 throw new FS.ErrnoError(err);
3008 node.node_ops.setattr(node, {
3010 timestamp: Date.now()
3012 },ftruncate:function (fd, len) {
3013 var stream = FS.getStream(fd);
3015 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3017 if ((stream.flags & 2097155) === 0) {
3018 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3020 FS.truncate(stream.node, len);
3021 },utime:function (path, atime, mtime) {
3022 var lookup = FS.lookupPath(path, { follow: true });
3023 var node = lookup.node;
3024 node.node_ops.setattr(node, {
3025 timestamp: Math.max(atime, mtime)
3027 },open:function (path, flags, mode, fd_start, fd_end) {
3028 flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3029 mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3031 mode = (mode & 4095) | 32768;
3036 if (typeof path === 'object') {
3039 path = PATH.normalize(path);
3041 var lookup = FS.lookupPath(path, {
3042 follow: !(flags & 131072)
3049 // perhaps we need to create the node
3052 // if O_CREAT and O_EXCL are set, error out if the node already exists
3053 if ((flags & 128)) {
3054 throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
3057 // node doesn't exist, try to create it
3058 node = FS.mknod(path, mode, 0);
3062 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3064 // can't truncate a device
3065 if (FS.isChrdev(node.mode)) {
3068 // check permissions
3069 var err = FS.mayOpen(node, flags);
3071 throw new FS.ErrnoError(err);
3073 // do truncation if necessary
3074 if ((flags & 512)) {
3075 FS.truncate(node, 0);
3077 // we've already handled these, don't pass down to the underlying vfs
3078 flags &= ~(128 | 512);
3080 // register the stream with the filesystem
3081 var stream = FS.createStream({
3083 path: FS.getPath(node), // we want the absolute path to the node
3087 stream_ops: node.stream_ops,
3088 // used by the file family libc calls (fopen, fwrite, ferror, etc.)
3091 }, fd_start, fd_end);
3092 // call the new stream's open function
3093 if (stream.stream_ops.open) {
3094 stream.stream_ops.open(stream);
3096 if (Module['logReadFiles'] && !(flags & 1)) {
3097 if (!FS.readFiles) FS.readFiles = {};
3098 if (!(path in FS.readFiles)) {
3099 FS.readFiles[path] = 1;
3100 Module['printErr']('read file: ' + path);
3104 },close:function (stream) {
3106 if (stream.stream_ops.close) {
3107 stream.stream_ops.close(stream);
3112 FS.closeStream(stream.fd);
3114 },llseek:function (stream, offset, whence) {
3115 if (!stream.seekable || !stream.stream_ops.llseek) {
3116 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3118 return stream.stream_ops.llseek(stream, offset, whence);
3119 },read:function (stream, buffer, offset, length, position) {
3120 if (length < 0 || position < 0) {
3121 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3123 if ((stream.flags & 2097155) === 1) {
3124 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3126 if (FS.isDir(stream.node.mode)) {
3127 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3129 if (!stream.stream_ops.read) {
3130 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3133 if (typeof position === 'undefined') {
3134 position = stream.position;
3136 } else if (!stream.seekable) {
3137 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3139 var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
3140 if (!seeking) stream.position += bytesRead;
3142 },write:function (stream, buffer, offset, length, position, canOwn) {
3143 if (length < 0 || position < 0) {
3144 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3146 if ((stream.flags & 2097155) === 0) {
3147 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3149 if (FS.isDir(stream.node.mode)) {
3150 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3152 if (!stream.stream_ops.write) {
3153 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3156 if (typeof position === 'undefined') {
3157 position = stream.position;
3159 } else if (!stream.seekable) {
3160 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3162 if (stream.flags & 1024) {
3163 // seek to the end before writing in append mode
3164 FS.llseek(stream, 0, 2);
3166 var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
3167 if (!seeking) stream.position += bytesWritten;
3168 return bytesWritten;
3169 },allocate:function (stream, offset, length) {
3170 if (offset < 0 || length <= 0) {
3171 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3173 if ((stream.flags & 2097155) === 0) {
3174 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3176 if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
3177 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3179 if (!stream.stream_ops.allocate) {
3180 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
3182 stream.stream_ops.allocate(stream, offset, length);
3183 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
3184 // TODO if PROT is PROT_WRITE, make sure we have write access
3185 if ((stream.flags & 2097155) === 1) {
3186 throw new FS.ErrnoError(ERRNO_CODES.EACCES);
3188 if (!stream.stream_ops.mmap) {
3189 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3191 return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
3192 },ioctl:function (stream, cmd, arg) {
3193 if (!stream.stream_ops.ioctl) {
3194 throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
3196 return stream.stream_ops.ioctl(stream, cmd, arg);
3197 },readFile:function (path, opts) {
3199 opts.flags = opts.flags || 'r';
3200 opts.encoding = opts.encoding || 'binary';
3201 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3202 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3205 var stream = FS.open(path, opts.flags);
3206 var stat = FS.stat(path);
3207 var length = stat.size;
3208 var buf = new Uint8Array(length);
3209 FS.read(stream, buf, 0, length, 0);
3210 if (opts.encoding === 'utf8') {
3212 var utf8 = new Runtime.UTF8Processor();
3213 for (var i = 0; i < length; i++) {
3214 ret += utf8.processCChar(buf[i]);
3216 } else if (opts.encoding === 'binary') {
3221 },writeFile:function (path, data, opts) {
3223 opts.flags = opts.flags || 'w';
3224 opts.encoding = opts.encoding || 'utf8';
3225 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3226 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3228 var stream = FS.open(path, opts.flags, opts.mode);
3229 if (opts.encoding === 'utf8') {
3230 var utf8 = new Runtime.UTF8Processor();
3231 var buf = new Uint8Array(utf8.processJSString(data));
3232 FS.write(stream, buf, 0, buf.length, 0, opts.canOwn);
3233 } else if (opts.encoding === 'binary') {
3234 FS.write(stream, data, 0, data.length, 0, opts.canOwn);
3238 return FS.currentPath;
3239 },chdir:function (path) {
3240 var lookup = FS.lookupPath(path, { follow: true });
3241 if (!FS.isDir(lookup.node.mode)) {
3242 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3244 var err = FS.nodePermissions(lookup.node, 'x');
3246 throw new FS.ErrnoError(err);
3248 FS.currentPath = lookup.path;
3249 },createDefaultDirectories:function () {
3251 },createDefaultDevices:function () {
3255 FS.registerDevice(FS.makedev(1, 3), {
3256 read: function() { return 0; },
3257 write: function() { return 0; }
3259 FS.mkdev('/dev/null', FS.makedev(1, 3));
3260 // setup /dev/tty and /dev/tty1
3261 // stderr needs to print output using Module['printErr']
3262 // so we register a second tty just for it.
3263 TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
3264 TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
3265 FS.mkdev('/dev/tty', FS.makedev(5, 0));
3266 FS.mkdev('/dev/tty1', FS.makedev(6, 0));
3267 // we're not going to emulate the actual shm device,
3268 // just create the tmp dirs that reside in it commonly
3269 FS.mkdir('/dev/shm');
3270 FS.mkdir('/dev/shm/tmp');
3271 },createStandardStreams:function () {
3272 // TODO deprecate the old functionality of a single
3273 // input / output callback and that utilizes FS.createDevice
3274 // and instead require a unique set of stream ops
3276 // by default, we symlink the standard streams to the
3277 // default tty devices. however, if the standard streams
3278 // have been overwritten we create a unique device for
3280 if (Module['stdin']) {
3281 FS.createDevice('/dev', 'stdin', Module['stdin']);
3283 FS.symlink('/dev/tty', '/dev/stdin');
3285 if (Module['stdout']) {
3286 FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3288 FS.symlink('/dev/tty', '/dev/stdout');
3290 if (Module['stderr']) {
3291 FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3293 FS.symlink('/dev/tty1', '/dev/stderr');
3296 // open default streams for the stdin, stdout and stderr devices
3297 var stdin = FS.open('/dev/stdin', 'r');
3298 HEAP32[((_stdin)>>2)]=FS.getPtrForStream(stdin);
3299 assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
3301 var stdout = FS.open('/dev/stdout', 'w');
3302 HEAP32[((_stdout)>>2)]=FS.getPtrForStream(stdout);
3303 assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
3305 var stderr = FS.open('/dev/stderr', 'w');
3306 HEAP32[((_stderr)>>2)]=FS.getPtrForStream(stderr);
3307 assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
3308 },ensureErrnoError:function () {
3309 if (FS.ErrnoError) return;
3310 FS.ErrnoError = function ErrnoError(errno) {
3312 for (var key in ERRNO_CODES) {
3313 if (ERRNO_CODES[key] === errno) {
3318 this.message = ERRNO_MESSAGES[errno];
3320 FS.ErrnoError.prototype = new Error();
3321 FS.ErrnoError.prototype.constructor = FS.ErrnoError;
3322 // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
3323 [ERRNO_CODES.ENOENT].forEach(function(code) {
3324 FS.genericErrors[code] = new FS.ErrnoError(code);
3325 FS.genericErrors[code].stack = '<generic error, no stack>';
3327 },staticInit:function () {
3328 FS.ensureErrnoError();
3330 FS.nameTable = new Array(4096);
3332 FS.mount(MEMFS, {}, '/');
3334 FS.createDefaultDirectories();
3335 FS.createDefaultDevices();
3336 },init:function (input, output, error) {
3337 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)');
3338 FS.init.initialized = true;
3340 FS.ensureErrnoError();
3342 // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
3343 Module['stdin'] = input || Module['stdin'];
3344 Module['stdout'] = output || Module['stdout'];
3345 Module['stderr'] = error || Module['stderr'];
3347 FS.createStandardStreams();
3348 },quit:function () {
3349 FS.init.initialized = false;
3350 for (var i = 0; i < FS.streams.length; i++) {
3351 var stream = FS.streams[i];
3357 },getMode:function (canRead, canWrite) {
3359 if (canRead) mode |= 292 | 73;
3360 if (canWrite) mode |= 146;
3362 },joinPath:function (parts, forceRelative) {
3363 var path = PATH.join.apply(null, parts);
3364 if (forceRelative && path[0] == '/') path = path.substr(1);
3366 },absolutePath:function (relative, base) {
3367 return PATH.resolve(base, relative);
3368 },standardizePath:function (path) {
3369 return PATH.normalize(path);
3370 },findObject:function (path, dontResolveLastLink) {
3371 var ret = FS.analyzePath(path, dontResolveLastLink);
3375 ___setErrNo(ret.error);
3378 },analyzePath:function (path, dontResolveLastLink) {
3379 // operate from within the context of the symlink's target
3381 var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3386 isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
3387 parentExists: false, parentPath: null, parentObject: null
3390 var lookup = FS.lookupPath(path, { parent: true });
3391 ret.parentExists = true;
3392 ret.parentPath = lookup.path;
3393 ret.parentObject = lookup.node;
3394 ret.name = PATH.basename(path);
3395 lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3397 ret.path = lookup.path;
3398 ret.object = lookup.node;
3399 ret.name = lookup.node.name;
3400 ret.isRoot = lookup.path === '/';
3402 ret.error = e.errno;
3405 },createFolder:function (parent, name, canRead, canWrite) {
3406 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3407 var mode = FS.getMode(canRead, canWrite);
3408 return FS.mkdir(path, mode);
3409 },createPath:function (parent, path, canRead, canWrite) {
3410 parent = typeof parent === 'string' ? parent : FS.getPath(parent);
3411 var parts = path.split('/').reverse();
3412 while (parts.length) {
3413 var part = parts.pop();
3414 if (!part) continue;
3415 var current = PATH.join2(parent, part);
3424 },createFile:function (parent, name, properties, canRead, canWrite) {
3425 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3426 var mode = FS.getMode(canRead, canWrite);
3427 return FS.create(path, mode);
3428 },createDataFile:function (parent, name, data, canRead, canWrite, canOwn) {
3429 var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
3430 var mode = FS.getMode(canRead, canWrite);
3431 var node = FS.create(path, mode);
3433 if (typeof data === 'string') {
3434 var arr = new Array(data.length);
3435 for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
3438 // make sure we can write to the file
3439 FS.chmod(node, mode | 146);
3440 var stream = FS.open(node, 'w');
3441 FS.write(stream, data, 0, data.length, 0, canOwn);
3443 FS.chmod(node, mode);
3446 },createDevice:function (parent, name, input, output) {
3447 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3448 var mode = FS.getMode(!!input, !!output);
3449 if (!FS.createDevice.major) FS.createDevice.major = 64;
3450 var dev = FS.makedev(FS.createDevice.major++, 0);
3451 // Create a fake device that a set of stream ops to emulate
3452 // the old behavior.
3453 FS.registerDevice(dev, {
3454 open: function(stream) {
3455 stream.seekable = false;
3457 close: function(stream) {
3458 // flush any pending line data
3459 if (output && output.buffer && output.buffer.length) {
3463 read: function(stream, buffer, offset, length, pos /* ignored */) {
3465 for (var i = 0; i < length; i++) {
3470 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3472 if (result === undefined && bytesRead === 0) {
3473 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
3475 if (result === null || result === undefined) break;
3477 buffer[offset+i] = result;
3480 stream.node.timestamp = Date.now();
3484 write: function(stream, buffer, offset, length, pos) {
3485 for (var i = 0; i < length; i++) {
3487 output(buffer[offset+i]);
3489 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3493 stream.node.timestamp = Date.now();
3498 return FS.mkdev(path, mode, dev);
3499 },createLink:function (parent, name, target, canRead, canWrite) {
3500 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3501 return FS.symlink(target, path);
3502 },forceLoadFile:function (obj) {
3503 if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
3505 if (typeof XMLHttpRequest !== 'undefined') {
3506 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.");
3507 } else if (Module['read']) {
3510 // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
3511 // read() will try to parse UTF8.
3512 obj.contents = intArrayFromString(Module['read'](obj.url), true);
3517 throw new Error('Cannot load without read() or XMLHttpRequest.');
3519 if (!success) ___setErrNo(ERRNO_CODES.EIO);
3521 },createLazyFile:function (parent, name, url, canRead, canWrite) {
3522 // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
3523 function LazyUint8Array() {
3524 this.lengthKnown = false;
3525 this.chunks = []; // Loaded chunks. Index is the chunk number
3527 LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
3528 if (idx > this.length-1 || idx < 0) {
3531 var chunkOffset = idx % this.chunkSize;
3532 var chunkNum = Math.floor(idx / this.chunkSize);
3533 return this.getter(chunkNum)[chunkOffset];
3535 LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
3536 this.getter = getter;
3538 LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
3540 var xhr = new XMLHttpRequest();
3541 xhr.open('HEAD', url, false);
3543 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3544 var datalength = Number(xhr.getResponseHeader("Content-length"));
3546 var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
3547 var chunkSize = 1024*1024; // Chunk size in bytes
3549 if (!hasByteServing) chunkSize = datalength;
3551 // Function to get a range from the remote URL.
3552 var doXHR = (function(from, to) {
3553 if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
3554 if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
3556 // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
3557 var xhr = new XMLHttpRequest();
3558 xhr.open('GET', url, false);
3559 if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
3561 // Some hints to the browser that we want binary data.
3562 if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
3563 if (xhr.overrideMimeType) {
3564 xhr.overrideMimeType('text/plain; charset=x-user-defined');
3568 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3569 if (xhr.response !== undefined) {
3570 return new Uint8Array(xhr.response || []);
3572 return intArrayFromString(xhr.responseText || '', true);
3575 var lazyArray = this;
3576 lazyArray.setDataGetter(function(chunkNum) {
3577 var start = chunkNum * chunkSize;
3578 var end = (chunkNum+1) * chunkSize - 1; // including this byte
3579 end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
3580 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
3581 lazyArray.chunks[chunkNum] = doXHR(start, end);
3583 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3584 return lazyArray.chunks[chunkNum];
3587 this._length = datalength;
3588 this._chunkSize = chunkSize;
3589 this.lengthKnown = true;
3591 if (typeof XMLHttpRequest !== 'undefined') {
3592 if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
3593 var lazyArray = new LazyUint8Array();
3594 Object.defineProperty(lazyArray, "length", {
3596 if(!this.lengthKnown) {
3599 return this._length;
3602 Object.defineProperty(lazyArray, "chunkSize", {
3604 if(!this.lengthKnown) {
3607 return this._chunkSize;
3611 var properties = { isDevice: false, contents: lazyArray };
3613 var properties = { isDevice: false, url: url };
3616 var node = FS.createFile(parent, name, properties, canRead, canWrite);
3617 // This is a total hack, but I want to get this lazy file code out of the
3618 // core of MEMFS. If we want to keep this lazy file concept I feel it should
3619 // be its own thin LAZYFS proxying calls to MEMFS.
3620 if (properties.contents) {
3621 node.contents = properties.contents;
3622 } else if (properties.url) {
3623 node.contents = null;
3624 node.url = properties.url;
3626 // override each stream op with one that tries to force load the lazy file first
3627 var stream_ops = {};
3628 var keys = Object.keys(node.stream_ops);
3629 keys.forEach(function(key) {
3630 var fn = node.stream_ops[key];
3631 stream_ops[key] = function forceLoadLazyFile() {
3632 if (!FS.forceLoadFile(node)) {
3633 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3635 return fn.apply(null, arguments);
3638 // use a custom read function
3639 stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
3640 if (!FS.forceLoadFile(node)) {
3641 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3643 var contents = stream.node.contents;
3644 if (position >= contents.length)
3646 var size = Math.min(contents.length - position, length);
3648 if (contents.slice) { // normal array
3649 for (var i = 0; i < size; i++) {
3650 buffer[offset + i] = contents[position + i];
3653 for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
3654 buffer[offset + i] = contents.get(position + i);
3659 node.stream_ops = stream_ops;
3661 },createPreloadedFile:function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn) {
3663 // TODO we should allow people to just pass in a complete filename instead
3664 // of parent and name being that we just join them anyways
3665 var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
3666 function processData(byteArray) {
3667 function finish(byteArray) {
3668 if (!dontCreateFile) {
3669 FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
3671 if (onload) onload();
3672 removeRunDependency('cp ' + fullname);
3674 var handled = false;
3675 Module['preloadPlugins'].forEach(function(plugin) {
3676 if (handled) return;
3677 if (plugin['canHandle'](fullname)) {
3678 plugin['handle'](byteArray, fullname, finish, function() {
3679 if (onerror) onerror();
3680 removeRunDependency('cp ' + fullname);
3685 if (!handled) finish(byteArray);
3687 addRunDependency('cp ' + fullname);
3688 if (typeof url == 'string') {
3689 Browser.asyncLoad(url, function(byteArray) {
3690 processData(byteArray);
3695 },indexedDB:function () {
3696 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
3697 },DB_NAME:function () {
3698 return 'EM_FS_' + window.location.pathname;
3699 },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function (paths, onload, onerror) {
3700 onload = onload || function(){};
3701 onerror = onerror || function(){};
3702 var indexedDB = FS.indexedDB();
3704 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3708 openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
3709 console.log('creating db');
3710 var db = openRequest.result;
3711 db.createObjectStore(FS.DB_STORE_NAME);
3713 openRequest.onsuccess = function openRequest_onsuccess() {
3714 var db = openRequest.result;
3715 var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
3716 var files = transaction.objectStore(FS.DB_STORE_NAME);
3717 var ok = 0, fail = 0, total = paths.length;
3719 if (fail == 0) onload(); else onerror();
3721 paths.forEach(function(path) {
3722 var putRequest = files.put(FS.analyzePath(path).object.contents, path);
3723 putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
3724 putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
3726 transaction.onerror = onerror;
3728 openRequest.onerror = onerror;
3729 },loadFilesFromDB:function (paths, onload, onerror) {
3730 onload = onload || function(){};
3731 onerror = onerror || function(){};
3732 var indexedDB = FS.indexedDB();
3734 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3738 openRequest.onupgradeneeded = onerror; // no database to load from
3739 openRequest.onsuccess = function openRequest_onsuccess() {
3740 var db = openRequest.result;
3742 var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
3747 var files = transaction.objectStore(FS.DB_STORE_NAME);
3748 var ok = 0, fail = 0, total = paths.length;
3750 if (fail == 0) onload(); else onerror();
3752 paths.forEach(function(path) {
3753 var getRequest = files.get(path);
3754 getRequest.onsuccess = function getRequest_onsuccess() {
3755 if (FS.analyzePath(path).exists) {
3758 FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
3760 if (ok + fail == total) finish();
3762 getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
3764 transaction.onerror = onerror;
3766 openRequest.onerror = onerror;
3767 }};var PATH={splitPath:function (filename) {
3768 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3769 return splitPathRe.exec(filename).slice(1);
3770 },normalizeArray:function (parts, allowAboveRoot) {
3771 // if the path tries to go above the root, `up` ends up > 0
3773 for (var i = parts.length - 1; i >= 0; i--) {
3774 var last = parts[i];
3777 } else if (last === '..') {
3785 // if the path is allowed to go above the root, restore leading ..s
3786 if (allowAboveRoot) {
3788 parts.unshift('..');
3792 },normalize:function (path) {
3793 var isAbsolute = path.charAt(0) === '/',
3794 trailingSlash = path.substr(-1) === '/';
3795 // Normalize the path
3796 path = PATH.normalizeArray(path.split('/').filter(function(p) {
3798 }), !isAbsolute).join('/');
3799 if (!path && !isAbsolute) {
3802 if (path && trailingSlash) {
3805 return (isAbsolute ? '/' : '') + path;
3806 },dirname:function (path) {
3807 var result = PATH.splitPath(path),
3810 if (!root && !dir) {
3811 // No dirname whatsoever
3815 // It has a dirname, strip trailing slash
3816 dir = dir.substr(0, dir.length - 1);
3819 },basename:function (path) {
3820 // EMSCRIPTEN return '/'' for '/', not an empty string
3821 if (path === '/') return '/';
3822 var lastSlash = path.lastIndexOf('/');
3823 if (lastSlash === -1) return path;
3824 return path.substr(lastSlash+1);
3825 },extname:function (path) {
3826 return PATH.splitPath(path)[3];
3827 },join:function () {
3828 var paths = Array.prototype.slice.call(arguments, 0);
3829 return PATH.normalize(paths.join('/'));
3830 },join2:function (l, r) {
3831 return PATH.normalize(l + '/' + r);
3832 },resolve:function () {
3833 var resolvedPath = '',
3834 resolvedAbsolute = false;
3835 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3836 var path = (i >= 0) ? arguments[i] : FS.cwd();
3837 // Skip empty and invalid entries
3838 if (typeof path !== 'string') {
3839 throw new TypeError('Arguments to path.resolve must be strings');
3843 resolvedPath = path + '/' + resolvedPath;
3844 resolvedAbsolute = path.charAt(0) === '/';
3846 // At this point the path should be resolved to a full absolute path, but
3847 // handle relative paths to be safe (might happen when process.cwd() fails)
3848 resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
3850 }), !resolvedAbsolute).join('/');
3851 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3852 },relative:function (from, to) {
3853 from = PATH.resolve(from).substr(1);
3854 to = PATH.resolve(to).substr(1);
3855 function trim(arr) {
3857 for (; start < arr.length; start++) {
3858 if (arr[start] !== '') break;
3860 var end = arr.length - 1;
3861 for (; end >= 0; end--) {
3862 if (arr[end] !== '') break;
3864 if (start > end) return [];
3865 return arr.slice(start, end - start + 1);
3867 var fromParts = trim(from.split('/'));
3868 var toParts = trim(to.split('/'));
3869 var length = Math.min(fromParts.length, toParts.length);
3870 var samePartsLength = length;
3871 for (var i = 0; i < length; i++) {
3872 if (fromParts[i] !== toParts[i]) {
3873 samePartsLength = i;
3877 var outputParts = [];
3878 for (var i = samePartsLength; i < fromParts.length; i++) {
3879 outputParts.push('..');
3881 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3882 return outputParts.join('/');
3883 }};var Browser={mainLoop:{scheduler:null,method:"",shouldPause:false,paused:false,queue:[],pause:function () {
3884 Browser.mainLoop.shouldPause = true;
3885 },resume:function () {
3886 if (Browser.mainLoop.paused) {
3887 Browser.mainLoop.paused = false;
3888 Browser.mainLoop.scheduler();
3890 Browser.mainLoop.shouldPause = false;
3891 },updateStatus:function () {
3892 if (Module['setStatus']) {
3893 var message = Module['statusMessage'] || 'Please wait...';
3894 var remaining = Browser.mainLoop.remainingBlockers;
3895 var expected = Browser.mainLoop.expectedBlockers;
3897 if (remaining < expected) {
3898 Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
3900 Module['setStatus'](message);
3903 Module['setStatus']('');
3906 }},isFullScreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function () {
3907 if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
3909 if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
3910 Browser.initted = true;
3914 Browser.hasBlobConstructor = true;
3916 Browser.hasBlobConstructor = false;
3917 console.log("warning: no blob constructor, cannot create blobs with mimetypes");
3919 Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
3920 Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
3921 if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
3922 console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
3923 Module.noImageDecoding = true;
3926 // Support for plugins that can process preloaded files. You can add more of these to
3927 // your app by creating and appending to Module.preloadPlugins.
3929 // Each plugin is asked if it can handle a file based on the file's name. If it can,
3930 // it is given the file's raw data. When it is done, it calls a callback with the file's
3931 // (possibly modified) data. For example, a plugin might decompress a file, or it
3932 // might create some side data structure for use later (like an Image element, etc.).
3934 var imagePlugin = {};
3935 imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
3936 return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
3938 imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
3940 if (Browser.hasBlobConstructor) {
3942 b = new Blob([byteArray], { type: Browser.getMimetype(name) });
3943 if (b.size !== byteArray.length) { // Safari bug #118630
3944 // Safari's Blob can only take an ArrayBuffer
3945 b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
3948 Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
3952 var bb = new Browser.BlobBuilder();
3953 bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
3956 var url = Browser.URLObject.createObjectURL(b);
3957 var img = new Image();
3958 img.onload = function img_onload() {
3959 assert(img.complete, 'Image ' + name + ' could not be decoded');
3960 var canvas = document.createElement('canvas');
3961 canvas.width = img.width;
3962 canvas.height = img.height;
3963 var ctx = canvas.getContext('2d');
3964 ctx.drawImage(img, 0, 0);
3965 Module["preloadedImages"][name] = canvas;
3966 Browser.URLObject.revokeObjectURL(url);
3967 if (onload) onload(byteArray);
3969 img.onerror = function img_onerror(event) {
3970 console.log('Image ' + url + ' could not be decoded');
3971 if (onerror) onerror();
3975 Module['preloadPlugins'].push(imagePlugin);
3977 var audioPlugin = {};
3978 audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
3979 return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
3981 audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
3983 function finish(audio) {
3986 Module["preloadedAudios"][name] = audio;
3987 if (onload) onload(byteArray);
3992 Module["preloadedAudios"][name] = new Audio(); // empty shim
3993 if (onerror) onerror();
3995 if (Browser.hasBlobConstructor) {
3997 var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4001 var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
4002 var audio = new Audio();
4003 audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
4004 audio.onerror = function audio_onerror(event) {
4006 console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
4007 function encode64(data) {
4008 var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4013 for (var i = 0; i < data.length; i++) {
4014 leftchar = (leftchar << 8) | data[i];
4016 while (leftbits >= 6) {
4017 var curr = (leftchar >> (leftbits-6)) & 0x3f;
4022 if (leftbits == 2) {
4023 ret += BASE[(leftchar&3) << 4];
4025 } else if (leftbits == 4) {
4026 ret += BASE[(leftchar&0xf) << 2];
4031 audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
4032 finish(audio); // we don't wait for confirmation this worked - but it's worth trying
4035 // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
4036 Browser.safeSetTimeout(function() {
4037 finish(audio); // try to use it even though it is not necessarily ready to play
4043 Module['preloadPlugins'].push(audioPlugin);
4045 // Canvas event setup
4047 var canvas = Module['canvas'];
4049 // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
4050 // Module['forcedAspectRatio'] = 4 / 3;
4052 canvas.requestPointerLock = canvas['requestPointerLock'] ||
4053 canvas['mozRequestPointerLock'] ||
4054 canvas['webkitRequestPointerLock'] ||
4055 canvas['msRequestPointerLock'] ||
4057 canvas.exitPointerLock = document['exitPointerLock'] ||
4058 document['mozExitPointerLock'] ||
4059 document['webkitExitPointerLock'] ||
4060 document['msExitPointerLock'] ||
4061 function(){}; // no-op if function does not exist
4062 canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
4064 function pointerLockChange() {
4065 Browser.pointerLock = document['pointerLockElement'] === canvas ||
4066 document['mozPointerLockElement'] === canvas ||
4067 document['webkitPointerLockElement'] === canvas ||
4068 document['msPointerLockElement'] === canvas;
4071 document.addEventListener('pointerlockchange', pointerLockChange, false);
4072 document.addEventListener('mozpointerlockchange', pointerLockChange, false);
4073 document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
4074 document.addEventListener('mspointerlockchange', pointerLockChange, false);
4076 if (Module['elementPointerLock']) {
4077 canvas.addEventListener("click", function(ev) {
4078 if (!Browser.pointerLock && canvas.requestPointerLock) {
4079 canvas.requestPointerLock();
4080 ev.preventDefault();
4084 },createContext:function (canvas, useWebGL, setInModule, webGLContextAttributes) {
4086 var errorInfo = '?';
4087 function onContextCreationError(event) {
4088 errorInfo = event.statusMessage || errorInfo;
4092 var contextAttributes = {
4097 if (webGLContextAttributes) {
4098 for (var attribute in webGLContextAttributes) {
4099 contextAttributes[attribute] = webGLContextAttributes[attribute];
4104 canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
4106 ['experimental-webgl', 'webgl'].some(function(webglId) {
4107 return ctx = canvas.getContext(webglId, contextAttributes);
4110 canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
4113 ctx = canvas.getContext('2d');
4115 if (!ctx) throw ':(';
4117 Module.print('Could not create canvas: ' + [errorInfo, e]);
4121 // Set the background of the WebGL canvas to black
4122 canvas.style.backgroundColor = "black";
4124 // Warn on context loss
4125 canvas.addEventListener('webglcontextlost', function(event) {
4126 alert('WebGL context lost. You will need to reload the page.');
4130 GLctx = Module.ctx = ctx;
4131 Module.useWebGL = useWebGL;
4132 Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
4136 },destroyContext:function (canvas, useWebGL, setInModule) {},fullScreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullScreen:function (lockPointer, resizeCanvas) {
4137 Browser.lockPointer = lockPointer;
4138 Browser.resizeCanvas = resizeCanvas;
4139 if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
4140 if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
4142 var canvas = Module['canvas'];
4143 function fullScreenChange() {
4144 Browser.isFullScreen = false;
4145 var canvasContainer = canvas.parentNode;
4146 if ((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
4147 document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
4148 document['fullScreenElement'] || document['fullscreenElement'] ||
4149 document['msFullScreenElement'] || document['msFullscreenElement'] ||
4150 document['webkitCurrentFullScreenElement']) === canvasContainer) {
4151 canvas.cancelFullScreen = document['cancelFullScreen'] ||
4152 document['mozCancelFullScreen'] ||
4153 document['webkitCancelFullScreen'] ||
4154 document['msExitFullscreen'] ||
4155 document['exitFullscreen'] ||
4157 canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
4158 if (Browser.lockPointer) canvas.requestPointerLock();
4159 Browser.isFullScreen = true;
4160 if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
4163 // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
4164 canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
4165 canvasContainer.parentNode.removeChild(canvasContainer);
4167 if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
4169 if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScreen);
4170 Browser.updateCanvasDimensions(canvas);
4173 if (!Browser.fullScreenHandlersInstalled) {
4174 Browser.fullScreenHandlersInstalled = true;
4175 document.addEventListener('fullscreenchange', fullScreenChange, false);
4176 document.addEventListener('mozfullscreenchange', fullScreenChange, false);
4177 document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
4178 document.addEventListener('MSFullscreenChange', fullScreenChange, false);
4181 // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root
4182 var canvasContainer = document.createElement("div");
4183 canvas.parentNode.insertBefore(canvasContainer, canvas);
4184 canvasContainer.appendChild(canvas);
4186 // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
4187 canvasContainer.requestFullScreen = canvasContainer['requestFullScreen'] ||
4188 canvasContainer['mozRequestFullScreen'] ||
4189 canvasContainer['msRequestFullscreen'] ||
4190 (canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
4191 canvasContainer.requestFullScreen();
4192 },requestAnimationFrame:function requestAnimationFrame(func) {
4193 if (typeof window === 'undefined') { // Provide fallback to setTimeout if window is undefined (e.g. in Node.js)
4194 setTimeout(func, 1000/60);
4196 if (!window.requestAnimationFrame) {
4197 window.requestAnimationFrame = window['requestAnimationFrame'] ||
4198 window['mozRequestAnimationFrame'] ||
4199 window['webkitRequestAnimationFrame'] ||
4200 window['msRequestAnimationFrame'] ||
4201 window['oRequestAnimationFrame'] ||
4202 window['setTimeout'];
4204 window.requestAnimationFrame(func);
4206 },safeCallback:function (func) {
4208 if (!ABORT) return func.apply(null, arguments);
4210 },safeRequestAnimationFrame:function (func) {
4211 return Browser.requestAnimationFrame(function() {
4214 },safeSetTimeout:function (func, timeout) {
4215 return setTimeout(function() {
4218 },safeSetInterval:function (func, timeout) {
4219 return setInterval(function() {
4222 },getMimetype:function (name) {
4224 'jpg': 'image/jpeg',
4225 'jpeg': 'image/jpeg',
4231 }[name.substr(name.lastIndexOf('.')+1)];
4232 },getUserMedia:function (func) {
4233 if(!window.getUserMedia) {
4234 window.getUserMedia = navigator['getUserMedia'] ||
4235 navigator['mozGetUserMedia'];
4237 window.getUserMedia(func);
4238 },getMovementX:function (event) {
4239 return event['movementX'] ||
4240 event['mozMovementX'] ||
4241 event['webkitMovementX'] ||
4243 },getMovementY:function (event) {
4244 return event['movementY'] ||
4245 event['mozMovementY'] ||
4246 event['webkitMovementY'] ||
4248 },getMouseWheelDelta:function (event) {
4249 return Math.max(-1, Math.min(1, event.type === 'DOMMouseScroll' ? event.detail : -event.wheelDelta));
4250 },mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,calculateMouseEvent:function (event) { // event should be mousemove, mousedown or mouseup
4251 if (Browser.pointerLock) {
4252 // When the pointer is locked, calculate the coordinates
4253 // based on the movement of the mouse.
4254 // Workaround for Firefox bug 764498
4255 if (event.type != 'mousemove' &&
4256 ('mozMovementX' in event)) {
4257 Browser.mouseMovementX = Browser.mouseMovementY = 0;
4259 Browser.mouseMovementX = Browser.getMovementX(event);
4260 Browser.mouseMovementY = Browser.getMovementY(event);
4263 // check if SDL is available
4264 if (typeof SDL != "undefined") {
4265 Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
4266 Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
4268 // just add the mouse delta to the current absolut mouse position
4269 // FIXME: ideally this should be clamped against the canvas size and zero
4270 Browser.mouseX += Browser.mouseMovementX;
4271 Browser.mouseY += Browser.mouseMovementY;
4274 // Otherwise, calculate the movement based on the changes
4275 // in the coordinates.
4276 var rect = Module["canvas"].getBoundingClientRect();
4279 // Neither .scrollX or .pageXOffset are defined in a spec, but
4280 // we prefer .scrollX because it is currently in a spec draft.
4281 // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
4282 var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
4283 var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
4284 if (event.type == 'touchstart' ||
4285 event.type == 'touchend' ||
4286 event.type == 'touchmove') {
4287 var t = event.touches.item(0);
4289 x = t.pageX - (scrollX + rect.left);
4290 y = t.pageY - (scrollY + rect.top);
4295 x = event.pageX - (scrollX + rect.left);
4296 y = event.pageY - (scrollY + rect.top);
4299 // the canvas might be CSS-scaled compared to its backbuffer;
4300 // SDL-using content will want mouse coordinates in terms
4301 // of backbuffer units.
4302 var cw = Module["canvas"].width;
4303 var ch = Module["canvas"].height;
4304 x = x * (cw / rect.width);
4305 y = y * (ch / rect.height);
4307 Browser.mouseMovementX = x - Browser.mouseX;
4308 Browser.mouseMovementY = y - Browser.mouseY;
4312 },xhrLoad:function (url, onload, onerror) {
4313 var xhr = new XMLHttpRequest();
4314 xhr.open('GET', url, true);
4315 xhr.responseType = 'arraybuffer';
4316 xhr.onload = function xhr_onload() {
4317 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
4318 onload(xhr.response);
4323 xhr.onerror = onerror;
4325 },asyncLoad:function (url, onload, onerror, noRunDep) {
4326 Browser.xhrLoad(url, function(arrayBuffer) {
4327 assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
4328 onload(new Uint8Array(arrayBuffer));
4329 if (!noRunDep) removeRunDependency('al ' + url);
4330 }, function(event) {
4334 throw 'Loading data file "' + url + '" failed.';
4337 if (!noRunDep) addRunDependency('al ' + url);
4338 },resizeListeners:[],updateResizeListeners:function () {
4339 var canvas = Module['canvas'];
4340 Browser.resizeListeners.forEach(function(listener) {
4341 listener(canvas.width, canvas.height);
4343 },setCanvasSize:function (width, height, noUpdates) {
4344 var canvas = Module['canvas'];
4345 Browser.updateCanvasDimensions(canvas, width, height);
4346 if (!noUpdates) Browser.updateResizeListeners();
4347 },windowedWidth:0,windowedHeight:0,setFullScreenCanvasSize:function () {
4348 // check if SDL is available
4349 if (typeof SDL != "undefined") {
4350 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
4351 flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
4352 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
4354 Browser.updateResizeListeners();
4355 },setWindowedCanvasSize:function () {
4356 // check if SDL is available
4357 if (typeof SDL != "undefined") {
4358 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
4359 flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
4360 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
4362 Browser.updateResizeListeners();
4363 },updateCanvasDimensions:function (canvas, wNative, hNative) {
4364 if (wNative && hNative) {
4365 canvas.widthNative = wNative;
4366 canvas.heightNative = hNative;
4368 wNative = canvas.widthNative;
4369 hNative = canvas.heightNative;
4373 if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
4374 if (w/h < Module['forcedAspectRatio']) {
4375 w = Math.round(h * Module['forcedAspectRatio']);
4377 h = Math.round(w / Module['forcedAspectRatio']);
4380 if (((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
4381 document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
4382 document['fullScreenElement'] || document['fullscreenElement'] ||
4383 document['msFullScreenElement'] || document['msFullscreenElement'] ||
4384 document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
4385 var factor = Math.min(screen.width / w, screen.height / h);
4386 w = Math.round(w * factor);
4387 h = Math.round(h * factor);
4389 if (Browser.resizeCanvas) {
4390 if (canvas.width != w) canvas.width = w;
4391 if (canvas.height != h) canvas.height = h;
4392 if (typeof canvas.style != 'undefined') {
4393 canvas.style.removeProperty( "width");
4394 canvas.style.removeProperty("height");
4397 if (canvas.width != wNative) canvas.width = wNative;
4398 if (canvas.height != hNative) canvas.height = hNative;
4399 if (typeof canvas.style != 'undefined') {
4400 if (w != wNative || h != hNative) {
4401 canvas.style.setProperty( "width", w + "px", "important");
4402 canvas.style.setProperty("height", h + "px", "important");
4404 canvas.style.removeProperty( "width");
4405 canvas.style.removeProperty("height");
4417 function _mkport() { throw 'TODO' }var SOCKFS={mount:function (mount) {
4418 return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
4419 },createSocket:function (family, type, protocol) {
4420 var streaming = type == 1;
4422 assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
4425 // create our internal socket structure
4434 sock_ops: SOCKFS.websocket_sock_ops
4437 // create the filesystem node to store the socket structure
4438 var name = SOCKFS.nextname();
4439 var node = FS.createNode(SOCKFS.root, name, 49152, 0);
4442 // and the wrapping stream that enables library functions such
4443 // as read and write to indirectly interact with the socket
4444 var stream = FS.createStream({
4447 flags: FS.modeStringToFlags('r+'),
4449 stream_ops: SOCKFS.stream_ops
4452 // map the new stream to the socket structure (sockets have a 1:1
4453 // relationship with a stream)
4454 sock.stream = stream;
4457 },getSocket:function (fd) {
4458 var stream = FS.getStream(fd);
4459 if (!stream || !FS.isSocket(stream.node.mode)) {
4462 return stream.node.sock;
4463 },stream_ops:{poll:function (stream) {
4464 var sock = stream.node.sock;
4465 return sock.sock_ops.poll(sock);
4466 },ioctl:function (stream, request, varargs) {
4467 var sock = stream.node.sock;
4468 return sock.sock_ops.ioctl(sock, request, varargs);
4469 },read:function (stream, buffer, offset, length, position /* ignored */) {
4470 var sock = stream.node.sock;
4471 var msg = sock.sock_ops.recvmsg(sock, length);
4476 buffer.set(msg.buffer, offset);
4477 return msg.buffer.length;
4478 },write:function (stream, buffer, offset, length, position /* ignored */) {
4479 var sock = stream.node.sock;
4480 return sock.sock_ops.sendmsg(sock, buffer, offset, length);
4481 },close:function (stream) {
4482 var sock = stream.node.sock;
4483 sock.sock_ops.close(sock);
4484 }},nextname:function () {
4485 if (!SOCKFS.nextname.current) {
4486 SOCKFS.nextname.current = 0;
4488 return 'socket[' + (SOCKFS.nextname.current++) + ']';
4489 },websocket_sock_ops:{createPeer:function (sock, addr, port) {
4492 if (typeof addr === 'object') {
4499 // for sockets that've already connected (e.g. we're the server)
4500 // we can inspect the _socket property for the address
4502 addr = ws._socket.remoteAddress;
4503 port = ws._socket.remotePort;
4505 // if we're just now initializing a connection to the remote,
4506 // inspect the url property
4508 var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
4510 throw new Error('WebSocket URL must be in the format ws(s)://address:port');
4513 port = parseInt(result[2], 10);
4516 // create the actual websocket object and connect
4518 // runtimeConfig gets set to true if WebSocket runtime configuration is available.
4519 var runtimeConfig = (Module['websocket'] && ('object' === typeof Module['websocket']));
4521 // The default value is 'ws://' the replace is needed because the compiler replaces "//" comments with '#'
4522 // comments without checking context, so we'd end up with ws:#, the replace swaps the "#" for "//" again.
4523 var url = 'ws:#'.replace('#', '//');
4525 if (runtimeConfig) {
4526 if ('string' === typeof Module['websocket']['url']) {
4527 url = Module['websocket']['url']; // Fetch runtime WebSocket URL config.
4531 if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
4532 url = url + addr + ':' + port;
4535 // Make the WebSocket subprotocol (Sec-WebSocket-Protocol) default to binary if no configuration is set.
4536 var subProtocols = 'binary'; // The default value is 'binary'
4538 if (runtimeConfig) {
4539 if ('string' === typeof Module['websocket']['subprotocol']) {
4540 subProtocols = Module['websocket']['subprotocol']; // Fetch runtime WebSocket subprotocol config.
4544 // The regex trims the string (removes spaces at the beginning and end, then splits the string by
4545 // <any space>,<any space> into an Array. Whitespace removal is important for Websockify and ws.
4546 subProtocols = subProtocols.replace(/^ +| +$/g,"").split(/ *, */);
4548 // The node ws library API for specifying optional subprotocol is slightly different than the browser's.
4549 var opts = ENVIRONMENT_IS_NODE ? {'protocol': subProtocols.toString()} : subProtocols;
4551 // If node we use the ws library.
4552 var WebSocket = ENVIRONMENT_IS_NODE ? require('ws') : window['WebSocket'];
4553 ws = new WebSocket(url, opts);
4554 ws.binaryType = 'arraybuffer';
4556 throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
4565 dgram_send_queue: []
4568 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4569 SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
4571 // if this is a bound dgram socket, send the port number first to allow
4572 // us to override the ephemeral port reported to us by remotePort on the
4574 if (sock.type === 2 && typeof sock.sport !== 'undefined') {
4575 peer.dgram_send_queue.push(new Uint8Array([
4577 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0),
4578 ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
4583 },getPeer:function (sock, addr, port) {
4584 return sock.peers[addr + ':' + port];
4585 },addPeer:function (sock, peer) {
4586 sock.peers[peer.addr + ':' + peer.port] = peer;
4587 },removePeer:function (sock, peer) {
4588 delete sock.peers[peer.addr + ':' + peer.port];
4589 },handlePeerEvents:function (sock, peer) {
4592 var handleOpen = function () {
4594 var queued = peer.dgram_send_queue.shift();
4596 peer.socket.send(queued);
4597 queued = peer.dgram_send_queue.shift();
4600 // not much we can do here in the way of proper error handling as we've already
4601 // lied and said this data was sent. shut it down.
4602 peer.socket.close();
4606 function handleMessage(data) {
4607 assert(typeof data !== 'string' && data.byteLength !== undefined); // must receive an ArrayBuffer
4608 data = new Uint8Array(data); // make a typed array view on the array buffer
4611 // if this is the port message, override the peer's port with it
4612 var wasfirst = first;
4615 data.length === 10 &&
4616 data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
4617 data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) && data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
4618 // update the peer's port and it's key in the peer map
4619 var newport = ((data[8] << 8) | data[9]);
4620 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4621 peer.port = newport;
4622 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4626 sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
4629 if (ENVIRONMENT_IS_NODE) {
4630 peer.socket.on('open', handleOpen);
4631 peer.socket.on('message', function(data, flags) {
4632 if (!flags.binary) {
4635 handleMessage((new Uint8Array(data)).buffer); // copy from node Buffer -> ArrayBuffer
4637 peer.socket.on('error', function() {
4641 peer.socket.onopen = handleOpen;
4642 peer.socket.onmessage = function peer_socket_onmessage(event) {
4643 handleMessage(event.data);
4646 },poll:function (sock) {
4647 if (sock.type === 1 && sock.server) {
4648 // listen sockets should only say they're available for reading
4649 // if there are pending clients.
4650 return sock.pending.length ? (64 | 1) : 0;
4654 var dest = sock.type === 1 ? // we only care about the socket state for connection-based sockets
4655 SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
4658 if (sock.recv_queue.length ||
4659 !dest || // connection-less sockets are always ready to read
4660 (dest && dest.socket.readyState === dest.socket.CLOSING) ||
4661 (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
4665 if (!dest || // connection-less sockets are always ready to write
4666 (dest && dest.socket.readyState === dest.socket.OPEN)) {
4670 if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
4671 (dest && dest.socket.readyState === dest.socket.CLOSED)) {
4676 },ioctl:function (sock, request, arg) {
4680 if (sock.recv_queue.length) {
4681 bytes = sock.recv_queue[0].data.length;
4683 HEAP32[((arg)>>2)]=bytes;
4686 return ERRNO_CODES.EINVAL;
4688 },close:function (sock) {
4689 // if we've spawned a listen server, close it
4692 sock.server.close();
4697 // close any peer connections
4698 var peers = Object.keys(sock.peers);
4699 for (var i = 0; i < peers.length; i++) {
4700 var peer = sock.peers[peers[i]];
4702 peer.socket.close();
4705 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4708 },bind:function (sock, addr, port) {
4709 if (typeof sock.saddr !== 'undefined' || typeof sock.sport !== 'undefined') {
4710 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already bound
4713 sock.sport = port || _mkport();
4714 // in order to emulate dgram sockets, we need to launch a listen server when
4715 // binding on a connection-less socket
4716 // note: this is only required on the server side
4717 if (sock.type === 2) {
4718 // close the existing server if it exists
4720 sock.server.close();
4723 // swallow error operation not supported error that occurs when binding in the
4724 // browser where this isn't supported
4726 sock.sock_ops.listen(sock, 0);
4728 if (!(e instanceof FS.ErrnoError)) throw e;
4729 if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
4732 },connect:function (sock, addr, port) {
4734 throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
4738 // if (!sock.addr && sock.type == 2) {
4741 // early out if we're already connected / in the middle of connecting
4742 if (typeof sock.daddr !== 'undefined' && typeof sock.dport !== 'undefined') {
4743 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
4745 if (dest.socket.readyState === dest.socket.CONNECTING) {
4746 throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
4748 throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
4753 // add the socket to our peer list and set our
4754 // destination address / port to match
4755 var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4756 sock.daddr = peer.addr;
4757 sock.dport = peer.port;
4759 // always "fail" in non-blocking mode
4760 throw new FS.ErrnoError(ERRNO_CODES.EINPROGRESS);
4761 },listen:function (sock, backlog) {
4762 if (!ENVIRONMENT_IS_NODE) {
4763 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
4766 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already listening
4768 var WebSocketServer = require('ws').Server;
4769 var host = sock.saddr;
4770 sock.server = new WebSocketServer({
4773 // TODO support backlog
4776 sock.server.on('connection', function(ws) {
4777 if (sock.type === 1) {
4778 var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
4780 // create a peer on the new socket
4781 var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
4782 newsock.daddr = peer.addr;
4783 newsock.dport = peer.port;
4785 // push to queue for accept to pick up
4786 sock.pending.push(newsock);
4788 // create a peer on the listen socket so calling sendto
4789 // with the listen socket and an address will resolve
4790 // to the correct client
4791 SOCKFS.websocket_sock_ops.createPeer(sock, ws);
4794 sock.server.on('closed', function() {
4797 sock.server.on('error', function() {
4800 },accept:function (listensock) {
4801 if (!listensock.server) {
4802 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4804 var newsock = listensock.pending.shift();
4805 newsock.stream.flags = listensock.stream.flags;
4807 },getname:function (sock, peer) {
4810 if (sock.daddr === undefined || sock.dport === undefined) {
4811 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4816 // TODO saddr and sport will be set for bind()'d UDP sockets, but what
4817 // should we be returning for TCP sockets that've been connect()'d?
4818 addr = sock.saddr || 0;
4819 port = sock.sport || 0;
4821 return { addr: addr, port: port };
4822 },sendmsg:function (sock, buffer, offset, length, addr, port) {
4823 if (sock.type === 2) {
4824 // connection-less sockets will honor the message address,
4825 // and otherwise fall back to the bound destination address
4826 if (addr === undefined || port === undefined) {
4830 // if there was no address to fall back to, error out
4831 if (addr === undefined || port === undefined) {
4832 throw new FS.ErrnoError(ERRNO_CODES.EDESTADDRREQ);
4835 // connection-based sockets will only use the bound
4840 // find the peer for the destination address
4841 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
4843 // early out if not connected with a connection-based socket
4844 if (sock.type === 1) {
4845 if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4846 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4847 } else if (dest.socket.readyState === dest.socket.CONNECTING) {
4848 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4852 // create a copy of the incoming data to send, as the WebSocket API
4853 // doesn't work entirely with an ArrayBufferView, it'll just send
4854 // the entire underlying buffer
4856 if (buffer instanceof Array || buffer instanceof ArrayBuffer) {
4857 data = buffer.slice(offset, offset + length);
4858 } else { // ArrayBufferView
4859 data = buffer.buffer.slice(buffer.byteOffset + offset, buffer.byteOffset + offset + length);
4862 // if we're emulating a connection-less dgram socket and don't have
4863 // a cached connection, queue the buffer to send upon connect and
4864 // lie, saying the data was sent now.
4865 if (sock.type === 2) {
4866 if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
4867 // if we're not connected, open a new connection
4868 if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4869 dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4871 dest.dgram_send_queue.push(data);
4877 // send the actual data
4878 dest.socket.send(data);
4881 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4883 },recvmsg:function (sock, length) {
4884 // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
4885 if (sock.type === 1 && sock.server) {
4886 // tcp servers should not be recv()'ing on the listen socket
4887 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4890 var queued = sock.recv_queue.shift();
4892 if (sock.type === 1) {
4893 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
4896 // if we have a destination address but are not connected, error out
4897 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4899 else if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4900 // return null if the socket has closed
4904 // else, our socket is in a valid state but truly has nothing available
4905 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4908 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4912 // queued.data will be an ArrayBuffer if it's unadulterated, but if it's
4913 // requeued TCP data it'll be an ArrayBufferView
4914 var queuedLength = queued.data.byteLength || queued.data.length;
4915 var queuedOffset = queued.data.byteOffset || 0;
4916 var queuedBuffer = queued.data.buffer || queued.data;
4917 var bytesRead = Math.min(length, queuedLength);
4919 buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
4925 // push back any unread data for TCP connections
4926 if (sock.type === 1 && bytesRead < queuedLength) {
4927 var bytesRemaining = queuedLength - bytesRead;
4928 queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
4929 sock.recv_queue.unshift(queued);
4933 }}};function _send(fd, buf, len, flags) {
4934 var sock = SOCKFS.getSocket(fd);
4936 ___setErrNo(ERRNO_CODES.EBADF);
4940 return _write(fd, buf, len);
4943 function _pwrite(fildes, buf, nbyte, offset) {
4944 // ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset);
4945 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4946 var stream = FS.getStream(fildes);
4948 ___setErrNo(ERRNO_CODES.EBADF);
4953 return FS.write(stream, slab, buf, nbyte, offset);
4955 FS.handleFSError(e);
4958 }function _write(fildes, buf, nbyte) {
4959 // ssize_t write(int fildes, const void *buf, size_t nbyte);
4960 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4961 var stream = FS.getStream(fildes);
4963 ___setErrNo(ERRNO_CODES.EBADF);
4970 return FS.write(stream, slab, buf, nbyte);
4972 FS.handleFSError(e);
4977 function _fileno(stream) {
4978 // int fileno(FILE *stream);
4979 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fileno.html
4980 stream = FS.getStreamFromPtr(stream);
4981 if (!stream) return -1;
4983 }function _fwrite(ptr, size, nitems, stream) {
4984 // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
4985 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fwrite.html
4986 var bytesToWrite = nitems * size;
4987 if (bytesToWrite == 0) return 0;
4988 var fd = _fileno(stream);
4989 var bytesWritten = _write(fd, ptr, bytesToWrite);
4990 if (bytesWritten == -1) {
4991 var streamObj = FS.getStreamFromPtr(stream);
4992 if (streamObj) streamObj.error = true;
4995 return Math.floor(bytesWritten / size);
5001 Module["_strlen"] = _strlen;
5003 function __reallyNegative(x) {
5004 return x < 0 || (x === 0 && (1/x) === -Infinity);
5005 }function __formatString(format, varargs) {
5006 var textIndex = format;
5008 function getNextArg(type) {
5009 // NOTE: Explicitly ignoring type safety. Otherwise this fails:
5010 // int x = 4; printf("%c\n", (char)x);
5012 if (type === 'double') {
5013 ret = HEAPF64[(((varargs)+(argIndex))>>3)];
5014 } else if (type == 'i64') {
5015 ret = [HEAP32[(((varargs)+(argIndex))>>2)],
5016 HEAP32[(((varargs)+(argIndex+4))>>2)]];
5019 type = 'i32'; // varargs are always i32, i64, or double
5020 ret = HEAP32[(((varargs)+(argIndex))>>2)];
5022 argIndex += Runtime.getNativeFieldSize(type);
5027 var curr, next, currArg;
5029 var startTextIndex = textIndex;
5030 curr = HEAP8[(textIndex)];
5031 if (curr === 0) break;
5032 next = HEAP8[((textIndex+1)|0)];
5035 var flagAlwaysSigned = false;
5036 var flagLeftAlign = false;
5037 var flagAlternative = false;
5038 var flagZeroPad = false;
5039 var flagPadSign = false;
5040 flagsLoop: while (1) {
5043 flagAlwaysSigned = true;
5046 flagLeftAlign = true;
5049 flagAlternative = true;
5065 next = HEAP8[((textIndex+1)|0)];
5071 width = getNextArg('i32');
5073 next = HEAP8[((textIndex+1)|0)];
5075 while (next >= 48 && next <= 57) {
5076 width = width * 10 + (next - 48);
5078 next = HEAP8[((textIndex+1)|0)];
5082 // Handle precision.
5083 var precisionSet = false, precision = -1;
5086 precisionSet = true;
5088 next = HEAP8[((textIndex+1)|0)];
5090 precision = getNextArg('i32');
5094 var precisionChr = HEAP8[((textIndex+1)|0)];
5095 if (precisionChr < 48 ||
5096 precisionChr > 57) break;
5097 precision = precision * 10 + (precisionChr - 48);
5101 next = HEAP8[((textIndex+1)|0)];
5103 if (precision < 0) {
5104 precision = 6; // Standard default.
5105 precisionSet = false;
5108 // Handle integer sizes. WARNING: These assume a 32-bit architecture!
5110 switch (String.fromCharCode(next)) {
5112 var nextNext = HEAP8[((textIndex+2)|0)];
5113 if (nextNext == 104) {
5115 argSize = 1; // char (actually i32 in varargs)
5117 argSize = 2; // short (actually i32 in varargs)
5121 var nextNext = HEAP8[((textIndex+2)|0)];
5122 if (nextNext == 108) {
5124 argSize = 8; // long long
5126 argSize = 4; // long
5129 case 'L': // long long
5130 case 'q': // int64_t
5131 case 'j': // intmax_t
5135 case 't': // ptrdiff_t
5136 case 'I': // signed ptrdiff_t or unsigned size_t
5142 if (argSize) textIndex++;
5143 next = HEAP8[((textIndex+1)|0)];
5145 // Handle type specifier.
5146 switch (String.fromCharCode(next)) {
5147 case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': {
5149 var signed = next == 100 || next == 105;
5150 argSize = argSize || 4;
5151 var currArg = getNextArg('i' + (argSize * 8));
5153 // Flatten i64-1 [low, high] into a (slightly rounded) double
5155 currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117);
5157 // Truncate to requested size.
5159 var limit = Math.pow(256, argSize) - 1;
5160 currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
5162 // Format the number.
5163 var currAbsArg = Math.abs(currArg);
5165 if (next == 100 || next == 105) {
5166 argText = reSign(currArg, 8 * argSize, 1).toString(10);
5167 } else if (next == 117) {
5168 argText = unSign(currArg, 8 * argSize, 1).toString(10);
5169 currArg = Math.abs(currArg);
5170 } else if (next == 111) {
5171 argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
5172 } else if (next == 120 || next == 88) {
5173 prefix = (flagAlternative && currArg != 0) ? '0x' : '';
5175 // Represent negative numbers in hex as 2's complement.
5177 argText = (currAbsArg - 1).toString(16);
5179 for (var i = 0; i < argText.length; i++) {
5180 buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
5182 argText = buffer.join('');
5183 while (argText.length < argSize * 2) argText = 'f' + argText;
5185 argText = currAbsArg.toString(16);
5188 prefix = prefix.toUpperCase();
5189 argText = argText.toUpperCase();
5191 } else if (next == 112) {
5192 if (currAbsArg === 0) {
5196 argText = currAbsArg.toString(16);
5200 while (argText.length < precision) {
5201 argText = '0' + argText;
5205 // Add sign if needed
5207 if (flagAlwaysSigned) {
5208 prefix = '+' + prefix;
5209 } else if (flagPadSign) {
5210 prefix = ' ' + prefix;
5214 // Move sign to prefix so we zero-pad after the sign
5215 if (argText.charAt(0) == '-') {
5216 prefix = '-' + prefix;
5217 argText = argText.substr(1);
5221 while (prefix.length + argText.length < width) {
5222 if (flagLeftAlign) {
5226 argText = '0' + argText;
5228 prefix = ' ' + prefix;
5233 // Insert the result into the buffer.
5234 argText = prefix + argText;
5235 argText.split('').forEach(function(chr) {
5236 ret.push(chr.charCodeAt(0));
5240 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': {
5242 var currArg = getNextArg('double');
5244 if (isNaN(currArg)) {
5246 flagZeroPad = false;
5247 } else if (!isFinite(currArg)) {
5248 argText = (currArg < 0 ? '-' : '') + 'inf';
5249 flagZeroPad = false;
5251 var isGeneral = false;
5252 var effectivePrecision = Math.min(precision, 20);
5254 // Convert g/G to f/F or e/E, as per:
5255 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
5256 if (next == 103 || next == 71) {
5258 precision = precision || 1;
5259 var exponent = parseInt(currArg.toExponential(effectivePrecision).split('e')[1], 10);
5260 if (precision > exponent && exponent >= -4) {
5261 next = ((next == 103) ? 'f' : 'F').charCodeAt(0);
5262 precision -= exponent + 1;
5264 next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
5267 effectivePrecision = Math.min(precision, 20);
5270 if (next == 101 || next == 69) {
5271 argText = currArg.toExponential(effectivePrecision);
5272 // Make sure the exponent has at least 2 digits.
5273 if (/[eE][-+]\d$/.test(argText)) {
5274 argText = argText.slice(0, -1) + '0' + argText.slice(-1);
5276 } else if (next == 102 || next == 70) {
5277 argText = currArg.toFixed(effectivePrecision);
5278 if (currArg === 0 && __reallyNegative(currArg)) {
5279 argText = '-' + argText;
5283 var parts = argText.split('e');
5284 if (isGeneral && !flagAlternative) {
5285 // Discard trailing zeros and periods.
5286 while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
5287 (parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.')) {
5288 parts[0] = parts[0].slice(0, -1);
5291 // Make sure we have a period in alternative mode.
5292 if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
5293 // Zero pad until required precision.
5294 while (precision > effectivePrecision++) parts[0] += '0';
5296 argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
5298 // Capitalize 'E' if needed.
5299 if (next == 69) argText = argText.toUpperCase();
5303 if (flagAlwaysSigned) {
5304 argText = '+' + argText;
5305 } else if (flagPadSign) {
5306 argText = ' ' + argText;
5312 while (argText.length < width) {
5313 if (flagLeftAlign) {
5316 if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
5317 argText = argText[0] + '0' + argText.slice(1);
5319 argText = (flagZeroPad ? '0' : ' ') + argText;
5325 if (next < 97) argText = argText.toUpperCase();
5327 // Insert the result into the buffer.
5328 argText.split('').forEach(function(chr) {
5329 ret.push(chr.charCodeAt(0));
5335 var arg = getNextArg('i8*');
5336 var argLength = arg ? _strlen(arg) : '(null)'.length;
5337 if (precisionSet) argLength = Math.min(argLength, precision);
5338 if (!flagLeftAlign) {
5339 while (argLength < width--) {
5344 for (var i = 0; i < argLength; i++) {
5345 ret.push(HEAPU8[((arg++)|0)]);
5348 ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true));
5350 if (flagLeftAlign) {
5351 while (argLength < width--) {
5359 if (flagLeftAlign) ret.push(getNextArg('i8'));
5360 while (--width > 0) {
5363 if (!flagLeftAlign) ret.push(getNextArg('i8'));
5367 // Write the length written so far to the next parameter.
5368 var ptr = getNextArg('i32*');
5369 HEAP32[((ptr)>>2)]=ret.length;
5373 // Literal percent sign.
5378 // Unknown specifiers remain untouched.
5379 for (var i = startTextIndex; i < textIndex + 2; i++) {
5380 ret.push(HEAP8[(i)]);
5385 // TODO: Support a/A (hex float) and m (last error) specifiers.
5386 // TODO: Support %1${specifier} for arg selection.
5393 }function _fprintf(stream, format, varargs) {
5394 // int fprintf(FILE *restrict stream, const char *restrict format, ...);
5395 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
5396 var result = __formatString(format, varargs);
5397 var stack = Runtime.stackSave();
5398 var ret = _fwrite(allocate(result, 'i8', ALLOC_STACK), 1, result.length, stream);
5399 Runtime.stackRestore(stack);
5401 }function _printf(format, varargs) {
5402 // int printf(const char *restrict format, ...);
5403 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
5404 var stdout = HEAP32[((_stdout)>>2)];
5405 return _fprintf(stdout, format, varargs);
5409 Module["_memset"] = _memset;
5413 function _emscripten_memcpy_big(dest, src, num) {
5414 HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
5417 Module["_memcpy"] = _memcpy;
5421 Module["_free"] = _free;
5422 Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, resizeCanvas) { Browser.requestFullScreen(lockPointer, resizeCanvas) };
5423 Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
5424 Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };
5425 Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };
5426 Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };
5427 Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }
5428 FS.staticInit();__ATINIT__.unshift({ func: function() { if (!Module["noFSInit"] && !FS.init.initialized) FS.init() } });__ATMAIN__.push({ func: function() { FS.ignorePermissions = false } });__ATEXIT__.push({ func: function() { FS.quit() } });Module["FS_createFolder"] = FS.createFolder;Module["FS_createPath"] = FS.createPath;Module["FS_createDataFile"] = FS.createDataFile;Module["FS_createPreloadedFile"] = FS.createPreloadedFile;Module["FS_createLazyFile"] = FS.createLazyFile;Module["FS_createLink"] = FS.createLink;Module["FS_createDevice"] = FS.createDevice;
5429 ___errno_state = Runtime.staticAlloc(4); HEAP32[((___errno_state)>>2)]=0;
5430 __ATINIT__.unshift({ func: function() { TTY.init() } });__ATEXIT__.push({ func: function() { TTY.shutdown() } });TTY.utf8 = new Runtime.UTF8Processor();
5431 if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); NODEFS.staticInit(); }
5432 __ATINIT__.push({ func: function() { SOCKFS.root = FS.mount(SOCKFS, {}, null); } });
5433 STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
5435 staticSealed = true; // seal the static portion of memory
5437 STACK_MAX = STACK_BASE + 5242880;
5439 DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
5441 assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
5444 var Math_min = Math.min;
5445 function asmPrintInt(x, y) {
5446 Module.print('int ' + x + ',' + y);// + ' ' + new Error().stack);
5448 function asmPrintFloat(x, y) {
5449 Module.print('float ' + x + ',' + y);// + ' ' + new Error().stack);
5451 // EMSCRIPTEN_START_ASM
5452 var asm = (function(global, env, buffer) {
5454 var HEAP8 = new global.Int8Array(buffer);
5455 var HEAP16 = new global.Int16Array(buffer);
5456 var HEAP32 = new global.Int32Array(buffer);
5457 var HEAPU8 = new global.Uint8Array(buffer);
5458 var HEAPU16 = new global.Uint16Array(buffer);
5459 var HEAPU32 = new global.Uint32Array(buffer);
5460 var HEAPF32 = new global.Float32Array(buffer);
5461 var HEAPF64 = new global.Float64Array(buffer);
5463 var STACKTOP=env.STACKTOP|0;
5464 var STACK_MAX=env.STACK_MAX|0;
5465 var tempDoublePtr=env.tempDoublePtr|0;
5466 var ABORT=env.ABORT|0;
5472 var nan = +env.NaN, inf = +env.Infinity;
5473 var tempInt = 0, tempBigInt = 0, tempBigIntP = 0, tempBigIntS = 0, tempBigIntR = 0.0, tempBigIntI = 0, tempBigIntD = 0, tempValue = 0, tempDouble = 0.0;
5485 var Math_floor=global.Math.floor;
5486 var Math_abs=global.Math.abs;
5487 var Math_sqrt=global.Math.sqrt;
5488 var Math_pow=global.Math.pow;
5489 var Math_cos=global.Math.cos;
5490 var Math_sin=global.Math.sin;
5491 var Math_tan=global.Math.tan;
5492 var Math_acos=global.Math.acos;
5493 var Math_asin=global.Math.asin;
5494 var Math_atan=global.Math.atan;
5495 var Math_atan2=global.Math.atan2;
5496 var Math_exp=global.Math.exp;
5497 var Math_log=global.Math.log;
5498 var Math_ceil=global.Math.ceil;
5499 var Math_imul=global.Math.imul;
5500 var abort=env.abort;
5501 var assert=env.assert;
5502 var asmPrintInt=env.asmPrintInt;
5503 var asmPrintFloat=env.asmPrintFloat;
5504 var Math_min=env.min;
5505 var _free=env._free;
5506 var _emscripten_memcpy_big=env._emscripten_memcpy_big;
5507 var _printf=env._printf;
5508 var _send=env._send;
5509 var _pwrite=env._pwrite;
5510 var __reallyNegative=env.__reallyNegative;
5511 var _fwrite=env._fwrite;
5512 var _malloc=env._malloc;
5513 var _mkport=env._mkport;
5514 var _fprintf=env._fprintf;
5515 var ___setErrNo=env.___setErrNo;
5516 var __formatString=env.__formatString;
5517 var _fileno=env._fileno;
5518 var _fflush=env._fflush;
5519 var _write=env._write;
5520 var tempFloat = 0.0;
5522 // EMSCRIPTEN_START_FUNCS
5523 function _main(i3, i5) {
5526 var i1 = 0, i2 = 0, i4 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0, i10 = 0, i11 = 0;
5528 STACKTOP = STACKTOP + 16 | 0;
5532 i3 = HEAP8[HEAP32[i5 + 4 >> 2] | 0] | 0;
5567 HEAP32[i2 >> 2] = i3 + -48;
5568 _printf(8, i2 | 0) | 0;
5578 if ((i4 | 0) == 4) {
5585 i6 = ((i5 | 0) % 5 | 0) + 1 | 0;
5586 i4 = ((i5 | 0) % 3 | 0) + 1 | 0;
5589 i11 = ((i7 | 0) / (i6 | 0) | 0) + i11 | 0;
5590 if (i11 >>> 0 > 1e3) {
5591 i11 = (i11 >>> 0) / (i4 >>> 0) | 0;
5593 if ((i7 & 3 | 0) == 0) {
5594 i11 = i11 + (Math_imul((i7 & 7 | 0) == 0 ? 1 : -1, i7) | 0) | 0;
5596 i10 = i11 << 16 >> 16;
5597 i10 = (Math_imul(i10, i10) | 0) & 255;
5598 i9 = i10 + (i8 & 65535) | 0;
5600 if ((i7 | 0) == 2e4) {
5607 if ((i5 | 0) < (i3 | 0)) {
5613 HEAP32[i2 >> 2] = i11;
5614 HEAP32[i2 + 4 >> 2] = i8 + i10 & 65535;
5615 _printf(24, i2 | 0) | 0;
5620 function _memcpy(i3, i2, i1) {
5625 if ((i1 | 0) >= 4096) return _emscripten_memcpy_big(i3 | 0, i2 | 0, i1 | 0) | 0;
5627 if ((i3 & 3) == (i2 & 3)) {
5629 if ((i1 | 0) == 0) return i4 | 0;
5630 HEAP8[i3] = HEAP8[i2] | 0;
5635 while ((i1 | 0) >= 4) {
5636 HEAP32[i3 >> 2] = HEAP32[i2 >> 2];
5642 while ((i1 | 0) > 0) {
5643 HEAP8[i3] = HEAP8[i2] | 0;
5650 function _memset(i1, i4, i3) {
5654 var i2 = 0, i5 = 0, i6 = 0, i7 = 0;
5656 if ((i3 | 0) >= 20) {
5659 i6 = i4 | i4 << 8 | i4 << 16 | i4 << 24;
5662 i7 = i1 + 4 - i7 | 0;
5663 while ((i1 | 0) < (i7 | 0)) {
5668 while ((i1 | 0) < (i5 | 0)) {
5669 HEAP32[i1 >> 2] = i6;
5673 while ((i1 | 0) < (i2 | 0)) {
5679 function copyTempDouble(i1) {
5681 HEAP8[tempDoublePtr] = HEAP8[i1];
5682 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
5683 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
5684 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
5685 HEAP8[tempDoublePtr + 4 | 0] = HEAP8[i1 + 4 | 0];
5686 HEAP8[tempDoublePtr + 5 | 0] = HEAP8[i1 + 5 | 0];
5687 HEAP8[tempDoublePtr + 6 | 0] = HEAP8[i1 + 6 | 0];
5688 HEAP8[tempDoublePtr + 7 | 0] = HEAP8[i1 + 7 | 0];
5690 function copyTempFloat(i1) {
5692 HEAP8[tempDoublePtr] = HEAP8[i1];
5693 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
5694 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
5695 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
5697 function runPostSets() {}
5698 function _strlen(i1) {
5702 while (HEAP8[i2] | 0) {
5707 function stackAlloc(i1) {
5711 STACKTOP = STACKTOP + i1 | 0;
5712 STACKTOP = STACKTOP + 7 & -8;
5715 function setThrew(i1, i2) {
5718 if ((__THREW__ | 0) == 0) {
5723 function stackRestore(i1) {
5727 function setTempRet9(i1) {
5731 function setTempRet8(i1) {
5735 function setTempRet7(i1) {
5739 function setTempRet6(i1) {
5743 function setTempRet5(i1) {
5747 function setTempRet4(i1) {
5751 function setTempRet3(i1) {
5755 function setTempRet2(i1) {
5759 function setTempRet1(i1) {
5763 function setTempRet0(i1) {
5767 function stackSave() {
5768 return STACKTOP | 0;
5771 // EMSCRIPTEN_END_FUNCS
5774 return { _strlen: _strlen, _memcpy: _memcpy, _main: _main, _memset: _memset, runPostSets: runPostSets, stackAlloc: stackAlloc, stackSave: stackSave, stackRestore: stackRestore, setThrew: setThrew, setTempRet0: setTempRet0, setTempRet1: setTempRet1, setTempRet2: setTempRet2, setTempRet3: setTempRet3, setTempRet4: setTempRet4, setTempRet5: setTempRet5, setTempRet6: setTempRet6, setTempRet7: setTempRet7, setTempRet8: setTempRet8, setTempRet9: setTempRet9 };
5776 // EMSCRIPTEN_END_ASM
5777 ({ "Math": Math, "Int8Array": Int8Array, "Int16Array": Int16Array, "Int32Array": Int32Array, "Uint8Array": Uint8Array, "Uint16Array": Uint16Array, "Uint32Array": Uint32Array, "Float32Array": Float32Array, "Float64Array": Float64Array }, { "abort": abort, "assert": assert, "asmPrintInt": asmPrintInt, "asmPrintFloat": asmPrintFloat, "min": Math_min, "_free": _free, "_emscripten_memcpy_big": _emscripten_memcpy_big, "_printf": _printf, "_send": _send, "_pwrite": _pwrite, "__reallyNegative": __reallyNegative, "_fwrite": _fwrite, "_malloc": _malloc, "_mkport": _mkport, "_fprintf": _fprintf, "___setErrNo": ___setErrNo, "__formatString": __formatString, "_fileno": _fileno, "_fflush": _fflush, "_write": _write, "STACKTOP": STACKTOP, "STACK_MAX": STACK_MAX, "tempDoublePtr": tempDoublePtr, "ABORT": ABORT, "NaN": NaN, "Infinity": Infinity }, buffer);
5778 var _strlen = Module["_strlen"] = asm["_strlen"];
5779 var _memcpy = Module["_memcpy"] = asm["_memcpy"];
5780 var _main = Module["_main"] = asm["_main"];
5781 var _memset = Module["_memset"] = asm["_memset"];
5782 var runPostSets = Module["runPostSets"] = asm["runPostSets"];
5784 Runtime.stackAlloc = function(size) { return asm['stackAlloc'](size) };
5785 Runtime.stackSave = function() { return asm['stackSave']() };
5786 Runtime.stackRestore = function(top) { asm['stackRestore'](top) };
5789 // Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
5792 // === Auto-generated postamble setup entry stuff ===
5794 if (memoryInitializer) {
5795 if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
5796 var data = Module['readBinary'](memoryInitializer);
5797 HEAPU8.set(data, STATIC_BASE);
5799 addRunDependency('memory initializer');
5800 Browser.asyncLoad(memoryInitializer, function(data) {
5801 HEAPU8.set(data, STATIC_BASE);
5802 removeRunDependency('memory initializer');
5804 throw 'could not load memory initializer ' + memoryInitializer;
5809 function ExitStatus(status) {
5810 this.name = "ExitStatus";
5811 this.message = "Program terminated with exit(" + status + ")";
5812 this.status = status;
5814 ExitStatus.prototype = new Error();
5815 ExitStatus.prototype.constructor = ExitStatus;
5817 var initialStackTop;
5818 var preloadStartTime = null;
5819 var calledMain = false;
5821 dependenciesFulfilled = function runCaller() {
5822 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
5823 if (!Module['calledRun'] && shouldRunNow) run([].concat(Module["arguments"]));
5824 if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
5827 Module['callMain'] = Module.callMain = function callMain(args) {
5828 assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on __ATMAIN__)');
5829 assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
5833 ensureInitRuntime();
5835 var argc = args.length+1;
5837 for (var i = 0; i < 4-1; i++) {
5841 var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORMAL) ];
5843 for (var i = 0; i < argc-1; i = i + 1) {
5844 argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
5848 argv = allocate(argv, 'i32', ALLOC_NORMAL);
5850 initialStackTop = STACKTOP;
5854 var ret = Module['_main'](argc, argv, 0);
5857 // if we're not running an evented main loop, it's time to exit
5858 if (!Module['noExitRuntime']) {
5863 if (e instanceof ExitStatus) {
5864 // exit() throws this once it's done to make sure execution
5865 // has been stopped completely
5867 } else if (e == 'SimulateInfiniteLoop') {
5868 // running an evented main loop, don't immediately exit
5869 Module['noExitRuntime'] = true;
5872 if (e && typeof e === 'object' && e.stack) Module.printErr('exception thrown: ' + [e, e.stack]);
5883 function run(args) {
5884 args = args || Module['arguments'];
5886 if (preloadStartTime === null) preloadStartTime = Date.now();
5888 if (runDependencies > 0) {
5889 Module.printErr('run() called, but dependencies remain, so not running');
5895 if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
5896 if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
5899 if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
5900 Module['calledRun'] = true;
5902 ensureInitRuntime();
5906 if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
5907 Module.printErr('pre-main prep time: ' + (Date.now() - preloadStartTime) + ' ms');
5910 if (Module['_main'] && shouldRunNow) {
5911 Module['callMain'](args);
5917 if (Module['setStatus']) {
5918 Module['setStatus']('Running...');
5919 setTimeout(function() {
5920 setTimeout(function() {
5921 Module['setStatus']('');
5923 if (!ABORT) doRun();
5929 Module['run'] = Module.run = run;
5931 function exit(status) {
5933 EXITSTATUS = status;
5934 STACKTOP = initialStackTop;
5939 // TODO We should handle this differently based on environment.
5940 // In the browser, the best we can do is throw an exception
5941 // to halt execution, but in node we could process.exit and
5942 // I'd imagine SM shell would have something equivalent.
5943 // This would let us set a proper exit status (which
5944 // would be great for checking test exit statuses).
5945 // https://github.com/kripken/emscripten/issues/1371
5947 // throw an exception to halt the current execution
5948 throw new ExitStatus(status);
5950 Module['exit'] = Module.exit = exit;
5952 function abort(text) {
5955 Module.printErr(text);
5961 var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
5963 throw 'abort() at ' + stackTrace() + extra;
5965 Module['abort'] = Module.abort = abort;
5967 // {{PRE_RUN_ADDITIONS}}
5969 if (Module['preInit']) {
5970 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
5971 while (Module['preInit'].length > 0) {
5972 Module['preInit'].pop()();
5976 // shouldRunNow refers to calling main(), not run().
5977 var shouldRunNow = true;
5978 if (Module['noInitialRun']) {
5979 shouldRunNow = false;
5983 run([].concat(Module["arguments"]));