1var EXPECTED_OUTPUT = 'final: 40006013:58243.\n';
2var Module = {
3  arguments: [1],
4  print: function(x) {Module.printBuffer += x + '\n';},
5  preRun: [function() {Module.printBuffer = ''}],
6  postRun: [function() {
7    assertEquals(EXPECTED_OUTPUT, Module.printBuffer);
8  }],
9};
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.
25var Module;
26if (!Module) Module = (typeof Module !== 'undefined' ? Module : null) || {};
27
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.
33var moduleOverrides = {};
34for (var key in Module) {
35  if (Module.hasOwnProperty(key)) {
36    moduleOverrides[key] = Module[key];
37  }
38}
39
40// The environment setup code below is customized to use Module.
41// *** Environment setup code ***
42var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
43var ENVIRONMENT_IS_WEB = typeof window === 'object';
44var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
45var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
46
47if (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');
52  };
53  if (!Module['printErr']) Module['printErr'] = function printErr(x) {
54    process['stderr'].write(x + '\n');
55  };
56
57  var nodeFS = require('fs');
58  var nodePath = require('path');
59
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);
67    }
68    if (ret && !binary) ret = ret.toString();
69    return ret;
70  };
71
72  Module['readBinary'] = function readBinary(filename) { return Module['read'](filename, true) };
73
74  Module['load'] = function load(f) {
75    globalEval(read(f));
76  };
77
78  Module['arguments'] = process['argv'].slice(2);
79
80  module['exports'] = Module;
81}
82else 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
85
86  if (typeof read != 'undefined') {
87    Module['read'] = read;
88  } else {
89    Module['read'] = function read() { throw 'no read() available (jsc?)' };
90  }
91
92  Module['readBinary'] = function readBinary(f) {
93    return read(f, 'binary');
94  };
95
96  if (typeof scriptArgs != 'undefined') {
97    Module['arguments'] = scriptArgs;
98  } else if (typeof arguments != 'undefined') {
99    Module['arguments'] = arguments;
100  }
101
102  this['Module'] = Module;
103
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)
105}
106else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
107  Module['read'] = function read(url) {
108    var xhr = new XMLHttpRequest();
109    xhr.open('GET', url, false);
110    xhr.send(null);
111    return xhr.responseText;
112  };
113
114  if (typeof arguments != 'undefined') {
115    Module['arguments'] = arguments;
116  }
117
118  if (typeof console !== 'undefined') {
119    if (!Module['print']) Module['print'] = function print(x) {
120      console.log(x);
121    };
122    if (!Module['printErr']) Module['printErr'] = function printErr(x) {
123      console.log(x);
124    };
125  } else {
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) {
129      dump(x);
130    }) : (function(x) {
131      // self.postMessage(x); // enable this if you want stdout to be sent as messages
132    }));
133  }
134
135  if (ENVIRONMENT_IS_WEB) {
136    window['Module'] = Module;
137  } else {
138    Module['load'] = importScripts;
139  }
140}
141else {
142  // Unreachable because SHELL is dependant on the others
143  throw 'Unknown runtime environment. Where are we?';
144}
145
146function globalEval(x) {
147  eval.call(null, x);
148}
149if (!Module['load'] == 'undefined' && Module['read']) {
150  Module['load'] = function load(f) {
151    globalEval(Module['read'](f));
152  };
153}
154if (!Module['print']) {
155  Module['print'] = function(){};
156}
157if (!Module['printErr']) {
158  Module['printErr'] = Module['print'];
159}
160if (!Module['arguments']) {
161  Module['arguments'] = [];
162}
163// *** Environment setup code ***
164
165// Closure helpers
166Module.print = Module['print'];
167Module.printErr = Module['printErr'];
168
169// Callbacks
170Module['preRun'] = [];
171Module['postRun'] = [];
172
173// Merge back in the overrides
174for (var key in moduleOverrides) {
175  if (moduleOverrides.hasOwnProperty(key)) {
176    Module[key] = moduleOverrides[key];
177  }
178}
179
180
181
182// === Auto-generated preamble library stuff ===
183
184//========================================
185// Runtime code shared with compiler
186//========================================
187
188var Runtime = {
189  stackSave: function () {
190    return STACKTOP;
191  },
192  stackRestore: function (stackTop) {
193    STACKTOP = stackTop;
194  },
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 + ')';
202    }
203    return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
204  },
205  isNumberType: function (type) {
206    return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
207  },
208  isPointerType: function isPointerType(type) {
209  return type[type.length-1] == '*';
210},
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] == '%';
217},
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;
223    return l + h;
224  },
225  and64: function (x, y) {
226    var l = (x | 0) & (y | 0);
227    var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 4294967296;
228    return l + h;
229  },
230  xor64: function (x, y) {
231    var l = (x | 0) ^ (y | 0);
232    var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 4294967296;
233    return l + h;
234  },
235  getNativeTypeSize: function (type) {
236    switch (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;
243      default: {
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);
249          return bits/8;
250        } else {
251          return 0;
252        }
253      }
254    }
255  },
256  getNativeFieldSize: function (type) {
257    return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
258  },
259  dedup: function dedup(items, ident) {
260  var seen = {};
261  if (ident) {
262    return items.filter(function(item) {
263      if (seen[item[ident]]) return false;
264      seen[item[ident]] = true;
265      return true;
266    });
267  } else {
268    return items.filter(function(item) {
269      if (seen[item]) return false;
270      seen[item] = true;
271      return true;
272    });
273  }
274},
275  set: function set() {
276  var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
277  var ret = {};
278  for (var i = 0; i < args.length; i++) {
279    ret[args[i]] = 0;
280  }
281  return ret;
282},
283  STACK_ALIGN: 8,
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);
289  },
290  calculateStructAlignment: function calculateStructAlignment(type) {
291    type.flatSize = 0;
292    type.alignSize = 0;
293    var diffs = [];
294    var prev = -1;
295    var index = 0;
296    type.flatIndexes = type.fields.map(function(field) {
297      index++;
298      var size, alignSize;
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!');
307          size = 0;
308          if (Types.types[field]) {
309            alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
310          } else {
311            alignSize = type.alignSize || QUANTUM_SIZE;
312          }
313        } else {
314          size = Types.types[field].flatSize;
315          alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
316        }
317      } else if (field[0] == 'b') {
318        // bN, large number field, like a [N x i8]
319        size = field.substr(1)|0;
320        alignSize = 1;
321      } else if (field[0] === '<') {
322        // vector type
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);
329      } else {
330        assert(false, 'invalid type for calculateStructAlignment');
331      }
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;
336      if (prev >= 0) {
337        diffs.push(curr-prev);
338      }
339      prev = curr;
340      return curr;
341    });
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;
346    }
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];
352    }
353    type.needsFlattening = (type.flatFactor != 1);
354    return type.flatIndexes;
355  },
356  generateStructInfo: function (struct, typeName, offset) {
357    var type, alignment;
358    if (typeName) {
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');
364        return null;
365      }
366      alignment = type.flatIndexes;
367    } else {
368      var type = { fields: struct.map(function(item) { return item[0] }) };
369      alignment = Runtime.calculateStructAlignment(type);
370    }
371    var ret = {
372      __size__: type.flatSize
373    };
374    if (typeName) {
375      struct.forEach(function(item, i) {
376        if (typeof item === 'string') {
377          ret[item] = alignment[i] + offset;
378        } else {
379          // embedded struct
380          var key;
381          for (var k in item) key = k;
382          ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], alignment[i]);
383        }
384      });
385    } else {
386      struct.forEach(function(item, i) {
387        ret[item[1]] = alignment[i];
388      });
389    }
390    return ret;
391  },
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);
397    } else {
398      return Module['dynCall_' + sig].call(null, ptr);
399    }
400  },
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;
406        return 2*(1 + i);
407      }
408    }
409    throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
410  },
411  removeFunction: function (index) {
412    Runtime.functionPointers[(index-2)/2] = null;
413  },
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;
419    var args = [];
420    for (var i = 0; i < numArgs; i++) {
421      args.push(String.fromCharCode(36) + i); // $0, $1 etc
422    }
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);
428      } else {
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)');
431      }
432    }
433    try {
434      var evalled = eval('(function(' + args.join(',') + '){ ' + source + ' })'); // new Function does not allow upvars in node
435    } catch(e) {
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.)');
437      throw e;
438    }
439    return Runtime.asmConstCache[code] = evalled;
440  },
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);
446    }
447  },
448  funcWrappers: {},
449  getFuncWrapper: function (func, sig) {
450    assert(sig);
451    if (!Runtime.funcWrappers[func]) {
452      Runtime.funcWrappers[func] = function dynCall_wrapper() {
453        return Runtime.dynCall(sig, func, arguments);
454      };
455    }
456    return Runtime.funcWrappers[func];
457  },
458  UTF8Processor: function () {
459    var buffer = [];
460    var needed = 0;
461    this.processCChar = function (code) {
462      code = code & 0xFF;
463
464      if (buffer.length == 0) {
465        if ((code & 0x80) == 0x00) {        // 0xxxxxxx
466          return String.fromCharCode(code);
467        }
468        buffer.push(code);
469        if ((code & 0xE0) == 0xC0) {        // 110xxxxx
470          needed = 1;
471        } else if ((code & 0xF0) == 0xE0) { // 1110xxxx
472          needed = 2;
473        } else {                            // 11110xxx
474          needed = 3;
475        }
476        return '';
477      }
478
479      if (needed) {
480        buffer.push(code);
481        needed--;
482        if (needed > 0) return '';
483      }
484
485      var c1 = buffer[0];
486      var c2 = buffer[1];
487      var c3 = buffer[2];
488      var c4 = buffer[3];
489      var ret;
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));
494      } else {
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);
501      }
502      buffer.length = 0;
503      return ret;
504    }
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);
510      */
511      string = unescape(encodeURIComponent(string));
512      var ret = [];
513      for (var i = 0; i < string.length; i++) {
514        ret.push(string.charCodeAt(i));
515      }
516      return ret;
517    }
518  },
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';
521  },
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; },
527  GLOBAL_BASE: 8,
528  QUANTUM_SIZE: 4,
529  __dummy__: 0
530}
531
532
533Module['Runtime'] = Runtime;
534
535
536
537
538
539
540
541
542
543//========================================
544// Runtime essentials
545//========================================
546
547var __THREW__ = 0; // Used in checking for thrown exceptions.
548
549var ABORT = false; // whether we are quitting the application. no code should run after this. set in exit() and abort()
550var EXITSTATUS = 0;
551
552var undef = 0;
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
555var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI, tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD, tempDouble, tempFloat;
556var tempI64, tempI64b;
557var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRet7, tempRet8, tempRet9;
558
559function assert(condition, text) {
560  if (!condition) {
561    abort('Assertion failed: ' + text);
562  }
563}
564
565var globalScope = this;
566
567// C calling interface. A convenient way to call C functions (in C files, or
568// defined with extern "C").
569//
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
573//
574//         -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
575//
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)
584function ccall(ident, returnType, argTypes, args) {
585  return ccallFunc(getCFunc(ident), returnType, argTypes, args);
586}
587Module["ccall"] = ccall;
588
589// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
590function getCFunc(ident) {
591  try {
592    var func = Module['_' + ident]; // closure exported function
593    if (!func) func = eval('_' + ident); // explicit lookup
594  } catch(e) {
595  }
596  assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
597  return func;
598}
599
600// Internal function that does a C call using a function, not an identifier
601function ccallFunc(func, returnType, argTypes, args) {
602  var stack = 0;
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);
607      type = 'array';
608    }
609    if (type == 'array') {
610      if (!stack) stack = Runtime.stackSave();
611      var ret = Runtime.stackAlloc(value.length);
612      writeArrayToMemory(value, ret);
613      return ret;
614    }
615    return value;
616  }
617  function fromC(value, type) {
618    if (type == 'string') {
619      return Pointer_stringify(value);
620    }
621    assert(type != 'array');
622    return value;
623  }
624  var i = 0;
625  var cArgs = args ? args.map(function(arg) {
626    return toC(arg, argTypes[i++]);
627  }) : [];
628  var ret = fromC(func.apply(null, cArgs), returnType);
629  if (stack) Runtime.stackRestore(stack);
630  return ret;
631}
632
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:
635//
636//   var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
637//   alert(my_function(5, 22));
638//   alert(my_function(99, 12));
639//
640function cwrap(ident, returnType, argTypes) {
641  var func = getCFunc(ident);
642  return function() {
643    return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(arguments));
644  }
645}
646Module["cwrap"] = cwrap;
647
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
652// run-time.
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
656function setValue(ptr, value, type, noSafe) {
657  type = type || 'i8';
658  if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
659    switch(type) {
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);
668    }
669}
670Module['setValue'] = setValue;
671
672// Parallel to setValue.
673function getValue(ptr, type, noSafe) {
674  type = type || 'i8';
675  if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
676    switch(type) {
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);
685    }
686  return null;
687}
688Module['getValue'] = getValue;
689
690var ALLOC_NORMAL = 0; // Tries to use _malloc()
691var ALLOC_STACK = 1; // Lives for the duration of the current function call
692var ALLOC_STATIC = 2; // Cannot be freed
693var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
694var ALLOC_NONE = 4; // Do not allocate
695Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
696Module['ALLOC_STACK'] = ALLOC_STACK;
697Module['ALLOC_STATIC'] = ALLOC_STATIC;
698Module['ALLOC_DYNAMIC'] = ALLOC_DYNAMIC;
699Module['ALLOC_NONE'] = ALLOC_NONE;
700
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
708//        affect this!)
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
712//         ignored.
713// @allocator: How to allocate memory, see ALLOC_*
714function allocate(slab, types, allocator, ptr) {
715  var zeroinit, size;
716  if (typeof slab === 'number') {
717    zeroinit = true;
718    size = slab;
719  } else {
720    zeroinit = false;
721    size = slab.length;
722  }
723
724  var singleType = typeof types === 'string' ? types : null;
725
726  var ret;
727  if (allocator == ALLOC_NONE) {
728    ret = ptr;
729  } else {
730    ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
731  }
732
733  if (zeroinit) {
734    var ptr = ret, stop;
735    assert((ret & 3) == 0);
736    stop = ret + (size & ~3);
737    for (; ptr < stop; ptr += 4) {
738      HEAP32[((ptr)>>2)]=0;
739    }
740    stop = ret + size;
741    while (ptr < stop) {
742      HEAP8[((ptr++)|0)]=0;
743    }
744    return ret;
745  }
746
747  if (singleType === 'i8') {
748    if (slab.subarray || slab.slice) {
749      HEAPU8.set(slab, ret);
750    } else {
751      HEAPU8.set(new Uint8Array(slab), ret);
752    }
753    return ret;
754  }
755
756  var i = 0, type, typeSize, previousType;
757  while (i < size) {
758    var curr = slab[i];
759
760    if (typeof curr === 'function') {
761      curr = Runtime.getFunctionIndex(curr);
762    }
763
764    type = singleType || types[i];
765    if (type === 0) {
766      i++;
767      continue;
768    }
769
770    if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
771
772    setValue(ret+i, curr, type);
773
774    // no need to look up size unless type changes, so cache it
775    if (previousType !== type) {
776      typeSize = Runtime.getNativeTypeSize(type);
777      previousType = type;
778    }
779    i += typeSize;
780  }
781
782  return ret;
783}
784Module['allocate'] = allocate;
785
786function Pointer_stringify(ptr, /* optional */ length) {
787  // TODO: use TextDecoder
788  // Find the length, and check for UTF while doing so
789  var hasUtf = false;
790  var t;
791  var i = 0;
792  while (1) {
793    t = HEAPU8[(((ptr)+(i))|0)];
794    if (t >= 128) hasUtf = true;
795    else if (t == 0 && !length) break;
796    i++;
797    if (length && i == length) break;
798  }
799  if (!length) length = i;
800
801  var ret = '';
802
803  if (!hasUtf) {
804    var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
805    var curr;
806    while (length > 0) {
807      curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
808      ret = ret ? ret + curr : curr;
809      ptr += MAX_CHUNK;
810      length -= MAX_CHUNK;
811    }
812    return ret;
813  }
814
815  var utf8 = new Runtime.UTF8Processor();
816  for (i = 0; i < length; i++) {
817    t = HEAPU8[(((ptr)+(i))|0)];
818    ret += utf8.processCChar(t);
819  }
820  return ret;
821}
822Module['Pointer_stringify'] = Pointer_stringify;
823
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.
826function UTF16ToString(ptr) {
827  var i = 0;
828
829  var str = '';
830  while (1) {
831    var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
832    if (codeUnit == 0)
833      return str;
834    ++i;
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);
837  }
838}
839Module['UTF16ToString'] = UTF16ToString;
840
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.
843function 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;
848  }
849  // Null-terminate the pointer to the HEAP.
850  HEAP16[(((outPtr)+(str.length*2))>>1)]=0;
851}
852Module['stringToUTF16'] = stringToUTF16;
853
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.
856function UTF32ToString(ptr) {
857  var i = 0;
858
859  var str = '';
860  while (1) {
861    var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
862    if (utf32 == 0)
863      return str;
864    ++i;
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));
869    } else {
870      str += String.fromCharCode(utf32);
871    }
872  }
873}
874Module['UTF32ToString'] = UTF32ToString;
875
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.
879function stringToUTF32(str, outPtr) {
880  var iChar = 0;
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);
887    }
888    HEAP32[(((outPtr)+(iChar*4))>>2)]=codeUnit;
889    ++iChar;
890  }
891  // Null-terminate the pointer to the HEAP.
892  HEAP32[(((outPtr)+(iChar*4))>>2)]=0;
893}
894Module['stringToUTF32'] = stringToUTF32;
895
896function demangle(func) {
897  var i = 3;
898  // params, etc.
899  var basicTypes = {
900    'v': 'void',
901    'b': 'bool',
902    'c': 'char',
903    's': 'short',
904    'i': 'int',
905    'l': 'long',
906    'f': 'float',
907    'd': 'double',
908    'w': 'wchar_t',
909    'a': 'signed char',
910    'h': 'unsigned char',
911    't': 'unsigned short',
912    'j': 'unsigned int',
913    'm': 'unsigned long',
914    'x': 'long long',
915    'y': 'unsigned long long',
916    'z': '...'
917  };
918  var subs = [];
919  var first = true;
920  function dump(x) {
921    //return;
922    if (x) Module.print(x);
923    Module.print(func);
924    var pre = '';
925    for (var a = 0; a < i; a++) pre += ' ';
926    Module.print (pre + '^');
927  }
928  function parseNested() {
929    i++;
930    if (func[i] === 'K') i++; // ignore const
931    var parts = [];
932    while (func[i] !== 'E') {
933      if (func[i] === 'S') { // substitution
934        i++;
935        var next = func.indexOf('_', i);
936        var num = func.substring(i, next) || 0;
937        parts.push(subs[num] || '?');
938        i = next+1;
939        continue;
940      }
941      if (func[i] === 'C') { // constructor
942        parts.push(parts[parts.length-1]);
943        i += 2;
944        continue;
945      }
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);
950      parts.push(curr);
951      subs.push(curr);
952      i += pre + size;
953    }
954    i++; // skip E
955    return parts;
956  }
957  function parse(rawList, limit, allowVoid) { // main parser
958    limit = limit || Infinity;
959    var ret = '', list = [];
960    function flushList() {
961      return '(' + list.join(', ') + ')';
962    }
963    var name;
964    if (func[i] === 'N') {
965      // namespaced N-E
966      name = parseNested().join('::');
967      limit--;
968      if (limit === 0) return rawList ? [name] : name;
969    } else {
970      // not namespaced
971      if (func[i] === 'K' || (first && func[i] === 'L')) i++; // ignore const and first 'L'
972      var size = parseInt(func.substr(i));
973      if (size) {
974        var pre = size.toString().length;
975        name = func.substr(i + pre, size);
976        i += pre + size;
977      }
978    }
979    first = false;
980    if (func[i] === 'I') {
981      i++;
982      var iList = parse(true);
983      var iRet = parse(true, 1, true);
984      ret += iRet[0] + ' ' + name + '<' + iList.join(', ') + '>';
985    } else {
986      ret = name;
987    }
988    paramLoop: while (i < func.length && limit-- > 0) {
989      //dump('paramLoop');
990      var c = func[i++];
991      if (c in basicTypes) {
992        list.push(basicTypes[c]);
993      } else {
994        switch (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);
1000            var size = end - i;
1001            list.push(func.substr(i, size));
1002            i += size + 2; // size + 'EE'
1003            break;
1004          }
1005          case 'A': { // array
1006            var size = parseInt(func.substr(i));
1007            i += size.toString().length;
1008            if (func[i] !== '_') throw '?';
1009            i++; // skip _
1010            list.push(parse(true, 1, true)[0] + ' [' + size + ']');
1011            break;
1012          }
1013          case 'E': break paramLoop;
1014          default: ret += '?' + c; break paramLoop;
1015        }
1016      }
1017    }
1018    if (!allowVoid && list.length === 1 && list[0] === 'void') list = []; // avoid (void)
1019    if (rawList) {
1020      if (ret) {
1021        list.push(ret + '?');
1022      }
1023      return list;
1024    } else {
1025      return ret + flushList();
1026    }
1027  }
1028  try {
1029    // Special-case the entry point, since its name differs from other name mangling.
1030    if (func == 'Object._main' || func == '_main') {
1031      return 'main()';
1032    }
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;
1037    switch (func[3]) {
1038      case 'n': return 'operator new()';
1039      case 'd': return 'operator delete()';
1040    }
1041    return parse();
1042  } catch(e) {
1043    return func;
1044  }
1045}
1046
1047function demangleAll(text) {
1048  return text.replace(/__Z[\w\d_]+/g, function(x) { var y = demangle(x); return x === y ? x : (x + ' [' + y + ']') });
1049}
1050
1051function 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.
1054}
1055
1056// Memory management
1057
1058var PAGE_SIZE = 4096;
1059function alignMemoryPage(x) {
1060  return (x+4095)&-4096;
1061}
1062
1063var HEAP;
1064var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
1065
1066var STATIC_BASE = 0, STATICTOP = 0, staticSealed = false; // static area
1067var STACK_BASE = 0, STACKTOP = 0, STACK_MAX = 0; // stack area
1068var DYNAMIC_BASE = 0, DYNAMICTOP = 0; // dynamic area handled by sbrk
1069
1070function 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.');
1072}
1073
1074var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
1075var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 134217728;
1076var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
1077
1078var totalMemory = 4096;
1079while (totalMemory < TOTAL_MEMORY || totalMemory < 2*TOTAL_STACK) {
1080  if (totalMemory < 16*1024*1024) {
1081    totalMemory *= 2;
1082  } else {
1083    totalMemory += 16*1024*1024
1084  }
1085}
1086if (totalMemory !== TOTAL_MEMORY) {
1087  Module.printErr('increasing TOTAL_MEMORY to ' + totalMemory + ' to be more reasonable');
1088  TOTAL_MEMORY = totalMemory;
1089}
1090
1091// Initialize the runtime's memory
1092// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1093assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
1094       'JS engine does not provide full typed array support');
1095
1096var buffer = new ArrayBuffer(TOTAL_MEMORY);
1097HEAP8 = new Int8Array(buffer);
1098HEAP16 = new Int16Array(buffer);
1099HEAP32 = new Int32Array(buffer);
1100HEAPU8 = new Uint8Array(buffer);
1101HEAPU16 = new Uint16Array(buffer);
1102HEAPU32 = new Uint32Array(buffer);
1103HEAPF32 = new Float32Array(buffer);
1104HEAPF64 = new Float64Array(buffer);
1105
1106// Endianness check (note: assumes compiler arch was little-endian)
1107HEAP32[0] = 255;
1108assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a little-endian system');
1109
1110Module['HEAP'] = HEAP;
1111Module['HEAP8'] = HEAP8;
1112Module['HEAP16'] = HEAP16;
1113Module['HEAP32'] = HEAP32;
1114Module['HEAPU8'] = HEAPU8;
1115Module['HEAPU16'] = HEAPU16;
1116Module['HEAPU32'] = HEAPU32;
1117Module['HEAPF32'] = HEAPF32;
1118Module['HEAPF64'] = HEAPF64;
1119
1120function callRuntimeCallbacks(callbacks) {
1121  while(callbacks.length > 0) {
1122    var callback = callbacks.shift();
1123    if (typeof callback == 'function') {
1124      callback();
1125      continue;
1126    }
1127    var func = callback.func;
1128    if (typeof func === 'number') {
1129      if (callback.arg === undefined) {
1130        Runtime.dynCall('v', func);
1131      } else {
1132        Runtime.dynCall('vi', func, [callback.arg]);
1133      }
1134    } else {
1135      func(callback.arg === undefined ? null : callback.arg);
1136    }
1137  }
1138}
1139
1140var __ATPRERUN__  = []; // functions called before the runtime is initialized
1141var __ATINIT__    = []; // functions called during startup
1142var __ATMAIN__    = []; // functions called when main() is to be run
1143var __ATEXIT__    = []; // functions called during shutdown
1144var __ATPOSTRUN__ = []; // functions called after the runtime has exited
1145
1146var runtimeInitialized = false;
1147
1148function preRun() {
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());
1154    }
1155  }
1156  callRuntimeCallbacks(__ATPRERUN__);
1157}
1158
1159function ensureInitRuntime() {
1160  if (runtimeInitialized) return;
1161  runtimeInitialized = true;
1162  callRuntimeCallbacks(__ATINIT__);
1163}
1164
1165function preMain() {
1166  callRuntimeCallbacks(__ATMAIN__);
1167}
1168
1169function exitRuntime() {
1170  callRuntimeCallbacks(__ATEXIT__);
1171}
1172
1173function 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());
1179    }
1180  }
1181  callRuntimeCallbacks(__ATPOSTRUN__);
1182}
1183
1184function addOnPreRun(cb) {
1185  __ATPRERUN__.unshift(cb);
1186}
1187Module['addOnPreRun'] = Module.addOnPreRun = addOnPreRun;
1188
1189function addOnInit(cb) {
1190  __ATINIT__.unshift(cb);
1191}
1192Module['addOnInit'] = Module.addOnInit = addOnInit;
1193
1194function addOnPreMain(cb) {
1195  __ATMAIN__.unshift(cb);
1196}
1197Module['addOnPreMain'] = Module.addOnPreMain = addOnPreMain;
1198
1199function addOnExit(cb) {
1200  __ATEXIT__.unshift(cb);
1201}
1202Module['addOnExit'] = Module.addOnExit = addOnExit;
1203
1204function addOnPostRun(cb) {
1205  __ATPOSTRUN__.unshift(cb);
1206}
1207Module['addOnPostRun'] = Module.addOnPostRun = addOnPostRun;
1208
1209// Tools
1210
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
1213function intArrayFromString(stringy, dontAddNull, length /* optional */) {
1214  var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
1215  if (length) {
1216    ret.length = length;
1217  }
1218  if (!dontAddNull) {
1219    ret.push(0);
1220  }
1221  return ret;
1222}
1223Module['intArrayFromString'] = intArrayFromString;
1224
1225function intArrayToString(array) {
1226  var ret = [];
1227  for (var i = 0; i < array.length; i++) {
1228    var chr = array[i];
1229    if (chr > 0xFF) {
1230      chr &= 0xFF;
1231    }
1232    ret.push(String.fromCharCode(chr));
1233  }
1234  return ret.join('');
1235}
1236Module['intArrayToString'] = intArrayToString;
1237
1238// Write a Javascript array to somewhere in the heap
1239function writeStringToMemory(string, buffer, dontAddNull) {
1240  var array = intArrayFromString(string, dontAddNull);
1241  var i = 0;
1242  while (i < array.length) {
1243    var chr = array[i];
1244    HEAP8[(((buffer)+(i))|0)]=chr;
1245    i = i + 1;
1246  }
1247}
1248Module['writeStringToMemory'] = writeStringToMemory;
1249
1250function writeArrayToMemory(array, buffer) {
1251  for (var i = 0; i < array.length; i++) {
1252    HEAP8[(((buffer)+(i))|0)]=array[i];
1253  }
1254}
1255Module['writeArrayToMemory'] = writeArrayToMemory;
1256
1257function writeAsciiToMemory(str, buffer, dontAddNull) {
1258  for (var i = 0; i < str.length; i++) {
1259    HEAP8[(((buffer)+(i))|0)]=str.charCodeAt(i);
1260  }
1261  if (!dontAddNull) HEAP8[(((buffer)+(str.length))|0)]=0;
1262}
1263Module['writeAsciiToMemory'] = writeAsciiToMemory;
1264
1265function unSign(value, bits, ignore) {
1266  if (value >= 0) {
1267    return value;
1268  }
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;
1271}
1272function reSign(value, bits, ignore) {
1273  if (value <= 0) {
1274    return value;
1275  }
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
1282  }
1283  return value;
1284}
1285
1286// check for imul support, and also for correctness ( https://bugs.webkit.org/show_bug.cgi?id=126345 )
1287if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
1288  var ah  = a >>> 16;
1289  var al = a & 0xffff;
1290  var bh  = b >>> 16;
1291  var bl = b & 0xffff;
1292  return (al*bl + ((ah*bl + al*bh) << 16))|0;
1293};
1294Math.imul = Math['imul'];
1295
1296
1297var Math_abs = Math.abs;
1298var Math_cos = Math.cos;
1299var Math_sin = Math.sin;
1300var Math_tan = Math.tan;
1301var Math_acos = Math.acos;
1302var Math_asin = Math.asin;
1303var Math_atan = Math.atan;
1304var Math_atan2 = Math.atan2;
1305var Math_exp = Math.exp;
1306var Math_log = Math.log;
1307var Math_sqrt = Math.sqrt;
1308var Math_ceil = Math.ceil;
1309var Math_floor = Math.floor;
1310var Math_pow = Math.pow;
1311var Math_imul = Math.imul;
1312var Math_fround = Math.fround;
1313var Math_min = Math.min;
1314
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.
1322var runDependencies = 0;
1323var runDependencyWatcher = null;
1324var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1325
1326function addRunDependency(id) {
1327  runDependencies++;
1328  if (Module['monitorRunDependencies']) {
1329    Module['monitorRunDependencies'](runDependencies);
1330  }
1331}
1332Module['addRunDependency'] = addRunDependency;
1333function removeRunDependency(id) {
1334  runDependencies--;
1335  if (Module['monitorRunDependencies']) {
1336    Module['monitorRunDependencies'](runDependencies);
1337  }
1338  if (runDependencies == 0) {
1339    if (runDependencyWatcher !== null) {
1340      clearInterval(runDependencyWatcher);
1341      runDependencyWatcher = null;
1342    }
1343    if (dependenciesFulfilled) {
1344      var callback = dependenciesFulfilled;
1345      dependenciesFulfilled = null;
1346      callback(); // can add another dependenciesFulfilled
1347    }
1348  }
1349}
1350Module['removeRunDependency'] = removeRunDependency;
1351
1352Module["preloadedImages"] = {}; // maps url to image data
1353Module["preloadedAudios"] = {}; // maps url to audio data
1354
1355
1356var memoryInitializer = null;
1357
1358// === Body ===
1359
1360
1361
1362
1363
1364STATIC_BASE = 8;
1365
1366STATICTOP = STATIC_BASE + Runtime.alignMemory(35);
1367/* global initializers */ __ATINIT__.push();
1368
1369
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);
1371
1372
1373
1374
1375var tempDoublePtr = Runtime.alignMemory(allocate(12, "i8", ALLOC_STATIC), 8);
1376
1377assert(tempDoublePtr % 8 == 0);
1378
1379function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1380
1381  HEAP8[tempDoublePtr] = HEAP8[ptr];
1382
1383  HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1384
1385  HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1386
1387  HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1388
1389}
1390
1391function copyTempDouble(ptr) {
1392
1393  HEAP8[tempDoublePtr] = HEAP8[ptr];
1394
1395  HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1396
1397  HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1398
1399  HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1400
1401  HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1402
1403  HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1404
1405  HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1406
1407  HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1408
1409}
1410
1411
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
1416       * not an issue.
1417       */
1418      var ptr = Runtime.dynamicAlloc(bytes + 8);
1419      return (ptr+8) & 0xFFFFFFF8;
1420    }
1421  Module["_malloc"] = _malloc;
1422
1423
1424
1425
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};
1427
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"};
1429
1430
1431  var ___errno_state=0;function ___setErrNo(value) {
1432      // For convenient setting and returning of errno.
1433      HEAP32[((___errno_state)>>2)]=value;
1434      return value;
1435    }
1436
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');
1445        // }
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']();
1455        // }
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];
1461          if (!tty) {
1462            throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1463          }
1464          stream.tty = tty;
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);
1470          }
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);
1474          }
1475          var bytesRead = 0;
1476          for (var i = 0; i < length; i++) {
1477            var result;
1478            try {
1479              result = stream.tty.ops.get_char(stream.tty);
1480            } catch (e) {
1481              throw new FS.ErrnoError(ERRNO_CODES.EIO);
1482            }
1483            if (result === undefined && bytesRead === 0) {
1484              throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
1485            }
1486            if (result === null || result === undefined) break;
1487            bytesRead++;
1488            buffer[offset+i] = result;
1489          }
1490          if (bytesRead) {
1491            stream.node.timestamp = Date.now();
1492          }
1493          return bytesRead;
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);
1497          }
1498          for (var i = 0; i < length; i++) {
1499            try {
1500              stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
1501            } catch (e) {
1502              throw new FS.ErrnoError(ERRNO_CODES.EIO);
1503            }
1504          }
1505          if (length) {
1506            stream.node.timestamp = Date.now();
1507          }
1508          return i;
1509        }},default_tty_ops:{get_char:function (tty) {
1510          if (!tty.input.length) {
1511            var result = null;
1512            if (ENVIRONMENT_IS_NODE) {
1513              result = process['stdin']['read']();
1514              if (!result) {
1515                if (process['stdin']['_readableState'] && process['stdin']['_readableState']['ended']) {
1516                  return null;  // EOF
1517                }
1518                return undefined;  // no data available
1519              }
1520            } else if (typeof window != 'undefined' &&
1521              typeof window.prompt == 'function') {
1522              // Browser.
1523              result = window.prompt('Input: ');  // returns null on cancel
1524              if (result !== null) {
1525                result += '\n';
1526              }
1527            } else if (typeof readline == 'function') {
1528              // Command line.
1529              result = readline();
1530              if (result !== null) {
1531                result += '\n';
1532              }
1533            }
1534            if (!result) {
1535              return null;
1536            }
1537            tty.input = intArrayFromString(result, true);
1538          }
1539          return tty.input.shift();
1540        },put_char:function (tty, val) {
1541          if (val === null || val === 10) {
1542            Module['print'](tty.output.join(''));
1543            tty.output = [];
1544          } else {
1545            tty.output.push(TTY.utf8.processCChar(val));
1546          }
1547        }},default_tty1_ops:{put_char:function (tty, val) {
1548          if (val === null || val === 10) {
1549            Module['printErr'](tty.output.join(''));
1550            tty.output = [];
1551          } else {
1552            tty.output.push(TTY.utf8.processCChar(val));
1553          }
1554        }}};
1555
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)) {
1560          // no supported
1561          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
1562        }
1563        if (!MEMFS.ops_table) {
1564          MEMFS.ops_table = {
1565            dir: {
1566              node: {
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
1576              },
1577              stream: {
1578                llseek: MEMFS.stream_ops.llseek
1579              }
1580            },
1581            file: {
1582              node: {
1583                getattr: MEMFS.node_ops.getattr,
1584                setattr: MEMFS.node_ops.setattr
1585              },
1586              stream: {
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
1592              }
1593            },
1594            link: {
1595              node: {
1596                getattr: MEMFS.node_ops.getattr,
1597                setattr: MEMFS.node_ops.setattr,
1598                readlink: MEMFS.node_ops.readlink
1599              },
1600              stream: {}
1601            },
1602            chrdev: {
1603              node: {
1604                getattr: MEMFS.node_ops.getattr,
1605                setattr: MEMFS.node_ops.setattr
1606              },
1607              stream: FS.chrdev_stream_ops
1608            },
1609          };
1610        }
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;
1615          node.contents = {};
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;
1619          node.contents = [];
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;
1627        }
1628        node.timestamp = Date.now();
1629        // add the new node to the parent
1630        if (parent) {
1631          parent.contents[name] = node;
1632        }
1633        return 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;
1639        }
1640      },node_ops:{getattr:function (node) {
1641          var attr = {};
1642          // device numbers reuse inode numbers.
1643          attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1644          attr.ino = node.id;
1645          attr.mode = node.mode;
1646          attr.nlink = 1;
1647          attr.uid = 0;
1648          attr.gid = 0;
1649          attr.rdev = node.rdev;
1650          if (FS.isDir(node.mode)) {
1651            attr.size = 4096;
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;
1656          } else {
1657            attr.size = 0;
1658          }
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);
1666          return attr;
1667        },setattr:function (node, attr) {
1668          if (attr.mode !== undefined) {
1669            node.mode = attr.mode;
1670          }
1671          if (attr.timestamp !== undefined) {
1672            node.timestamp = attr.timestamp;
1673          }
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);
1679          }
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)) {
1687            var new_node;
1688            try {
1689              new_node = FS.lookupNode(new_dir, new_name);
1690            } catch (e) {
1691            }
1692            if (new_node) {
1693              for (var i in new_node.contents) {
1694                throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1695              }
1696            }
1697          }
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);
1709          }
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)) {
1715              continue;
1716            }
1717            entries.push(key);
1718          }
1719          return entries;
1720        },symlink:function (parent, newname, oldpath) {
1721          var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
1722          node.link = oldpath;
1723          return node;
1724        },readlink:function (node) {
1725          if (!FS.isLink(node.mode)) {
1726            throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1727          }
1728          return node.link;
1729        }},stream_ops:{read:function (stream, buffer, offset, length, position) {
1730          var contents = stream.node.contents;
1731          if (position >= contents.length)
1732            return 0;
1733          var size = Math.min(contents.length - position, length);
1734          assert(size >= 0);
1735          if (size > 8 && contents.subarray) { // non-trivial, and typed array
1736            buffer.set(contents.subarray(position, position + size), offset);
1737          } else
1738          {
1739            for (var i = 0; i < size; i++) {
1740              buffer[offset + i] = contents[position + i];
1741            }
1742          }
1743          return size;
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;
1753            } else {
1754              node.contents = new Uint8Array(buffer.subarray(offset, offset+length));
1755              node.contentMode = MEMFS.CONTENT_FIXED;
1756            }
1757            return length;
1758          }
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];
1764          }
1765          return length;
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;
1773            }
1774          }
1775          if (position < 0) {
1776            throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1777          }
1778          stream.ungotten = [];
1779          stream.position = position;
1780          return 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);
1789          }
1790          var ptr;
1791          var allocated;
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).
1798            allocated = false;
1799            ptr = contents.byteOffset;
1800          } else {
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);
1805              } else {
1806                contents = Array.prototype.slice.call(contents, position, position + length);
1807              }
1808            }
1809            allocated = true;
1810            ptr = _malloc(length);
1811            if (!ptr) {
1812              throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
1813            }
1814            buffer.set(contents, ptr);
1815          }
1816          return { ptr: ptr, allocated: allocated };
1817        }}};
1818
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);
1827
1828          IDBFS.getRemoteSet(mount, function(err, remote) {
1829            if (err) return callback(err);
1830
1831            var src = populate ? remote : local;
1832            var dst = populate ? local : remote;
1833
1834            IDBFS.reconcile(src, dst, callback);
1835          });
1836        });
1837      },getDB:function (name, callback) {
1838        // check the cache first
1839        var db = IDBFS.dbs[name];
1840        if (db) {
1841          return callback(null, db);
1842        }
1843
1844        var req;
1845        try {
1846          req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
1847        } catch (e) {
1848          return callback(e);
1849        }
1850        req.onupgradeneeded = function(e) {
1851          var db = e.target.result;
1852          var transaction = e.target.transaction;
1853
1854          var fileStore;
1855
1856          if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
1857            fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
1858          } else {
1859            fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
1860          }
1861
1862          fileStore.createIndex('timestamp', 'timestamp', { unique: false });
1863        };
1864        req.onsuccess = function() {
1865          db = req.result;
1866
1867          // add to the cache
1868          IDBFS.dbs[name] = db;
1869          callback(null, db);
1870        };
1871        req.onerror = function() {
1872          callback(this.error);
1873        };
1874      },getLocalSet:function (mount, callback) {
1875        var entries = {};
1876
1877        function isRealDir(p) {
1878          return p !== '.' && p !== '..';
1879        };
1880        function toAbsolute(root) {
1881          return function(p) {
1882            return PATH.join2(root, p);
1883          }
1884        };
1885
1886        var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
1887
1888        while (check.length) {
1889          var path = check.pop();
1890          var stat;
1891
1892          try {
1893            stat = FS.stat(path);
1894          } catch (e) {
1895            return callback(e);
1896          }
1897
1898          if (FS.isDir(stat.mode)) {
1899            check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
1900          }
1901
1902          entries[path] = { timestamp: stat.mtime };
1903        }
1904
1905        return callback(null, { type: 'local', entries: entries });
1906      },getRemoteSet:function (mount, callback) {
1907        var entries = {};
1908
1909        IDBFS.getDB(mount.mountpoint, function(err, db) {
1910          if (err) return callback(err);
1911
1912          var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
1913          transaction.onerror = function() { callback(this.error); };
1914
1915          var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
1916          var index = store.index('timestamp');
1917
1918          index.openKeyCursor().onsuccess = function(event) {
1919            var cursor = event.target.result;
1920
1921            if (!cursor) {
1922              return callback(null, { type: 'remote', db: db, entries: entries });
1923            }
1924
1925            entries[cursor.primaryKey] = { timestamp: cursor.key };
1926
1927            cursor.continue();
1928          };
1929        });
1930      },loadLocalEntry:function (path, callback) {
1931        var stat, node;
1932
1933        try {
1934          var lookup = FS.lookupPath(path);
1935          node = lookup.node;
1936          stat = FS.stat(path);
1937        } catch (e) {
1938          return callback(e);
1939        }
1940
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 });
1945        } else {
1946          return callback(new Error('node type not supported'));
1947        }
1948      },storeLocalEntry:function (path, entry, callback) {
1949        try {
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 });
1954          } else {
1955            return callback(new Error('node type not supported'));
1956          }
1957
1958          FS.utime(path, entry.timestamp, entry.timestamp);
1959        } catch (e) {
1960          return callback(e);
1961        }
1962
1963        callback(null);
1964      },removeLocalEntry:function (path, callback) {
1965        try {
1966          var lookup = FS.lookupPath(path);
1967          var stat = FS.stat(path);
1968
1969          if (FS.isDir(stat.mode)) {
1970            FS.rmdir(path);
1971          } else if (FS.isFile(stat.mode)) {
1972            FS.unlink(path);
1973          }
1974        } catch (e) {
1975          return callback(e);
1976        }
1977
1978        callback(null);
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) {
1992        var total = 0;
1993
1994        var create = [];
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) {
1999            create.push(key);
2000            total++;
2001          }
2002        });
2003
2004        var remove = [];
2005        Object.keys(dst.entries).forEach(function (key) {
2006          var e = dst.entries[key];
2007          var e2 = src.entries[key];
2008          if (!e2) {
2009            remove.push(key);
2010            total++;
2011          }
2012        });
2013
2014        if (!total) {
2015          return callback(null);
2016        }
2017
2018        var errored = false;
2019        var completed = 0;
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);
2023
2024        function done(err) {
2025          if (err) {
2026            if (!done.errored) {
2027              done.errored = true;
2028              return callback(err);
2029            }
2030            return;
2031          }
2032          if (++completed >= total) {
2033            return callback(null);
2034          }
2035        };
2036
2037        transaction.onerror = function() { done(this.error); };
2038
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);
2046            });
2047          } else {
2048            IDBFS.loadLocalEntry(path, function (err, entry) {
2049              if (err) return done(err);
2050              IDBFS.storeRemoteEntry(store, path, entry, done);
2051            });
2052          }
2053        });
2054
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);
2060          } else {
2061            IDBFS.removeRemoteEntry(store, path, done);
2062          }
2063        });
2064      }};
2065
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);
2074        }
2075        var node = FS.createNode(parent, name, mode);
2076        node.node_ops = NODEFS.node_ops;
2077        node.stream_ops = NODEFS.stream_ops;
2078        return node;
2079      },getMode:function (path) {
2080        var stat;
2081        try {
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);
2087          }
2088        } catch (e) {
2089          if (!e.code) throw e;
2090          throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2091        }
2092        return stat.mode;
2093      },realPath:function (node) {
2094        var parts = [];
2095        while (node.parent !== node) {
2096          parts.push(node.name);
2097          node = node.parent;
2098        }
2099        parts.push(node.mount.opts.root);
2100        parts.reverse();
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];
2105        } else {
2106          return flags;
2107        }
2108      },node_ops:{getattr:function (node) {
2109          var path = NODEFS.realPath(node);
2110          var stat;
2111          try {
2112            stat = fs.lstatSync(path);
2113          } catch (e) {
2114            if (!e.code) throw e;
2115            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2116          }
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;
2121          }
2122          if (NODEFS.isWindows && !stat.blocks) {
2123            stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
2124          }
2125          return {
2126            dev: stat.dev,
2127            ino: stat.ino,
2128            mode: stat.mode,
2129            nlink: stat.nlink,
2130            uid: stat.uid,
2131            gid: stat.gid,
2132            rdev: stat.rdev,
2133            size: stat.size,
2134            atime: stat.atime,
2135            mtime: stat.mtime,
2136            ctime: stat.ctime,
2137            blksize: stat.blksize,
2138            blocks: stat.blocks
2139          };
2140        },setattr:function (node, attr) {
2141          var path = NODEFS.realPath(node);
2142          try {
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;
2147            }
2148            if (attr.timestamp !== undefined) {
2149              var date = new Date(attr.timestamp);
2150              fs.utimesSync(path, date, date);
2151            }
2152            if (attr.size !== undefined) {
2153              fs.truncateSync(path, attr.size);
2154            }
2155          } catch (e) {
2156            if (!e.code) throw e;
2157            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2158          }
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);
2167          try {
2168            if (FS.isDir(node.mode)) {
2169              fs.mkdirSync(path, node.mode);
2170            } else {
2171              fs.writeFileSync(path, '', { mode: node.mode });
2172            }
2173          } catch (e) {
2174            if (!e.code) throw e;
2175            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2176          }
2177          return node;
2178        },rename:function (oldNode, newDir, newName) {
2179          var oldPath = NODEFS.realPath(oldNode);
2180          var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
2181          try {
2182            fs.renameSync(oldPath, newPath);
2183          } catch (e) {
2184            if (!e.code) throw e;
2185            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2186          }
2187        },unlink:function (parent, name) {
2188          var path = PATH.join2(NODEFS.realPath(parent), name);
2189          try {
2190            fs.unlinkSync(path);
2191          } catch (e) {
2192            if (!e.code) throw e;
2193            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2194          }
2195        },rmdir:function (parent, name) {
2196          var path = PATH.join2(NODEFS.realPath(parent), name);
2197          try {
2198            fs.rmdirSync(path);
2199          } catch (e) {
2200            if (!e.code) throw e;
2201            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2202          }
2203        },readdir:function (node) {
2204          var path = NODEFS.realPath(node);
2205          try {
2206            return fs.readdirSync(path);
2207          } catch (e) {
2208            if (!e.code) throw e;
2209            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2210          }
2211        },symlink:function (parent, newName, oldPath) {
2212          var newPath = PATH.join2(NODEFS.realPath(parent), newName);
2213          try {
2214            fs.symlinkSync(oldPath, newPath);
2215          } catch (e) {
2216            if (!e.code) throw e;
2217            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2218          }
2219        },readlink:function (node) {
2220          var path = NODEFS.realPath(node);
2221          try {
2222            return fs.readlinkSync(path);
2223          } catch (e) {
2224            if (!e.code) throw e;
2225            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2226          }
2227        }},stream_ops:{open:function (stream) {
2228          var path = NODEFS.realPath(stream.node);
2229          try {
2230            if (FS.isFile(stream.node.mode)) {
2231              stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
2232            }
2233          } catch (e) {
2234            if (!e.code) throw e;
2235            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2236          }
2237        },close:function (stream) {
2238          try {
2239            if (FS.isFile(stream.node.mode) && stream.nfd) {
2240              fs.closeSync(stream.nfd);
2241            }
2242          } catch (e) {
2243            if (!e.code) throw e;
2244            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2245          }
2246        },read:function (stream, buffer, offset, length, position) {
2247          // FIXME this is terrible.
2248          var nbuffer = new Buffer(length);
2249          var res;
2250          try {
2251            res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
2252          } catch (e) {
2253            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2254          }
2255          if (res > 0) {
2256            for (var i = 0; i < res; i++) {
2257              buffer[offset + i] = nbuffer[i];
2258            }
2259          }
2260          return res;
2261        },write:function (stream, buffer, offset, length, position) {
2262          // FIXME this is terrible.
2263          var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
2264          var res;
2265          try {
2266            res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
2267          } catch (e) {
2268            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2269          }
2270          return res;
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)) {
2277              try {
2278                var stat = fs.fstatSync(stream.nfd);
2279                position += stat.size;
2280              } catch (e) {
2281                throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2282              }
2283            }
2284          }
2285
2286          if (position < 0) {
2287            throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2288          }
2289
2290          stream.position = position;
2291          return position;
2292        }}};
2293
2294  var _stdin=allocate(1, "i32*", ALLOC_STATIC);
2295
2296  var _stdout=allocate(1, "i32*", ALLOC_STATIC);
2297
2298  var _stderr=allocate(1, "i32*", ALLOC_STATIC);
2299
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);
2309        opts = opts || {};
2310
2311        var defaults = {
2312          follow_mount: true,
2313          recurse_count: 0
2314        };
2315        for (var key in defaults) {
2316          if (opts[key] === undefined) {
2317            opts[key] = defaults[key];
2318          }
2319        }
2320
2321        if (opts.recurse_count > 8) {  // max recursive lookup of 8
2322          throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2323        }
2324
2325        // split the path
2326        var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2327          return !!p;
2328        }), false);
2329
2330        // start at the root
2331        var current = FS.root;
2332        var current_path = '/';
2333
2334        for (var i = 0; i < parts.length; i++) {
2335          var islast = (i === parts.length-1);
2336          if (islast && opts.parent) {
2337            // stop resolving
2338            break;
2339          }
2340
2341          current = FS.lookupNode(current, parts[i]);
2342          current_path = PATH.join2(current_path, parts[i]);
2343
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;
2348            }
2349          }
2350
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) {
2354            var count = 0;
2355            while (FS.isLink(current.mode)) {
2356              var link = FS.readlink(current_path);
2357              current_path = PATH.resolve(PATH.dirname(current_path), link);
2358
2359              var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
2360              current = lookup.node;
2361
2362              if (count++ > 40) {  // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
2363                throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2364              }
2365            }
2366          }
2367        }
2368
2369        return { path: current_path, node: current };
2370      },getPath:function (node) {
2371        var path;
2372        while (true) {
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;
2377          }
2378          path = path ? node.name + '/' + path : node.name;
2379          node = node.parent;
2380        }
2381      },hashName:function (parentid, name) {
2382        var hash = 0;
2383
2384
2385        for (var i = 0; i < name.length; i++) {
2386          hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2387        }
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;
2397        } else {
2398          var current = FS.nameTable[hash];
2399          while (current) {
2400            if (current.name_next === node) {
2401              current.name_next = node.name_next;
2402              break;
2403            }
2404            current = current.name_next;
2405          }
2406        }
2407      },lookupNode:function (parent, name) {
2408        var err = FS.mayLookup(parent);
2409        if (err) {
2410          throw new FS.ErrnoError(err);
2411        }
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) {
2416            return node;
2417          }
2418        }
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) {
2422        if (!FS.FSNode) {
2423          FS.FSNode = function(parent, name, mode, rdev) {
2424            if (!parent) {
2425              parent = this;  // root node sets parent to itself
2426            }
2427            this.parent = parent;
2428            this.mount = parent.mount;
2429            this.mounted = null;
2430            this.id = FS.nextInode++;
2431            this.name = name;
2432            this.mode = mode;
2433            this.node_ops = {};
2434            this.stream_ops = {};
2435            this.rdev = rdev;
2436          };
2437
2438          FS.FSNode.prototype = {};
2439
2440          // compatibility
2441          var readMode = 292 | 73;
2442          var writeMode = 146;
2443
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, {
2447            read: {
2448              get: function() { return (this.mode & readMode) === readMode; },
2449              set: function(val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
2450            },
2451            write: {
2452              get: function() { return (this.mode & writeMode) === writeMode; },
2453              set: function(val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
2454            },
2455            isFolder: {
2456              get: function() { return FS.isDir(this.mode); },
2457            },
2458            isDevice: {
2459              get: function() { return FS.isChrdev(this.mode); },
2460            },
2461          });
2462        }
2463
2464        var node = new FS.FSNode(parent, name, mode, rdev);
2465
2466        FS.hashAddNode(node);
2467
2468        return 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);
2493        }
2494        return flags;
2495      },flagsToPermissionString:function (flag) {
2496        var accmode = flag & 2097155;
2497        var perms = ['r', 'w', 'rw'][accmode];
2498        if ((flag & 512)) {
2499          perms += 'w';
2500        }
2501        return perms;
2502      },nodePermissions:function (node, perms) {
2503        if (FS.ignorePermissions) {
2504          return 0;
2505        }
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;
2513        }
2514        return 0;
2515      },mayLookup:function (dir) {
2516        return FS.nodePermissions(dir, 'x');
2517      },mayCreate:function (dir, name) {
2518        try {
2519          var node = FS.lookupNode(dir, name);
2520          return ERRNO_CODES.EEXIST;
2521        } catch (e) {
2522        }
2523        return FS.nodePermissions(dir, 'wx');
2524      },mayDelete:function (dir, name, isdir) {
2525        var node;
2526        try {
2527          node = FS.lookupNode(dir, name);
2528        } catch (e) {
2529          return e.errno;
2530        }
2531        var err = FS.nodePermissions(dir, 'wx');
2532        if (err) {
2533          return err;
2534        }
2535        if (isdir) {
2536          if (!FS.isDir(node.mode)) {
2537            return ERRNO_CODES.ENOTDIR;
2538          }
2539          if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2540            return ERRNO_CODES.EBUSY;
2541          }
2542        } else {
2543          if (FS.isDir(node.mode)) {
2544            return ERRNO_CODES.EISDIR;
2545          }
2546        }
2547        return 0;
2548      },mayOpen:function (node, flags) {
2549        if (!node) {
2550          return ERRNO_CODES.ENOENT;
2551        }
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
2556              (flags & 512)) {
2557            return ERRNO_CODES.EISDIR;
2558          }
2559        }
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]) {
2566            return fd;
2567          }
2568        }
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) {
2573        if (!FS.FSStream) {
2574          FS.FSStream = function(){};
2575          FS.FSStream.prototype = {};
2576          // compatibility
2577          Object.defineProperties(FS.FSStream.prototype, {
2578            object: {
2579              get: function() { return this.node; },
2580              set: function(val) { this.node = val; }
2581            },
2582            isRead: {
2583              get: function() { return (this.flags & 2097155) !== 1; }
2584            },
2585            isWrite: {
2586              get: function() { return (this.flags & 2097155) !== 0; }
2587            },
2588            isAppend: {
2589              get: function() { return (this.flags & 1024); }
2590            }
2591          });
2592        }
2593        if (0) {
2594          // reuse the object
2595          stream.__proto__ = FS.FSStream.prototype;
2596        } else {
2597          var newStream = new FS.FSStream();
2598          for (var p in stream) {
2599            newStream[p] = stream[p];
2600          }
2601          stream = newStream;
2602        }
2603        var fd = FS.nextfd(fd_start, fd_end);
2604        stream.fd = fd;
2605        FS.streams[fd] = stream;
2606        return 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);
2620          }
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) {
2634        var mounts = [];
2635        var check = [mount];
2636
2637        while (check.length) {
2638          var m = check.pop();
2639
2640          mounts.push(m);
2641
2642          check.push.apply(check, m.mounts);
2643        }
2644
2645        return mounts;
2646      },syncfs:function (populate, callback) {
2647        if (typeof(populate) === 'function') {
2648          callback = populate;
2649          populate = false;
2650        }
2651
2652        var mounts = FS.getMounts(FS.root.mount);
2653        var completed = 0;
2654
2655        function done(err) {
2656          if (err) {
2657            if (!done.errored) {
2658              done.errored = true;
2659              return callback(err);
2660            }
2661            return;
2662          }
2663          if (++completed >= mounts.length) {
2664            callback(null);
2665          }
2666        };
2667
2668        // sync all mounts
2669        mounts.forEach(function (mount) {
2670          if (!mount.type.syncfs) {
2671            return done(null);
2672          }
2673          mount.type.syncfs(mount, populate, done);
2674        });
2675      },mount:function (type, opts, mountpoint) {
2676        var root = mountpoint === '/';
2677        var pseudo = !mountpoint;
2678        var node;
2679
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 });
2684
2685          mountpoint = lookup.path;  // use the absolute path
2686          node = lookup.node;
2687
2688          if (FS.isMountpoint(node)) {
2689            throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2690          }
2691
2692          if (!FS.isDir(node.mode)) {
2693            throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2694          }
2695        }
2696
2697        var mount = {
2698          type: type,
2699          opts: opts,
2700          mountpoint: mountpoint,
2701          mounts: []
2702        };
2703
2704        // create a root node for the fs
2705        var mountRoot = type.mount(mount);
2706        mountRoot.mount = mount;
2707        mount.root = mountRoot;
2708
2709        if (root) {
2710          FS.root = mountRoot;
2711        } else if (node) {
2712          // set as a mountpoint
2713          node.mounted = mount;
2714
2715          // add the new mount to the current mount's children
2716          if (node.mount) {
2717            node.mount.mounts.push(mount);
2718          }
2719        }
2720
2721        return mountRoot;
2722      },unmount:function (mountpoint) {
2723        var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2724
2725        if (!FS.isMountpoint(lookup.node)) {
2726          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2727        }
2728
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);
2733
2734        Object.keys(FS.nameTable).forEach(function (hash) {
2735          var current = FS.nameTable[hash];
2736
2737          while (current) {
2738            var next = current.name_next;
2739
2740            if (mounts.indexOf(current.mount) !== -1) {
2741              FS.destroyNode(current);
2742            }
2743
2744            current = next;
2745          }
2746        });
2747
2748        // no longer a mountpoint
2749        node.mounted = null;
2750
2751        // remove this mount from the child mounts
2752        var idx = node.mount.mounts.indexOf(mount);
2753        assert(idx !== -1);
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);
2762        if (err) {
2763          throw new FS.ErrnoError(err);
2764        }
2765        if (!parent.node_ops.mknod) {
2766          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2767        }
2768        return parent.node_ops.mknod(parent, name, mode, dev);
2769      },create:function (path, mode) {
2770        mode = mode !== undefined ? mode : 438 /* 0666 */;
2771        mode &= 4095;
2772        mode |= 32768;
2773        return FS.mknod(path, mode, 0);
2774      },mkdir:function (path, mode) {
2775        mode = mode !== undefined ? mode : 511 /* 0777 */;
2776        mode &= 511 | 512;
2777        mode |= 16384;
2778        return FS.mknod(path, mode, 0);
2779      },mkdev:function (path, mode, dev) {
2780        if (typeof(dev) === 'undefined') {
2781          dev = mode;
2782          mode = 438 /* 0666 */;
2783        }
2784        mode |= 8192;
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);
2791        if (err) {
2792          throw new FS.ErrnoError(err);
2793        }
2794        if (!parent.node_ops.symlink) {
2795          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2796        }
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;
2805        try {
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;
2810        } catch (e) {
2811          throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2812        }
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);
2816        }
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);
2823        }
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);
2828        }
2829        // see if the new path already exists
2830        var new_node;
2831        try {
2832          new_node = FS.lookupNode(new_dir, new_name);
2833        } catch (e) {
2834          // not fatal
2835        }
2836        // early out if nothing needs to change
2837        if (old_node === new_node) {
2838          return;
2839        }
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);
2843        if (err) {
2844          throw new FS.ErrnoError(err);
2845        }
2846        // need delete permissions if we'll be overwriting.
2847        // need create permissions if new doesn't already exist.
2848        err = new_node ?
2849          FS.mayDelete(new_dir, new_name, isdir) :
2850          FS.mayCreate(new_dir, new_name);
2851        if (err) {
2852          throw new FS.ErrnoError(err);
2853        }
2854        if (!old_dir.node_ops.rename) {
2855          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2856        }
2857        if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
2858          throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2859        }
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');
2863          if (err) {
2864            throw new FS.ErrnoError(err);
2865          }
2866        }
2867        // remove the node from the lookup hash
2868        FS.hashRemoveNode(old_node);
2869        // do the underlying fs rename
2870        try {
2871          old_dir.node_ops.rename(old_node, new_dir, new_name);
2872        } catch (e) {
2873          throw e;
2874        } finally {
2875          // add the node back to the hash (in case node_ops.rename
2876          // changed its name)
2877          FS.hashAddNode(old_node);
2878        }
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);
2885        if (err) {
2886          throw new FS.ErrnoError(err);
2887        }
2888        if (!parent.node_ops.rmdir) {
2889          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2890        }
2891        if (FS.isMountpoint(node)) {
2892          throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2893        }
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);
2901        }
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);
2909        if (err) {
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);
2913        }
2914        if (!parent.node_ops.unlink) {
2915          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2916        }
2917        if (FS.isMountpoint(node)) {
2918          throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2919        }
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);
2927        }
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);
2934        }
2935        return node.node_ops.getattr(node);
2936      },lstat:function (path) {
2937        return FS.stat(path, true);
2938      },chmod:function (path, mode, dontFollow) {
2939        var node;
2940        if (typeof path === 'string') {
2941          var lookup = FS.lookupPath(path, { follow: !dontFollow });
2942          node = lookup.node;
2943        } else {
2944          node = path;
2945        }
2946        if (!node.node_ops.setattr) {
2947          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2948        }
2949        node.node_ops.setattr(node, {
2950          mode: (mode & 4095) | (node.mode & ~4095),
2951          timestamp: Date.now()
2952        });
2953      },lchmod:function (path, mode) {
2954        FS.chmod(path, mode, true);
2955      },fchmod:function (fd, mode) {
2956        var stream = FS.getStream(fd);
2957        if (!stream) {
2958          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2959        }
2960        FS.chmod(stream.node, mode);
2961      },chown:function (path, uid, gid, dontFollow) {
2962        var node;
2963        if (typeof path === 'string') {
2964          var lookup = FS.lookupPath(path, { follow: !dontFollow });
2965          node = lookup.node;
2966        } else {
2967          node = path;
2968        }
2969        if (!node.node_ops.setattr) {
2970          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2971        }
2972        node.node_ops.setattr(node, {
2973          timestamp: Date.now()
2974          // we ignore the uid / gid for now
2975        });
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);
2980        if (!stream) {
2981          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2982        }
2983        FS.chown(stream.node, uid, gid);
2984      },truncate:function (path, len) {
2985        if (len < 0) {
2986          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2987        }
2988        var node;
2989        if (typeof path === 'string') {
2990          var lookup = FS.lookupPath(path, { follow: true });
2991          node = lookup.node;
2992        } else {
2993          node = path;
2994        }
2995        if (!node.node_ops.setattr) {
2996          throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2997        }
2998        if (FS.isDir(node.mode)) {
2999          throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3000        }
3001        if (!FS.isFile(node.mode)) {
3002          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3003        }
3004        var err = FS.nodePermissions(node, 'w');
3005        if (err) {
3006          throw new FS.ErrnoError(err);
3007        }
3008        node.node_ops.setattr(node, {
3009          size: len,
3010          timestamp: Date.now()
3011        });
3012      },ftruncate:function (fd, len) {
3013        var stream = FS.getStream(fd);
3014        if (!stream) {
3015          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3016        }
3017        if ((stream.flags & 2097155) === 0) {
3018          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3019        }
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)
3026        });
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;
3030        if ((flags & 64)) {
3031          mode = (mode & 4095) | 32768;
3032        } else {
3033          mode = 0;
3034        }
3035        var node;
3036        if (typeof path === 'object') {
3037          node = path;
3038        } else {
3039          path = PATH.normalize(path);
3040          try {
3041            var lookup = FS.lookupPath(path, {
3042              follow: !(flags & 131072)
3043            });
3044            node = lookup.node;
3045          } catch (e) {
3046            // ignore
3047          }
3048        }
3049        // perhaps we need to create the node
3050        if ((flags & 64)) {
3051          if (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);
3055            }
3056          } else {
3057            // node doesn't exist, try to create it
3058            node = FS.mknod(path, mode, 0);
3059          }
3060        }
3061        if (!node) {
3062          throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3063        }
3064        // can't truncate a device
3065        if (FS.isChrdev(node.mode)) {
3066          flags &= ~512;
3067        }
3068        // check permissions
3069        var err = FS.mayOpen(node, flags);
3070        if (err) {
3071          throw new FS.ErrnoError(err);
3072        }
3073        // do truncation if necessary
3074        if ((flags & 512)) {
3075          FS.truncate(node, 0);
3076        }
3077        // we've already handled these, don't pass down to the underlying vfs
3078        flags &= ~(128 | 512);
3079
3080        // register the stream with the filesystem
3081        var stream = FS.createStream({
3082          node: node,
3083          path: FS.getPath(node),  // we want the absolute path to the node
3084          flags: flags,
3085          seekable: true,
3086          position: 0,
3087          stream_ops: node.stream_ops,
3088          // used by the file family libc calls (fopen, fwrite, ferror, etc.)
3089          ungotten: [],
3090          error: false
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);
3095        }
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);
3101          }
3102        }
3103        return stream;
3104      },close:function (stream) {
3105        try {
3106          if (stream.stream_ops.close) {
3107            stream.stream_ops.close(stream);
3108          }
3109        } catch (e) {
3110          throw e;
3111        } finally {
3112          FS.closeStream(stream.fd);
3113        }
3114      },llseek:function (stream, offset, whence) {
3115        if (!stream.seekable || !stream.stream_ops.llseek) {
3116          throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3117        }
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);
3122        }
3123        if ((stream.flags & 2097155) === 1) {
3124          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3125        }
3126        if (FS.isDir(stream.node.mode)) {
3127          throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3128        }
3129        if (!stream.stream_ops.read) {
3130          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3131        }
3132        var seeking = true;
3133        if (typeof position === 'undefined') {
3134          position = stream.position;
3135          seeking = false;
3136        } else if (!stream.seekable) {
3137          throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3138        }
3139        var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
3140        if (!seeking) stream.position += bytesRead;
3141        return bytesRead;
3142      },write:function (stream, buffer, offset, length, position, canOwn) {
3143        if (length < 0 || position < 0) {
3144          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3145        }
3146        if ((stream.flags & 2097155) === 0) {
3147          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3148        }
3149        if (FS.isDir(stream.node.mode)) {
3150          throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3151        }
3152        if (!stream.stream_ops.write) {
3153          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3154        }
3155        var seeking = true;
3156        if (typeof position === 'undefined') {
3157          position = stream.position;
3158          seeking = false;
3159        } else if (!stream.seekable) {
3160          throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3161        }
3162        if (stream.flags & 1024) {
3163          // seek to the end before writing in append mode
3164          FS.llseek(stream, 0, 2);
3165        }
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);
3172        }
3173        if ((stream.flags & 2097155) === 0) {
3174          throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3175        }
3176        if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
3177          throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3178        }
3179        if (!stream.stream_ops.allocate) {
3180          throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
3181        }
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);
3187        }
3188        if (!stream.stream_ops.mmap) {
3189          throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3190        }
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);
3195        }
3196        return stream.stream_ops.ioctl(stream, cmd, arg);
3197      },readFile:function (path, opts) {
3198        opts = 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 + '"');
3203        }
3204        var ret;
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') {
3211          ret = '';
3212          var utf8 = new Runtime.UTF8Processor();
3213          for (var i = 0; i < length; i++) {
3214            ret += utf8.processCChar(buf[i]);
3215          }
3216        } else if (opts.encoding === 'binary') {
3217          ret = buf;
3218        }
3219        FS.close(stream);
3220        return ret;
3221      },writeFile:function (path, data, opts) {
3222        opts = 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 + '"');
3227        }
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);
3235        }
3236        FS.close(stream);
3237      },cwd:function () {
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);
3243        }
3244        var err = FS.nodePermissions(lookup.node, 'x');
3245        if (err) {
3246          throw new FS.ErrnoError(err);
3247        }
3248        FS.currentPath = lookup.path;
3249      },createDefaultDirectories:function () {
3250        FS.mkdir('/tmp');
3251      },createDefaultDevices:function () {
3252        // create /dev
3253        FS.mkdir('/dev');
3254        // setup /dev/null
3255        FS.registerDevice(FS.makedev(1, 3), {
3256          read: function() { return 0; },
3257          write: function() { return 0; }
3258        });
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
3275
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
3279        // them instead.
3280        if (Module['stdin']) {
3281          FS.createDevice('/dev', 'stdin', Module['stdin']);
3282        } else {
3283          FS.symlink('/dev/tty', '/dev/stdin');
3284        }
3285        if (Module['stdout']) {
3286          FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3287        } else {
3288          FS.symlink('/dev/tty', '/dev/stdout');
3289        }
3290        if (Module['stderr']) {
3291          FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3292        } else {
3293          FS.symlink('/dev/tty1', '/dev/stderr');
3294        }
3295
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 + ')');
3300
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 + ')');
3304
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) {
3311          this.errno = errno;
3312          for (var key in ERRNO_CODES) {
3313            if (ERRNO_CODES[key] === errno) {
3314              this.code = key;
3315              break;
3316            }
3317          }
3318          this.message = ERRNO_MESSAGES[errno];
3319        };
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>';
3326        });
3327      },staticInit:function () {
3328        FS.ensureErrnoError();
3329
3330        FS.nameTable = new Array(4096);
3331
3332        FS.mount(MEMFS, {}, '/');
3333
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;
3339
3340        FS.ensureErrnoError();
3341
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'];
3346
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];
3352          if (!stream) {
3353            continue;
3354          }
3355          FS.close(stream);
3356        }
3357      },getMode:function (canRead, canWrite) {
3358        var mode = 0;
3359        if (canRead) mode |= 292 | 73;
3360        if (canWrite) mode |= 146;
3361        return mode;
3362      },joinPath:function (parts, forceRelative) {
3363        var path = PATH.join.apply(null, parts);
3364        if (forceRelative && path[0] == '/') path = path.substr(1);
3365        return path;
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);
3372        if (ret.exists) {
3373          return ret.object;
3374        } else {
3375          ___setErrNo(ret.error);
3376          return null;
3377        }
3378      },analyzePath:function (path, dontResolveLastLink) {
3379        // operate from within the context of the symlink's target
3380        try {
3381          var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3382          path = lookup.path;
3383        } catch (e) {
3384        }
3385        var ret = {
3386          isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
3387          parentExists: false, parentPath: null, parentObject: null
3388        };
3389        try {
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 });
3396          ret.exists = true;
3397          ret.path = lookup.path;
3398          ret.object = lookup.node;
3399          ret.name = lookup.node.name;
3400          ret.isRoot = lookup.path === '/';
3401        } catch (e) {
3402          ret.error = e.errno;
3403        };
3404        return ret;
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);
3416          try {
3417            FS.mkdir(current);
3418          } catch (e) {
3419            // ignore EEXIST
3420          }
3421          parent = current;
3422        }
3423        return current;
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);
3432        if (data) {
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);
3436            data = arr;
3437          }
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);
3442          FS.close(stream);
3443          FS.chmod(node, mode);
3444        }
3445        return node;
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;
3456          },
3457          close: function(stream) {
3458            // flush any pending line data
3459            if (output && output.buffer && output.buffer.length) {
3460              output(10);
3461            }
3462          },
3463          read: function(stream, buffer, offset, length, pos /* ignored */) {
3464            var bytesRead = 0;
3465            for (var i = 0; i < length; i++) {
3466              var result;
3467              try {
3468                result = input();
3469              } catch (e) {
3470                throw new FS.ErrnoError(ERRNO_CODES.EIO);
3471              }
3472              if (result === undefined && bytesRead === 0) {
3473                throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
3474              }
3475              if (result === null || result === undefined) break;
3476              bytesRead++;
3477              buffer[offset+i] = result;
3478            }
3479            if (bytesRead) {
3480              stream.node.timestamp = Date.now();
3481            }
3482            return bytesRead;
3483          },
3484          write: function(stream, buffer, offset, length, pos) {
3485            for (var i = 0; i < length; i++) {
3486              try {
3487                output(buffer[offset+i]);
3488              } catch (e) {
3489                throw new FS.ErrnoError(ERRNO_CODES.EIO);
3490              }
3491            }
3492            if (length) {
3493              stream.node.timestamp = Date.now();
3494            }
3495            return i;
3496          }
3497        });
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;
3504        var success = 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']) {
3508          // Command-line.
3509          try {
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);
3513          } catch (e) {
3514            success = false;
3515          }
3516        } else {
3517          throw new Error('Cannot load without read() or XMLHttpRequest.');
3518        }
3519        if (!success) ___setErrNo(ERRNO_CODES.EIO);
3520        return success;
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
3526        }
3527        LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
3528          if (idx > this.length-1 || idx < 0) {
3529            return undefined;
3530          }
3531          var chunkOffset = idx % this.chunkSize;
3532          var chunkNum = Math.floor(idx / this.chunkSize);
3533          return this.getter(chunkNum)[chunkOffset];
3534        }
3535        LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
3536          this.getter = getter;
3537        }
3538        LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
3539            // Find length
3540            var xhr = new XMLHttpRequest();
3541            xhr.open('HEAD', url, false);
3542            xhr.send(null);
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"));
3545            var header;
3546            var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
3547            var chunkSize = 1024*1024; // Chunk size in bytes
3548
3549            if (!hasByteServing) chunkSize = datalength;
3550
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!");
3555
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);
3560
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');
3565              }
3566
3567              xhr.send(null);
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 || []);
3571              } else {
3572                return intArrayFromString(xhr.responseText || '', true);
3573              }
3574            });
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);
3582              }
3583              if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3584              return lazyArray.chunks[chunkNum];
3585            });
3586
3587            this._length = datalength;
3588            this._chunkSize = chunkSize;
3589            this.lengthKnown = true;
3590        }
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", {
3595              get: function() {
3596                  if(!this.lengthKnown) {
3597                      this.cacheLength();
3598                  }
3599                  return this._length;
3600              }
3601          });
3602          Object.defineProperty(lazyArray, "chunkSize", {
3603              get: function() {
3604                  if(!this.lengthKnown) {
3605                      this.cacheLength();
3606                  }
3607                  return this._chunkSize;
3608              }
3609          });
3610
3611          var properties = { isDevice: false, contents: lazyArray };
3612        } else {
3613          var properties = { isDevice: false, url: url };
3614        }
3615
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;
3625        }
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);
3634            }
3635            return fn.apply(null, arguments);
3636          };
3637        });
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);
3642          }
3643          var contents = stream.node.contents;
3644          if (position >= contents.length)
3645            return 0;
3646          var size = Math.min(contents.length - position, length);
3647          assert(size >= 0);
3648          if (contents.slice) { // normal array
3649            for (var i = 0; i < size; i++) {
3650              buffer[offset + i] = contents[position + i];
3651            }
3652          } else {
3653            for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
3654              buffer[offset + i] = contents.get(position + i);
3655            }
3656          }
3657          return size;
3658        };
3659        node.stream_ops = stream_ops;
3660        return node;
3661      },createPreloadedFile:function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn) {
3662        Browser.init();
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);
3670            }
3671            if (onload) onload();
3672            removeRunDependency('cp ' + fullname);
3673          }
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);
3681              });
3682              handled = true;
3683            }
3684          });
3685          if (!handled) finish(byteArray);
3686        }
3687        addRunDependency('cp ' + fullname);
3688        if (typeof url == 'string') {
3689          Browser.asyncLoad(url, function(byteArray) {
3690            processData(byteArray);
3691          }, onerror);
3692        } else {
3693          processData(url);
3694        }
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();
3703        try {
3704          var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3705        } catch (e) {
3706          return onerror(e);
3707        }
3708        openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
3709          console.log('creating db');
3710          var db = openRequest.result;
3711          db.createObjectStore(FS.DB_STORE_NAME);
3712        };
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;
3718          function finish() {
3719            if (fail == 0) onload(); else onerror();
3720          }
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() };
3725          });
3726          transaction.onerror = onerror;
3727        };
3728        openRequest.onerror = onerror;
3729      },loadFilesFromDB:function (paths, onload, onerror) {
3730        onload = onload || function(){};
3731        onerror = onerror || function(){};
3732        var indexedDB = FS.indexedDB();
3733        try {
3734          var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3735        } catch (e) {
3736          return onerror(e);
3737        }
3738        openRequest.onupgradeneeded = onerror; // no database to load from
3739        openRequest.onsuccess = function openRequest_onsuccess() {
3740          var db = openRequest.result;
3741          try {
3742            var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
3743          } catch(e) {
3744            onerror(e);
3745            return;
3746          }
3747          var files = transaction.objectStore(FS.DB_STORE_NAME);
3748          var ok = 0, fail = 0, total = paths.length;
3749          function finish() {
3750            if (fail == 0) onload(); else onerror();
3751          }
3752          paths.forEach(function(path) {
3753            var getRequest = files.get(path);
3754            getRequest.onsuccess = function getRequest_onsuccess() {
3755              if (FS.analyzePath(path).exists) {
3756                FS.unlink(path);
3757              }
3758              FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
3759              ok++;
3760              if (ok + fail == total) finish();
3761            };
3762            getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
3763          });
3764          transaction.onerror = onerror;
3765        };
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
3772        var up = 0;
3773        for (var i = parts.length - 1; i >= 0; i--) {
3774          var last = parts[i];
3775          if (last === '.') {
3776            parts.splice(i, 1);
3777          } else if (last === '..') {
3778            parts.splice(i, 1);
3779            up++;
3780          } else if (up) {
3781            parts.splice(i, 1);
3782            up--;
3783          }
3784        }
3785        // if the path is allowed to go above the root, restore leading ..s
3786        if (allowAboveRoot) {
3787          for (; up--; up) {
3788            parts.unshift('..');
3789          }
3790        }
3791        return parts;
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) {
3797          return !!p;
3798        }), !isAbsolute).join('/');
3799        if (!path && !isAbsolute) {
3800          path = '.';
3801        }
3802        if (path && trailingSlash) {
3803          path += '/';
3804        }
3805        return (isAbsolute ? '/' : '') + path;
3806      },dirname:function (path) {
3807        var result = PATH.splitPath(path),
3808            root = result[0],
3809            dir = result[1];
3810        if (!root && !dir) {
3811          // No dirname whatsoever
3812          return '.';
3813        }
3814        if (dir) {
3815          // It has a dirname, strip trailing slash
3816          dir = dir.substr(0, dir.length - 1);
3817        }
3818        return root + dir;
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');
3840          } else if (!path) {
3841            continue;
3842          }
3843          resolvedPath = path + '/' + resolvedPath;
3844          resolvedAbsolute = path.charAt(0) === '/';
3845        }
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) {
3849          return !!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) {
3856          var start = 0;
3857          for (; start < arr.length; start++) {
3858            if (arr[start] !== '') break;
3859          }
3860          var end = arr.length - 1;
3861          for (; end >= 0; end--) {
3862            if (arr[end] !== '') break;
3863          }
3864          if (start > end) return [];
3865          return arr.slice(start, end - start + 1);
3866        }
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;
3874            break;
3875          }
3876        }
3877        var outputParts = [];
3878        for (var i = samePartsLength; i < fromParts.length; i++) {
3879          outputParts.push('..');
3880        }
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();
3889          }
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;
3896            if (remaining) {
3897              if (remaining < expected) {
3898                Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
3899              } else {
3900                Module['setStatus'](message);
3901              }
3902            } else {
3903              Module['setStatus']('');
3904            }
3905          }
3906        }},isFullScreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function () {
3907        if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
3908
3909        if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
3910        Browser.initted = true;
3911
3912        try {
3913          new Blob();
3914          Browser.hasBlobConstructor = true;
3915        } catch(e) {
3916          Browser.hasBlobConstructor = false;
3917          console.log("warning: no blob constructor, cannot create blobs with mimetypes");
3918        }
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;
3924        }
3925
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.
3928        //
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.).
3933
3934        var imagePlugin = {};
3935        imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
3936          return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
3937        };
3938        imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
3939          var b = null;
3940          if (Browser.hasBlobConstructor) {
3941            try {
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) });
3946              }
3947            } catch(e) {
3948              Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
3949            }
3950          }
3951          if (!b) {
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
3954            b = bb.getBlob();
3955          }
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);
3968          };
3969          img.onerror = function img_onerror(event) {
3970            console.log('Image ' + url + ' could not be decoded');
3971            if (onerror) onerror();
3972          };
3973          img.src = url;
3974        };
3975        Module['preloadPlugins'].push(imagePlugin);
3976
3977        var audioPlugin = {};
3978        audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
3979          return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
3980        };
3981        audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
3982          var done = false;
3983          function finish(audio) {
3984            if (done) return;
3985            done = true;
3986            Module["preloadedAudios"][name] = audio;
3987            if (onload) onload(byteArray);
3988          }
3989          function fail() {
3990            if (done) return;
3991            done = true;
3992            Module["preloadedAudios"][name] = new Audio(); // empty shim
3993            if (onerror) onerror();
3994          }
3995          if (Browser.hasBlobConstructor) {
3996            try {
3997              var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
3998            } catch(e) {
3999              return fail();
4000            }
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) {
4005              if (done) return;
4006              console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
4007              function encode64(data) {
4008                var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4009                var PAD = '=';
4010                var ret = '';
4011                var leftchar = 0;
4012                var leftbits = 0;
4013                for (var i = 0; i < data.length; i++) {
4014                  leftchar = (leftchar << 8) | data[i];
4015                  leftbits += 8;
4016                  while (leftbits >= 6) {
4017                    var curr = (leftchar >> (leftbits-6)) & 0x3f;
4018                    leftbits -= 6;
4019                    ret += BASE[curr];
4020                  }
4021                }
4022                if (leftbits == 2) {
4023                  ret += BASE[(leftchar&3) << 4];
4024                  ret += PAD + PAD;
4025                } else if (leftbits == 4) {
4026                  ret += BASE[(leftchar&0xf) << 2];
4027                  ret += PAD;
4028                }
4029                return ret;
4030              }
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
4033            };
4034            audio.src = url;
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
4038            }, 10000);
4039          } else {
4040            return fail();
4041          }
4042        };
4043        Module['preloadPlugins'].push(audioPlugin);
4044
4045        // Canvas event setup
4046
4047        var canvas = Module['canvas'];
4048
4049        // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
4050        // Module['forcedAspectRatio'] = 4 / 3;
4051
4052        canvas.requestPointerLock = canvas['requestPointerLock'] ||
4053                                    canvas['mozRequestPointerLock'] ||
4054                                    canvas['webkitRequestPointerLock'] ||
4055                                    canvas['msRequestPointerLock'] ||
4056                                    function(){};
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);
4063
4064        function pointerLockChange() {
4065          Browser.pointerLock = document['pointerLockElement'] === canvas ||
4066                                document['mozPointerLockElement'] === canvas ||
4067                                document['webkitPointerLockElement'] === canvas ||
4068                                document['msPointerLockElement'] === canvas;
4069        }
4070
4071        document.addEventListener('pointerlockchange', pointerLockChange, false);
4072        document.addEventListener('mozpointerlockchange', pointerLockChange, false);
4073        document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
4074        document.addEventListener('mspointerlockchange', pointerLockChange, false);
4075
4076        if (Module['elementPointerLock']) {
4077          canvas.addEventListener("click", function(ev) {
4078            if (!Browser.pointerLock && canvas.requestPointerLock) {
4079              canvas.requestPointerLock();
4080              ev.preventDefault();
4081            }
4082          }, false);
4083        }
4084      },createContext:function (canvas, useWebGL, setInModule, webGLContextAttributes) {
4085        var ctx;
4086        var errorInfo = '?';
4087        function onContextCreationError(event) {
4088          errorInfo = event.statusMessage || errorInfo;
4089        }
4090        try {
4091          if (useWebGL) {
4092            var contextAttributes = {
4093              antialias: false,
4094              alpha: false
4095            };
4096
4097            if (webGLContextAttributes) {
4098              for (var attribute in webGLContextAttributes) {
4099                contextAttributes[attribute] = webGLContextAttributes[attribute];
4100              }
4101            }
4102
4103
4104            canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
4105            try {
4106              ['experimental-webgl', 'webgl'].some(function(webglId) {
4107                return ctx = canvas.getContext(webglId, contextAttributes);
4108              });
4109            } finally {
4110              canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
4111            }
4112          } else {
4113            ctx = canvas.getContext('2d');
4114          }
4115          if (!ctx) throw ':(';
4116        } catch (e) {
4117          Module.print('Could not create canvas: ' + [errorInfo, e]);
4118          return null;
4119        }
4120        if (useWebGL) {
4121          // Set the background of the WebGL canvas to black
4122          canvas.style.backgroundColor = "black";
4123
4124          // Warn on context loss
4125          canvas.addEventListener('webglcontextlost', function(event) {
4126            alert('WebGL context lost. You will need to reload the page.');
4127          }, false);
4128        }
4129        if (setInModule) {
4130          GLctx = Module.ctx = ctx;
4131          Module.useWebGL = useWebGL;
4132          Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
4133          Browser.init();
4134        }
4135        return ctx;
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;
4141
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'] ||
4156                                      function() {};
4157            canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
4158            if (Browser.lockPointer) canvas.requestPointerLock();
4159            Browser.isFullScreen = true;
4160            if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
4161          } else {
4162
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);
4166
4167            if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
4168          }
4169          if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScreen);
4170          Browser.updateCanvasDimensions(canvas);
4171        }
4172
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);
4179        }
4180
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);
4185
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);
4195        } else {
4196          if (!window.requestAnimationFrame) {
4197            window.requestAnimationFrame = window['requestAnimationFrame'] ||
4198                                           window['mozRequestAnimationFrame'] ||
4199                                           window['webkitRequestAnimationFrame'] ||
4200                                           window['msRequestAnimationFrame'] ||
4201                                           window['oRequestAnimationFrame'] ||
4202                                           window['setTimeout'];
4203          }
4204          window.requestAnimationFrame(func);
4205        }
4206      },safeCallback:function (func) {
4207        return function() {
4208          if (!ABORT) return func.apply(null, arguments);
4209        };
4210      },safeRequestAnimationFrame:function (func) {
4211        return Browser.requestAnimationFrame(function() {
4212          if (!ABORT) func();
4213        });
4214      },safeSetTimeout:function (func, timeout) {
4215        return setTimeout(function() {
4216          if (!ABORT) func();
4217        }, timeout);
4218      },safeSetInterval:function (func, timeout) {
4219        return setInterval(function() {
4220          if (!ABORT) func();
4221        }, timeout);
4222      },getMimetype:function (name) {
4223        return {
4224          'jpg': 'image/jpeg',
4225          'jpeg': 'image/jpeg',
4226          'png': 'image/png',
4227          'bmp': 'image/bmp',
4228          'ogg': 'audio/ogg',
4229          'wav': 'audio/wav',
4230          'mp3': 'audio/mpeg'
4231        }[name.substr(name.lastIndexOf('.')+1)];
4232      },getUserMedia:function (func) {
4233        if(!window.getUserMedia) {
4234          window.getUserMedia = navigator['getUserMedia'] ||
4235                                navigator['mozGetUserMedia'];
4236        }
4237        window.getUserMedia(func);
4238      },getMovementX:function (event) {
4239        return event['movementX'] ||
4240               event['mozMovementX'] ||
4241               event['webkitMovementX'] ||
4242               0;
4243      },getMovementY:function (event) {
4244        return event['movementY'] ||
4245               event['mozMovementY'] ||
4246               event['webkitMovementY'] ||
4247               0;
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;
4258          } else {
4259            Browser.mouseMovementX = Browser.getMovementX(event);
4260            Browser.mouseMovementY = Browser.getMovementY(event);
4261          }
4262
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;
4267          } else {
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;
4272          }
4273        } else {
4274          // Otherwise, calculate the movement based on the changes
4275          // in the coordinates.
4276          var rect = Module["canvas"].getBoundingClientRect();
4277          var x, y;
4278
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);
4288            if (t) {
4289              x = t.pageX - (scrollX + rect.left);
4290              y = t.pageY - (scrollY + rect.top);
4291            } else {
4292              return;
4293            }
4294          } else {
4295            x = event.pageX - (scrollX + rect.left);
4296            y = event.pageY - (scrollY + rect.top);
4297          }
4298
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);
4306
4307          Browser.mouseMovementX = x - Browser.mouseX;
4308          Browser.mouseMovementY = y - Browser.mouseY;
4309          Browser.mouseX = x;
4310          Browser.mouseY = y;
4311        }
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);
4319          } else {
4320            onerror();
4321          }
4322        };
4323        xhr.onerror = onerror;
4324        xhr.send(null);
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) {
4331          if (onerror) {
4332            onerror();
4333          } else {
4334            throw 'Loading data file "' + url + '" failed.';
4335          }
4336        });
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);
4342        });
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
4353        }
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
4361        }
4362        Browser.updateResizeListeners();
4363      },updateCanvasDimensions:function (canvas, wNative, hNative) {
4364        if (wNative && hNative) {
4365          canvas.widthNative = wNative;
4366          canvas.heightNative = hNative;
4367        } else {
4368          wNative = canvas.widthNative;
4369          hNative = canvas.heightNative;
4370        }
4371        var w = wNative;
4372        var h = hNative;
4373        if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
4374          if (w/h < Module['forcedAspectRatio']) {
4375            w = Math.round(h * Module['forcedAspectRatio']);
4376          } else {
4377            h = Math.round(w / Module['forcedAspectRatio']);
4378          }
4379        }
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);
4388        }
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");
4395          }
4396        } else {
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");
4403            } else {
4404              canvas.style.removeProperty( "width");
4405              canvas.style.removeProperty("height");
4406            }
4407          }
4408        }
4409      }};
4410
4411
4412
4413
4414
4415
4416
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;
4421        if (protocol) {
4422          assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
4423        }
4424
4425        // create our internal socket structure
4426        var sock = {
4427          family: family,
4428          type: type,
4429          protocol: protocol,
4430          server: null,
4431          peers: {},
4432          pending: [],
4433          recv_queue: [],
4434          sock_ops: SOCKFS.websocket_sock_ops
4435        };
4436
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);
4440        node.sock = sock;
4441
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({
4445          path: name,
4446          node: node,
4447          flags: FS.modeStringToFlags('r+'),
4448          seekable: false,
4449          stream_ops: SOCKFS.stream_ops
4450        });
4451
4452        // map the new stream to the socket structure (sockets have a 1:1
4453        // relationship with a stream)
4454        sock.stream = stream;
4455
4456        return sock;
4457      },getSocket:function (fd) {
4458        var stream = FS.getStream(fd);
4459        if (!stream || !FS.isSocket(stream.node.mode)) {
4460          return null;
4461        }
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);
4472          if (!msg) {
4473            // socket is closed
4474            return 0;
4475          }
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;
4487        }
4488        return 'socket[' + (SOCKFS.nextname.current++) + ']';
4489      },websocket_sock_ops:{createPeer:function (sock, addr, port) {
4490          var ws;
4491
4492          if (typeof addr === 'object') {
4493            ws = addr;
4494            addr = null;
4495            port = null;
4496          }
4497
4498          if (ws) {
4499            // for sockets that've already connected (e.g. we're the server)
4500            // we can inspect the _socket property for the address
4501            if (ws._socket) {
4502              addr = ws._socket.remoteAddress;
4503              port = ws._socket.remotePort;
4504            }
4505            // if we're just now initializing a connection to the remote,
4506            // inspect the url property
4507            else {
4508              var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
4509              if (!result) {
4510                throw new Error('WebSocket URL must be in the format ws(s)://address:port');
4511              }
4512              addr = result[1];
4513              port = parseInt(result[2], 10);
4514            }
4515          } else {
4516            // create the actual websocket object and connect
4517            try {
4518              // runtimeConfig gets set to true if WebSocket runtime configuration is available.
4519              var runtimeConfig = (Module['websocket'] && ('object' === typeof Module['websocket']));
4520
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('#', '//');
4524
4525              if (runtimeConfig) {
4526                if ('string' === typeof Module['websocket']['url']) {
4527                  url = Module['websocket']['url']; // Fetch runtime WebSocket URL config.
4528                }
4529              }
4530
4531              if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
4532                url = url + addr + ':' + port;
4533              }
4534
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'
4537
4538              if (runtimeConfig) {
4539                if ('string' === typeof Module['websocket']['subprotocol']) {
4540                  subProtocols = Module['websocket']['subprotocol']; // Fetch runtime WebSocket subprotocol config.
4541                }
4542              }
4543
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(/ *, */);
4547
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;
4550
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';
4555            } catch (e) {
4556              throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
4557            }
4558          }
4559
4560
4561          var peer = {
4562            addr: addr,
4563            port: port,
4564            socket: ws,
4565            dgram_send_queue: []
4566          };
4567
4568          SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4569          SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
4570
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
4573          // remote end.
4574          if (sock.type === 2 && typeof sock.sport !== 'undefined') {
4575            peer.dgram_send_queue.push(new Uint8Array([
4576                255, 255, 255, 255,
4577                'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0),
4578                ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
4579            ]));
4580          }
4581
4582          return peer;
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) {
4590          var first = true;
4591
4592          var handleOpen = function () {
4593            try {
4594              var queued = peer.dgram_send_queue.shift();
4595              while (queued) {
4596                peer.socket.send(queued);
4597                queued = peer.dgram_send_queue.shift();
4598              }
4599            } catch (e) {
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();
4603            }
4604          };
4605
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
4609
4610
4611            // if this is the port message, override the peer's port with it
4612            var wasfirst = first;
4613            first = false;
4614            if (wasfirst &&
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);
4623              return;
4624            }
4625
4626            sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
4627          };
4628
4629          if (ENVIRONMENT_IS_NODE) {
4630            peer.socket.on('open', handleOpen);
4631            peer.socket.on('message', function(data, flags) {
4632              if (!flags.binary) {
4633                return;
4634              }
4635              handleMessage((new Uint8Array(data)).buffer);  // copy from node Buffer -> ArrayBuffer
4636            });
4637            peer.socket.on('error', function() {
4638              // don't throw
4639            });
4640          } else {
4641            peer.socket.onopen = handleOpen;
4642            peer.socket.onmessage = function peer_socket_onmessage(event) {
4643              handleMessage(event.data);
4644            };
4645          }
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;
4651          }
4652
4653          var mask = 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) :
4656            null;
4657
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
4662            mask |= (64 | 1);
4663          }
4664
4665          if (!dest ||  // connection-less sockets are always ready to write
4666              (dest && dest.socket.readyState === dest.socket.OPEN)) {
4667            mask |= 4;
4668          }
4669
4670          if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
4671              (dest && dest.socket.readyState === dest.socket.CLOSED)) {
4672            mask |= 16;
4673          }
4674
4675          return mask;
4676        },ioctl:function (sock, request, arg) {
4677          switch (request) {
4678            case 21531:
4679              var bytes = 0;
4680              if (sock.recv_queue.length) {
4681                bytes = sock.recv_queue[0].data.length;
4682              }
4683              HEAP32[((arg)>>2)]=bytes;
4684              return 0;
4685            default:
4686              return ERRNO_CODES.EINVAL;
4687          }
4688        },close:function (sock) {
4689          // if we've spawned a listen server, close it
4690          if (sock.server) {
4691            try {
4692              sock.server.close();
4693            } catch (e) {
4694            }
4695            sock.server = null;
4696          }
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]];
4701            try {
4702              peer.socket.close();
4703            } catch (e) {
4704            }
4705            SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4706          }
4707          return 0;
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
4711          }
4712          sock.saddr = addr;
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
4719            if (sock.server) {
4720              sock.server.close();
4721              sock.server = null;
4722            }
4723            // swallow error operation not supported error that occurs when binding in the
4724            // browser where this isn't supported
4725            try {
4726              sock.sock_ops.listen(sock, 0);
4727            } catch (e) {
4728              if (!(e instanceof FS.ErrnoError)) throw e;
4729              if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
4730            }
4731          }
4732        },connect:function (sock, addr, port) {
4733          if (sock.server) {
4734            throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
4735          }
4736
4737          // TODO autobind
4738          // if (!sock.addr && sock.type == 2) {
4739          // }
4740
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);
4744            if (dest) {
4745              if (dest.socket.readyState === dest.socket.CONNECTING) {
4746                throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
4747              } else {
4748                throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
4749              }
4750            }
4751          }
4752
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;
4758
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);
4764          }
4765          if (sock.server) {
4766             throw new FS.ErrnoError(ERRNO_CODES.EINVAL);  // already listening
4767          }
4768          var WebSocketServer = require('ws').Server;
4769          var host = sock.saddr;
4770          sock.server = new WebSocketServer({
4771            host: host,
4772            port: sock.sport
4773            // TODO support backlog
4774          });
4775
4776          sock.server.on('connection', function(ws) {
4777            if (sock.type === 1) {
4778              var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
4779
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;
4784
4785              // push to queue for accept to pick up
4786              sock.pending.push(newsock);
4787            } else {
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);
4792            }
4793          });
4794          sock.server.on('closed', function() {
4795            sock.server = null;
4796          });
4797          sock.server.on('error', function() {
4798            // don't throw
4799          });
4800        },accept:function (listensock) {
4801          if (!listensock.server) {
4802            throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4803          }
4804          var newsock = listensock.pending.shift();
4805          newsock.stream.flags = listensock.stream.flags;
4806          return newsock;
4807        },getname:function (sock, peer) {
4808          var addr, port;
4809          if (peer) {
4810            if (sock.daddr === undefined || sock.dport === undefined) {
4811              throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4812            }
4813            addr = sock.daddr;
4814            port = sock.dport;
4815          } else {
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;
4820          }
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) {
4827              addr = sock.daddr;
4828              port = sock.dport;
4829            }
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);
4833            }
4834          } else {
4835            // connection-based sockets will only use the bound
4836            addr = sock.daddr;
4837            port = sock.dport;
4838          }
4839
4840          // find the peer for the destination address
4841          var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
4842
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);
4849            }
4850          }
4851
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
4855          var data;
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);
4860          }
4861
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);
4870              }
4871              dest.dgram_send_queue.push(data);
4872              return length;
4873            }
4874          }
4875
4876          try {
4877            // send the actual data
4878            dest.socket.send(data);
4879            return length;
4880          } catch (e) {
4881            throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4882          }
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);
4888          }
4889
4890          var queued = sock.recv_queue.shift();
4891          if (!queued) {
4892            if (sock.type === 1) {
4893              var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
4894
4895              if (!dest) {
4896                // if we have a destination address but are not connected, error out
4897                throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4898              }
4899              else if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4900                // return null if the socket has closed
4901                return null;
4902              }
4903              else {
4904                // else, our socket is in a valid state but truly has nothing available
4905                throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4906              }
4907            } else {
4908              throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4909            }
4910          }
4911
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);
4918          var res = {
4919            buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
4920            addr: queued.addr,
4921            port: queued.port
4922          };
4923
4924
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);
4930          }
4931
4932          return res;
4933        }}};function _send(fd, buf, len, flags) {
4934      var sock = SOCKFS.getSocket(fd);
4935      if (!sock) {
4936        ___setErrNo(ERRNO_CODES.EBADF);
4937        return -1;
4938      }
4939      // TODO honor flags
4940      return _write(fd, buf, len);
4941    }
4942
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);
4947      if (!stream) {
4948        ___setErrNo(ERRNO_CODES.EBADF);
4949        return -1;
4950      }
4951      try {
4952        var slab = HEAP8;
4953        return FS.write(stream, slab, buf, nbyte, offset);
4954      } catch (e) {
4955        FS.handleFSError(e);
4956        return -1;
4957      }
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);
4962      if (!stream) {
4963        ___setErrNo(ERRNO_CODES.EBADF);
4964        return -1;
4965      }
4966
4967
4968      try {
4969        var slab = HEAP8;
4970        return FS.write(stream, slab, buf, nbyte);
4971      } catch (e) {
4972        FS.handleFSError(e);
4973        return -1;
4974      }
4975    }
4976
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;
4982      return stream.fd;
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;
4993        return 0;
4994      } else {
4995        return Math.floor(bytesWritten / size);
4996      }
4997    }
4998
4999
5000
5001  Module["_strlen"] = _strlen;
5002
5003  function __reallyNegative(x) {
5004      return x < 0 || (x === 0 && (1/x) === -Infinity);
5005    }function __formatString(format, varargs) {
5006      var textIndex = format;
5007      var argIndex = 0;
5008      function getNextArg(type) {
5009        // NOTE: Explicitly ignoring type safety. Otherwise this fails:
5010        //       int x = 4; printf("%c\n", (char)x);
5011        var ret;
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)]];
5017
5018        } else {
5019          type = 'i32'; // varargs are always i32, i64, or double
5020          ret = HEAP32[(((varargs)+(argIndex))>>2)];
5021        }
5022        argIndex += Runtime.getNativeFieldSize(type);
5023        return ret;
5024      }
5025
5026      var ret = [];
5027      var curr, next, currArg;
5028      while(1) {
5029        var startTextIndex = textIndex;
5030        curr = HEAP8[(textIndex)];
5031        if (curr === 0) break;
5032        next = HEAP8[((textIndex+1)|0)];
5033        if (curr == 37) {
5034          // Handle flags.
5035          var flagAlwaysSigned = false;
5036          var flagLeftAlign = false;
5037          var flagAlternative = false;
5038          var flagZeroPad = false;
5039          var flagPadSign = false;
5040          flagsLoop: while (1) {
5041            switch (next) {
5042              case 43:
5043                flagAlwaysSigned = true;
5044                break;
5045              case 45:
5046                flagLeftAlign = true;
5047                break;
5048              case 35:
5049                flagAlternative = true;
5050                break;
5051              case 48:
5052                if (flagZeroPad) {
5053                  break flagsLoop;
5054                } else {
5055                  flagZeroPad = true;
5056                  break;
5057                }
5058              case 32:
5059                flagPadSign = true;
5060                break;
5061              default:
5062                break flagsLoop;
5063            }
5064            textIndex++;
5065            next = HEAP8[((textIndex+1)|0)];
5066          }
5067
5068          // Handle width.
5069          var width = 0;
5070          if (next == 42) {
5071            width = getNextArg('i32');
5072            textIndex++;
5073            next = HEAP8[((textIndex+1)|0)];
5074          } else {
5075            while (next >= 48 && next <= 57) {
5076              width = width * 10 + (next - 48);
5077              textIndex++;
5078              next = HEAP8[((textIndex+1)|0)];
5079            }
5080          }
5081
5082          // Handle precision.
5083          var precisionSet = false, precision = -1;
5084          if (next == 46) {
5085            precision = 0;
5086            precisionSet = true;
5087            textIndex++;
5088            next = HEAP8[((textIndex+1)|0)];
5089            if (next == 42) {
5090              precision = getNextArg('i32');
5091              textIndex++;
5092            } else {
5093              while(1) {
5094                var precisionChr = HEAP8[((textIndex+1)|0)];
5095                if (precisionChr < 48 ||
5096                    precisionChr > 57) break;
5097                precision = precision * 10 + (precisionChr - 48);
5098                textIndex++;
5099              }
5100            }
5101            next = HEAP8[((textIndex+1)|0)];
5102          }
5103          if (precision < 0) {
5104            precision = 6; // Standard default.
5105            precisionSet = false;
5106          }
5107
5108          // Handle integer sizes. WARNING: These assume a 32-bit architecture!
5109          var argSize;
5110          switch (String.fromCharCode(next)) {
5111            case 'h':
5112              var nextNext = HEAP8[((textIndex+2)|0)];
5113              if (nextNext == 104) {
5114                textIndex++;
5115                argSize = 1; // char (actually i32 in varargs)
5116              } else {
5117                argSize = 2; // short (actually i32 in varargs)
5118              }
5119              break;
5120            case 'l':
5121              var nextNext = HEAP8[((textIndex+2)|0)];
5122              if (nextNext == 108) {
5123                textIndex++;
5124                argSize = 8; // long long
5125              } else {
5126                argSize = 4; // long
5127              }
5128              break;
5129            case 'L': // long long
5130            case 'q': // int64_t
5131            case 'j': // intmax_t
5132              argSize = 8;
5133              break;
5134            case 'z': // size_t
5135            case 't': // ptrdiff_t
5136            case 'I': // signed ptrdiff_t or unsigned size_t
5137              argSize = 4;
5138              break;
5139            default:
5140              argSize = null;
5141          }
5142          if (argSize) textIndex++;
5143          next = HEAP8[((textIndex+1)|0)];
5144
5145          // Handle type specifier.
5146          switch (String.fromCharCode(next)) {
5147            case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': {
5148              // Integer.
5149              var signed = next == 100 || next == 105;
5150              argSize = argSize || 4;
5151              var currArg = getNextArg('i' + (argSize * 8));
5152              var argText;
5153              // Flatten i64-1 [low, high] into a (slightly rounded) double
5154              if (argSize == 8) {
5155                currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117);
5156              }
5157              // Truncate to requested size.
5158              if (argSize <= 4) {
5159                var limit = Math.pow(256, argSize) - 1;
5160                currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
5161              }
5162              // Format the number.
5163              var currAbsArg = Math.abs(currArg);
5164              var prefix = '';
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' : '';
5174                if (currArg < 0) {
5175                  // Represent negative numbers in hex as 2's complement.
5176                  currArg = -currArg;
5177                  argText = (currAbsArg - 1).toString(16);
5178                  var buffer = [];
5179                  for (var i = 0; i < argText.length; i++) {
5180                    buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
5181                  }
5182                  argText = buffer.join('');
5183                  while (argText.length < argSize * 2) argText = 'f' + argText;
5184                } else {
5185                  argText = currAbsArg.toString(16);
5186                }
5187                if (next == 88) {
5188                  prefix = prefix.toUpperCase();
5189                  argText = argText.toUpperCase();
5190                }
5191              } else if (next == 112) {
5192                if (currAbsArg === 0) {
5193                  argText = '(nil)';
5194                } else {
5195                  prefix = '0x';
5196                  argText = currAbsArg.toString(16);
5197                }
5198              }
5199              if (precisionSet) {
5200                while (argText.length < precision) {
5201                  argText = '0' + argText;
5202                }
5203              }
5204
5205              // Add sign if needed
5206              if (currArg >= 0) {
5207                if (flagAlwaysSigned) {
5208                  prefix = '+' + prefix;
5209                } else if (flagPadSign) {
5210                  prefix = ' ' + prefix;
5211                }
5212              }
5213
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);
5218              }
5219
5220              // Add padding.
5221              while (prefix.length + argText.length < width) {
5222                if (flagLeftAlign) {
5223                  argText += ' ';
5224                } else {
5225                  if (flagZeroPad) {
5226                    argText = '0' + argText;
5227                  } else {
5228                    prefix = ' ' + prefix;
5229                  }
5230                }
5231              }
5232
5233              // Insert the result into the buffer.
5234              argText = prefix + argText;
5235              argText.split('').forEach(function(chr) {
5236                ret.push(chr.charCodeAt(0));
5237              });
5238              break;
5239            }
5240            case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': {
5241              // Float.
5242              var currArg = getNextArg('double');
5243              var argText;
5244              if (isNaN(currArg)) {
5245                argText = 'nan';
5246                flagZeroPad = false;
5247              } else if (!isFinite(currArg)) {
5248                argText = (currArg < 0 ? '-' : '') + 'inf';
5249                flagZeroPad = false;
5250              } else {
5251                var isGeneral = false;
5252                var effectivePrecision = Math.min(precision, 20);
5253
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) {
5257                  isGeneral = true;
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;
5263                  } else {
5264                    next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
5265                    precision--;
5266                  }
5267                  effectivePrecision = Math.min(precision, 20);
5268                }
5269
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);
5275                  }
5276                } else if (next == 102 || next == 70) {
5277                  argText = currArg.toFixed(effectivePrecision);
5278                  if (currArg === 0 && __reallyNegative(currArg)) {
5279                    argText = '-' + argText;
5280                  }
5281                }
5282
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);
5289                  }
5290                } else {
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';
5295                }
5296                argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
5297
5298                // Capitalize 'E' if needed.
5299                if (next == 69) argText = argText.toUpperCase();
5300
5301                // Add sign.
5302                if (currArg >= 0) {
5303                  if (flagAlwaysSigned) {
5304                    argText = '+' + argText;
5305                  } else if (flagPadSign) {
5306                    argText = ' ' + argText;
5307                  }
5308                }
5309              }
5310
5311              // Add padding.
5312              while (argText.length < width) {
5313                if (flagLeftAlign) {
5314                  argText += ' ';
5315                } else {
5316                  if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
5317                    argText = argText[0] + '0' + argText.slice(1);
5318                  } else {
5319                    argText = (flagZeroPad ? '0' : ' ') + argText;
5320                  }
5321                }
5322              }
5323
5324              // Adjust case.
5325              if (next < 97) argText = argText.toUpperCase();
5326
5327              // Insert the result into the buffer.
5328              argText.split('').forEach(function(chr) {
5329                ret.push(chr.charCodeAt(0));
5330              });
5331              break;
5332            }
5333            case 's': {
5334              // String.
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--) {
5340                  ret.push(32);
5341                }
5342              }
5343              if (arg) {
5344                for (var i = 0; i < argLength; i++) {
5345                  ret.push(HEAPU8[((arg++)|0)]);
5346                }
5347              } else {
5348                ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true));
5349              }
5350              if (flagLeftAlign) {
5351                while (argLength < width--) {
5352                  ret.push(32);
5353                }
5354              }
5355              break;
5356            }
5357            case 'c': {
5358              // Character.
5359              if (flagLeftAlign) ret.push(getNextArg('i8'));
5360              while (--width > 0) {
5361                ret.push(32);
5362              }
5363              if (!flagLeftAlign) ret.push(getNextArg('i8'));
5364              break;
5365            }
5366            case 'n': {
5367              // Write the length written so far to the next parameter.
5368              var ptr = getNextArg('i32*');
5369              HEAP32[((ptr)>>2)]=ret.length;
5370              break;
5371            }
5372            case '%': {
5373              // Literal percent sign.
5374              ret.push(curr);
5375              break;
5376            }
5377            default: {
5378              // Unknown specifiers remain untouched.
5379              for (var i = startTextIndex; i < textIndex + 2; i++) {
5380                ret.push(HEAP8[(i)]);
5381              }
5382            }
5383          }
5384          textIndex += 2;
5385          // TODO: Support a/A (hex float) and m (last error) specifiers.
5386          // TODO: Support %1${specifier} for arg selection.
5387        } else {
5388          ret.push(curr);
5389          textIndex += 1;
5390        }
5391      }
5392      return ret;
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);
5400      return ret;
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);
5406    }
5407
5408
5409  Module["_memset"] = _memset;
5410
5411
5412
5413  function _emscripten_memcpy_big(dest, src, num) {
5414      HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
5415      return dest;
5416    }
5417  Module["_memcpy"] = _memcpy;
5418
5419  function _free() {
5420  }
5421  Module["_free"] = _free;
5422Module["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() }
5428FS.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();
5431if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); NODEFS.staticInit(); }
5432__ATINIT__.push({ func: function() { SOCKFS.root = FS.mount(SOCKFS, {}, null); } });
5433STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
5434
5435staticSealed = true; // seal the static portion of memory
5436
5437STACK_MAX = STACK_BASE + 5242880;
5438
5439DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
5440
5441assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
5442
5443
5444var Math_min = Math.min;
5445function asmPrintInt(x, y) {
5446  Module.print('int ' + x + ',' + y);// + ' ' + new Error().stack);
5447}
5448function asmPrintFloat(x, y) {
5449  Module.print('float ' + x + ',' + y);// + ' ' + new Error().stack);
5450}
5451// EMSCRIPTEN_START_ASM
5452var asm = (function(global, env, buffer) {
5453  'use asm';
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);
5462
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;
5467
5468  var __THREW__ = 0;
5469  var threwValue = 0;
5470  var setjmpId = 0;
5471  var undef = 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;
5474
5475  var tempRet0 = 0;
5476  var tempRet1 = 0;
5477  var tempRet2 = 0;
5478  var tempRet3 = 0;
5479  var tempRet4 = 0;
5480  var tempRet5 = 0;
5481  var tempRet6 = 0;
5482  var tempRet7 = 0;
5483  var tempRet8 = 0;
5484  var tempRet9 = 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;
5521
5522// EMSCRIPTEN_START_FUNCS
5523function _main(i3, i5) {
5524 i3 = i3 | 0;
5525 i5 = i5 | 0;
5526 var i1 = 0, i2 = 0, i4 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0, i10 = 0, i11 = 0;
5527 i1 = STACKTOP;
5528 STACKTOP = STACKTOP + 16 | 0;
5529 i2 = i1;
5530 L1 : do {
5531  if ((i3 | 0) > 1) {
5532   i3 = HEAP8[HEAP32[i5 + 4 >> 2] | 0] | 0;
5533   switch (i3 | 0) {
5534   case 50:
5535    {
5536     i3 = 3500;
5537     break L1;
5538    }
5539   case 51:
5540    {
5541     i4 = 4;
5542     break L1;
5543    }
5544   case 52:
5545    {
5546     i3 = 35e3;
5547     break L1;
5548    }
5549   case 53:
5550    {
5551     i3 = 7e4;
5552     break L1;
5553    }
5554   case 49:
5555    {
5556     i3 = 550;
5557     break L1;
5558    }
5559   case 48:
5560    {
5561     i11 = 0;
5562     STACKTOP = i1;
5563     return i11 | 0;
5564    }
5565   default:
5566    {
5567     HEAP32[i2 >> 2] = i3 + -48;
5568     _printf(8, i2 | 0) | 0;
5569     i11 = -1;
5570     STACKTOP = i1;
5571     return i11 | 0;
5572    }
5573   }
5574  } else {
5575   i4 = 4;
5576  }
5577 } while (0);
5578 if ((i4 | 0) == 4) {
5579  i3 = 7e3;
5580 }
5581 i11 = 0;
5582 i8 = 0;
5583 i5 = 0;
5584 while (1) {
5585  i6 = ((i5 | 0) % 5 | 0) + 1 | 0;
5586  i4 = ((i5 | 0) % 3 | 0) + 1 | 0;
5587  i7 = 0;
5588  while (1) {
5589   i11 = ((i7 | 0) / (i6 | 0) | 0) + i11 | 0;
5590   if (i11 >>> 0 > 1e3) {
5591    i11 = (i11 >>> 0) / (i4 >>> 0) | 0;
5592   }
5593   if ((i7 & 3 | 0) == 0) {
5594    i11 = i11 + (Math_imul((i7 & 7 | 0) == 0 ? 1 : -1, i7) | 0) | 0;
5595   }
5596   i10 = i11 << 16 >> 16;
5597   i10 = (Math_imul(i10, i10) | 0) & 255;
5598   i9 = i10 + (i8 & 65535) | 0;
5599   i7 = i7 + 1 | 0;
5600   if ((i7 | 0) == 2e4) {
5601    break;
5602   } else {
5603    i8 = i9;
5604   }
5605  }
5606  i5 = i5 + 1 | 0;
5607  if ((i5 | 0) < (i3 | 0)) {
5608   i8 = i9;
5609  } else {
5610   break;
5611  }
5612 }
5613 HEAP32[i2 >> 2] = i11;
5614 HEAP32[i2 + 4 >> 2] = i8 + i10 & 65535;
5615 _printf(24, i2 | 0) | 0;
5616 i11 = 0;
5617 STACKTOP = i1;
5618 return i11 | 0;
5619}
5620function _memcpy(i3, i2, i1) {
5621 i3 = i3 | 0;
5622 i2 = i2 | 0;
5623 i1 = i1 | 0;
5624 var i4 = 0;
5625 if ((i1 | 0) >= 4096) return _emscripten_memcpy_big(i3 | 0, i2 | 0, i1 | 0) | 0;
5626 i4 = i3 | 0;
5627 if ((i3 & 3) == (i2 & 3)) {
5628  while (i3 & 3) {
5629   if ((i1 | 0) == 0) return i4 | 0;
5630   HEAP8[i3] = HEAP8[i2] | 0;
5631   i3 = i3 + 1 | 0;
5632   i2 = i2 + 1 | 0;
5633   i1 = i1 - 1 | 0;
5634  }
5635  while ((i1 | 0) >= 4) {
5636   HEAP32[i3 >> 2] = HEAP32[i2 >> 2];
5637   i3 = i3 + 4 | 0;
5638   i2 = i2 + 4 | 0;
5639   i1 = i1 - 4 | 0;
5640  }
5641 }
5642 while ((i1 | 0) > 0) {
5643  HEAP8[i3] = HEAP8[i2] | 0;
5644  i3 = i3 + 1 | 0;
5645  i2 = i2 + 1 | 0;
5646  i1 = i1 - 1 | 0;
5647 }
5648 return i4 | 0;
5649}
5650function _memset(i1, i4, i3) {
5651 i1 = i1 | 0;
5652 i4 = i4 | 0;
5653 i3 = i3 | 0;
5654 var i2 = 0, i5 = 0, i6 = 0, i7 = 0;
5655 i2 = i1 + i3 | 0;
5656 if ((i3 | 0) >= 20) {
5657  i4 = i4 & 255;
5658  i7 = i1 & 3;
5659  i6 = i4 | i4 << 8 | i4 << 16 | i4 << 24;
5660  i5 = i2 & ~3;
5661  if (i7) {
5662   i7 = i1 + 4 - i7 | 0;
5663   while ((i1 | 0) < (i7 | 0)) {
5664    HEAP8[i1] = i4;
5665    i1 = i1 + 1 | 0;
5666   }
5667  }
5668  while ((i1 | 0) < (i5 | 0)) {
5669   HEAP32[i1 >> 2] = i6;
5670   i1 = i1 + 4 | 0;
5671  }
5672 }
5673 while ((i1 | 0) < (i2 | 0)) {
5674  HEAP8[i1] = i4;
5675  i1 = i1 + 1 | 0;
5676 }
5677 return i1 - i3 | 0;
5678}
5679function copyTempDouble(i1) {
5680 i1 = i1 | 0;
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];
5689}
5690function copyTempFloat(i1) {
5691 i1 = i1 | 0;
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];
5696}
5697function runPostSets() {}
5698function _strlen(i1) {
5699 i1 = i1 | 0;
5700 var i2 = 0;
5701 i2 = i1;
5702 while (HEAP8[i2] | 0) {
5703  i2 = i2 + 1 | 0;
5704 }
5705 return i2 - i1 | 0;
5706}
5707function stackAlloc(i1) {
5708 i1 = i1 | 0;
5709 var i2 = 0;
5710 i2 = STACKTOP;
5711 STACKTOP = STACKTOP + i1 | 0;
5712 STACKTOP = STACKTOP + 7 & -8;
5713 return i2 | 0;
5714}
5715function setThrew(i1, i2) {
5716 i1 = i1 | 0;
5717 i2 = i2 | 0;
5718 if ((__THREW__ | 0) == 0) {
5719  __THREW__ = i1;
5720  threwValue = i2;
5721 }
5722}
5723function stackRestore(i1) {
5724 i1 = i1 | 0;
5725 STACKTOP = i1;
5726}
5727function setTempRet9(i1) {
5728 i1 = i1 | 0;
5729 tempRet9 = i1;
5730}
5731function setTempRet8(i1) {
5732 i1 = i1 | 0;
5733 tempRet8 = i1;
5734}
5735function setTempRet7(i1) {
5736 i1 = i1 | 0;
5737 tempRet7 = i1;
5738}
5739function setTempRet6(i1) {
5740 i1 = i1 | 0;
5741 tempRet6 = i1;
5742}
5743function setTempRet5(i1) {
5744 i1 = i1 | 0;
5745 tempRet5 = i1;
5746}
5747function setTempRet4(i1) {
5748 i1 = i1 | 0;
5749 tempRet4 = i1;
5750}
5751function setTempRet3(i1) {
5752 i1 = i1 | 0;
5753 tempRet3 = i1;
5754}
5755function setTempRet2(i1) {
5756 i1 = i1 | 0;
5757 tempRet2 = i1;
5758}
5759function setTempRet1(i1) {
5760 i1 = i1 | 0;
5761 tempRet1 = i1;
5762}
5763function setTempRet0(i1) {
5764 i1 = i1 | 0;
5765 tempRet0 = i1;
5766}
5767function stackSave() {
5768 return STACKTOP | 0;
5769}
5770
5771// EMSCRIPTEN_END_FUNCS
5772
5773
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 };
5775})
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);
5778var _strlen = Module["_strlen"] = asm["_strlen"];
5779var _memcpy = Module["_memcpy"] = asm["_memcpy"];
5780var _main = Module["_main"] = asm["_main"];
5781var _memset = Module["_memset"] = asm["_memset"];
5782var runPostSets = Module["runPostSets"] = asm["runPostSets"];
5783
5784Runtime.stackAlloc = function(size) { return asm['stackAlloc'](size) };
5785Runtime.stackSave = function() { return asm['stackSave']() };
5786Runtime.stackRestore = function(top) { asm['stackRestore'](top) };
5787
5788
5789// Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
5790var i64Math = null;
5791
5792// === Auto-generated postamble setup entry stuff ===
5793
5794if (memoryInitializer) {
5795  if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
5796    var data = Module['readBinary'](memoryInitializer);
5797    HEAPU8.set(data, STATIC_BASE);
5798  } else {
5799    addRunDependency('memory initializer');
5800    Browser.asyncLoad(memoryInitializer, function(data) {
5801      HEAPU8.set(data, STATIC_BASE);
5802      removeRunDependency('memory initializer');
5803    }, function(data) {
5804      throw 'could not load memory initializer ' + memoryInitializer;
5805    });
5806  }
5807}
5808
5809function ExitStatus(status) {
5810  this.name = "ExitStatus";
5811  this.message = "Program terminated with exit(" + status + ")";
5812  this.status = status;
5813};
5814ExitStatus.prototype = new Error();
5815ExitStatus.prototype.constructor = ExitStatus;
5816
5817var initialStackTop;
5818var preloadStartTime = null;
5819var calledMain = false;
5820
5821dependenciesFulfilled = 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
5825}
5826
5827Module['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');
5830
5831  args = args || [];
5832
5833  ensureInitRuntime();
5834
5835  var argc = args.length+1;
5836  function pad() {
5837    for (var i = 0; i < 4-1; i++) {
5838      argv.push(0);
5839    }
5840  }
5841  var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORMAL) ];
5842  pad();
5843  for (var i = 0; i < argc-1; i = i + 1) {
5844    argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
5845    pad();
5846  }
5847  argv.push(0);
5848  argv = allocate(argv, 'i32', ALLOC_NORMAL);
5849
5850  initialStackTop = STACKTOP;
5851
5852  try {
5853
5854    var ret = Module['_main'](argc, argv, 0);
5855
5856
5857    // if we're not running an evented main loop, it's time to exit
5858    if (!Module['noExitRuntime']) {
5859      exit(ret);
5860    }
5861  }
5862  catch(e) {
5863    if (e instanceof ExitStatus) {
5864      // exit() throws this once it's done to make sure execution
5865      // has been stopped completely
5866      return;
5867    } else if (e == 'SimulateInfiniteLoop') {
5868      // running an evented main loop, don't immediately exit
5869      Module['noExitRuntime'] = true;
5870      return;
5871    } else {
5872      if (e && typeof e === 'object' && e.stack) Module.printErr('exception thrown: ' + [e, e.stack]);
5873      throw e;
5874    }
5875  } finally {
5876    calledMain = true;
5877  }
5878}
5879
5880
5881
5882
5883function run(args) {
5884  args = args || Module['arguments'];
5885
5886  if (preloadStartTime === null) preloadStartTime = Date.now();
5887
5888  if (runDependencies > 0) {
5889    Module.printErr('run() called, but dependencies remain, so not running');
5890    return;
5891  }
5892
5893  preRun();
5894
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
5897
5898  function doRun() {
5899    if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
5900    Module['calledRun'] = true;
5901
5902    ensureInitRuntime();
5903
5904    preMain();
5905
5906    if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
5907      Module.printErr('pre-main prep time: ' + (Date.now() - preloadStartTime) + ' ms');
5908    }
5909
5910    if (Module['_main'] && shouldRunNow) {
5911      Module['callMain'](args);
5912    }
5913
5914    postRun();
5915  }
5916
5917  if (Module['setStatus']) {
5918    Module['setStatus']('Running...');
5919    setTimeout(function() {
5920      setTimeout(function() {
5921        Module['setStatus']('');
5922      }, 1);
5923      if (!ABORT) doRun();
5924    }, 1);
5925  } else {
5926    doRun();
5927  }
5928}
5929Module['run'] = Module.run = run;
5930
5931function exit(status) {
5932  ABORT = true;
5933  EXITSTATUS = status;
5934  STACKTOP = initialStackTop;
5935
5936  // exit the runtime
5937  exitRuntime();
5938
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
5946
5947  // throw an exception to halt the current execution
5948  throw new ExitStatus(status);
5949}
5950Module['exit'] = Module.exit = exit;
5951
5952function abort(text) {
5953  if (text) {
5954    Module.print(text);
5955    Module.printErr(text);
5956  }
5957
5958  ABORT = true;
5959  EXITSTATUS = 1;
5960
5961  var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
5962
5963  throw 'abort() at ' + stackTrace() + extra;
5964}
5965Module['abort'] = Module.abort = abort;
5966
5967// {{PRE_RUN_ADDITIONS}}
5968
5969if (Module['preInit']) {
5970  if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
5971  while (Module['preInit'].length > 0) {
5972    Module['preInit'].pop()();
5973  }
5974}
5975
5976// shouldRunNow refers to calling main(), not run().
5977var shouldRunNow = true;
5978if (Module['noInitialRun']) {
5979  shouldRunNow = false;
5980}
5981
5982
5983run([].concat(Module["arguments"]));
5984