blob: 5e02d79dec1b25f7afecb0ff669976c5142d351b [file] [log] [blame]
Ben Murdochda12d292016-06-02 14:46:10 +01001// Modified embenchen to direct to asm-wasm.
2// Flags: --expose-wasm
3
4var EXPECTED_OUTPUT = 'lastprime: 387677.\n';
5var Module = {
6 arguments: [1],
7 print: function(x) {Module.printBuffer += x + '\n';},
8 preRun: [function() {Module.printBuffer = ''}],
9 postRun: [function() {
10 assertEquals(EXPECTED_OUTPUT, Module.printBuffer);
11 }],
12};
13// The Module object: Our interface to the outside world. We import
14// and export values on it, and do the work to get that through
15// closure compiler if necessary. There are various ways Module can be used:
16// 1. Not defined. We create it here
17// 2. A function parameter, function(Module) { ..generated code.. }
18// 3. pre-run appended it, var Module = {}; ..generated code..
19// 4. External script tag defines var Module.
20// We need to do an eval in order to handle the closure compiler
21// case, where this code here is minified but Module was defined
22// elsewhere (e.g. case 4 above). We also need to check if Module
23// already exists (e.g. case 3 above).
24// Note that if you want to run closure, and also to use Module
25// after the generated code, you will need to define var Module = {};
26// before the code. Then that object will be used in the code, and you
27// can continue to use Module afterwards as well.
28var Module;
29if (!Module) Module = (typeof Module !== 'undefined' ? Module : null) || {};
30
31// Sometimes an existing Module object exists with properties
32// meant to overwrite the default module functionality. Here
33// we collect those properties and reapply _after_ we configure
34// the current environment's defaults to avoid having to be so
35// defensive during initialization.
36var moduleOverrides = {};
37for (var key in Module) {
38 if (Module.hasOwnProperty(key)) {
39 moduleOverrides[key] = Module[key];
40 }
41}
42
43// The environment setup code below is customized to use Module.
44// *** Environment setup code ***
45var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
46var ENVIRONMENT_IS_WEB = typeof window === 'object';
47var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
48var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
49
50if (ENVIRONMENT_IS_NODE) {
51 // Expose functionality in the same simple way that the shells work
52 // Note that we pollute the global namespace here, otherwise we break in node
53 if (!Module['print']) Module['print'] = function print(x) {
54 process['stdout'].write(x + '\n');
55 };
56 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
57 process['stderr'].write(x + '\n');
58 };
59
60 var nodeFS = require('fs');
61 var nodePath = require('path');
62
63 Module['read'] = function read(filename, binary) {
64 filename = nodePath['normalize'](filename);
65 var ret = nodeFS['readFileSync'](filename);
66 // The path is absolute if the normalized version is the same as the resolved.
67 if (!ret && filename != nodePath['resolve'](filename)) {
68 filename = path.join(__dirname, '..', 'src', filename);
69 ret = nodeFS['readFileSync'](filename);
70 }
71 if (ret && !binary) ret = ret.toString();
72 return ret;
73 };
74
75 Module['readBinary'] = function readBinary(filename) { return Module['read'](filename, true) };
76
77 Module['load'] = function load(f) {
78 globalEval(read(f));
79 };
80
81 Module['arguments'] = process['argv'].slice(2);
82
83 module['exports'] = Module;
84}
85else if (ENVIRONMENT_IS_SHELL) {
86 if (!Module['print']) Module['print'] = print;
87 if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not present in v8 or older sm
88
89 if (typeof read != 'undefined') {
90 Module['read'] = read;
91 } else {
92 Module['read'] = function read() { throw 'no read() available (jsc?)' };
93 }
94
95 Module['readBinary'] = function readBinary(f) {
96 return read(f, 'binary');
97 };
98
99 if (typeof scriptArgs != 'undefined') {
100 Module['arguments'] = scriptArgs;
101 } else if (typeof arguments != 'undefined') {
102 Module['arguments'] = arguments;
103 }
104
105 this['Module'] = Module;
106
107 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)
108}
109else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
110 Module['read'] = function read(url) {
111 var xhr = new XMLHttpRequest();
112 xhr.open('GET', url, false);
113 xhr.send(null);
114 return xhr.responseText;
115 };
116
117 if (typeof arguments != 'undefined') {
118 Module['arguments'] = arguments;
119 }
120
121 if (typeof console !== 'undefined') {
122 if (!Module['print']) Module['print'] = function print(x) {
123 console.log(x);
124 };
125 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
126 console.log(x);
127 };
128 } else {
129 // Probably a worker, and without console.log. We can do very little here...
130 var TRY_USE_DUMP = false;
131 if (!Module['print']) Module['print'] = (TRY_USE_DUMP && (typeof(dump) !== "undefined") ? (function(x) {
132 dump(x);
133 }) : (function(x) {
134 // self.postMessage(x); // enable this if you want stdout to be sent as messages
135 }));
136 }
137
138 if (ENVIRONMENT_IS_WEB) {
139 window['Module'] = Module;
140 } else {
141 Module['load'] = importScripts;
142 }
143}
144else {
145 // Unreachable because SHELL is dependant on the others
146 throw 'Unknown runtime environment. Where are we?';
147}
148
149function globalEval(x) {
150 eval.call(null, x);
151}
152if (!Module['load'] == 'undefined' && Module['read']) {
153 Module['load'] = function load(f) {
154 globalEval(Module['read'](f));
155 };
156}
157if (!Module['print']) {
158 Module['print'] = function(){};
159}
160if (!Module['printErr']) {
161 Module['printErr'] = Module['print'];
162}
163if (!Module['arguments']) {
164 Module['arguments'] = [];
165}
166// *** Environment setup code ***
167
168// Closure helpers
169Module.print = Module['print'];
170Module.printErr = Module['printErr'];
171
172// Callbacks
173Module['preRun'] = [];
174Module['postRun'] = [];
175
176// Merge back in the overrides
177for (var key in moduleOverrides) {
178 if (moduleOverrides.hasOwnProperty(key)) {
179 Module[key] = moduleOverrides[key];
180 }
181}
182
183
184
185// === Auto-generated preamble library stuff ===
186
187//========================================
188// Runtime code shared with compiler
189//========================================
190
191var Runtime = {
192 stackSave: function () {
193 return STACKTOP;
194 },
195 stackRestore: function (stackTop) {
196 STACKTOP = stackTop;
197 },
198 forceAlign: function (target, quantum) {
199 quantum = quantum || 4;
200 if (quantum == 1) return target;
201 if (isNumber(target) && isNumber(quantum)) {
202 return Math.ceil(target/quantum)*quantum;
203 } else if (isNumber(quantum) && isPowerOfTwo(quantum)) {
204 return '(((' +target + ')+' + (quantum-1) + ')&' + -quantum + ')';
205 }
206 return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
207 },
208 isNumberType: function (type) {
209 return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
210 },
211 isPointerType: function isPointerType(type) {
212 return type[type.length-1] == '*';
213},
214 isStructType: function isStructType(type) {
215 if (isPointerType(type)) return false;
216 if (isArrayType(type)) return true;
217 if (/<?\{ ?[^}]* ?\}>?/.test(type)) return true; // { i32, i8 } etc. - anonymous struct types
218 // See comment in isStructPointerType()
219 return type[0] == '%';
220},
221 INT_TYPES: {"i1":0,"i8":0,"i16":0,"i32":0,"i64":0},
222 FLOAT_TYPES: {"float":0,"double":0},
223 or64: function (x, y) {
224 var l = (x | 0) | (y | 0);
225 var h = (Math.round(x / 4294967296) | Math.round(y / 4294967296)) * 4294967296;
226 return l + h;
227 },
228 and64: function (x, y) {
229 var l = (x | 0) & (y | 0);
230 var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 4294967296;
231 return l + h;
232 },
233 xor64: function (x, y) {
234 var l = (x | 0) ^ (y | 0);
235 var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 4294967296;
236 return l + h;
237 },
238 getNativeTypeSize: function (type) {
239 switch (type) {
240 case 'i1': case 'i8': return 1;
241 case 'i16': return 2;
242 case 'i32': return 4;
243 case 'i64': return 8;
244 case 'float': return 4;
245 case 'double': return 8;
246 default: {
247 if (type[type.length-1] === '*') {
248 return Runtime.QUANTUM_SIZE; // A pointer
249 } else if (type[0] === 'i') {
250 var bits = parseInt(type.substr(1));
251 assert(bits % 8 === 0);
252 return bits/8;
253 } else {
254 return 0;
255 }
256 }
257 }
258 },
259 getNativeFieldSize: function (type) {
260 return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
261 },
262 dedup: function dedup(items, ident) {
263 var seen = {};
264 if (ident) {
265 return items.filter(function(item) {
266 if (seen[item[ident]]) return false;
267 seen[item[ident]] = true;
268 return true;
269 });
270 } else {
271 return items.filter(function(item) {
272 if (seen[item]) return false;
273 seen[item] = true;
274 return true;
275 });
276 }
277},
278 set: function set() {
279 var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
280 var ret = {};
281 for (var i = 0; i < args.length; i++) {
282 ret[args[i]] = 0;
283 }
284 return ret;
285},
286 STACK_ALIGN: 8,
287 getAlignSize: function (type, size, vararg) {
288 // we align i64s and doubles on 64-bit boundaries, unlike x86
289 if (!vararg && (type == 'i64' || type == 'double')) return 8;
290 if (!type) return Math.min(size, 8); // align structures internally to 64 bits
291 return Math.min(size || (type ? Runtime.getNativeFieldSize(type) : 0), Runtime.QUANTUM_SIZE);
292 },
293 calculateStructAlignment: function calculateStructAlignment(type) {
294 type.flatSize = 0;
295 type.alignSize = 0;
296 var diffs = [];
297 var prev = -1;
298 var index = 0;
299 type.flatIndexes = type.fields.map(function(field) {
300 index++;
301 var size, alignSize;
302 if (Runtime.isNumberType(field) || Runtime.isPointerType(field)) {
303 size = Runtime.getNativeTypeSize(field); // pack char; char; in structs, also char[X]s.
304 alignSize = Runtime.getAlignSize(field, size);
305 } else if (Runtime.isStructType(field)) {
306 if (field[1] === '0') {
307 // this is [0 x something]. When inside another structure like here, it must be at the end,
308 // and it adds no size
309 // XXX this happens in java-nbody for example... assert(index === type.fields.length, 'zero-length in the middle!');
310 size = 0;
311 if (Types.types[field]) {
312 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
313 } else {
314 alignSize = type.alignSize || QUANTUM_SIZE;
315 }
316 } else {
317 size = Types.types[field].flatSize;
318 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
319 }
320 } else if (field[0] == 'b') {
321 // bN, large number field, like a [N x i8]
322 size = field.substr(1)|0;
323 alignSize = 1;
324 } else if (field[0] === '<') {
325 // vector type
326 size = alignSize = Types.types[field].flatSize; // fully aligned
327 } else if (field[0] === 'i') {
328 // illegal integer field, that could not be legalized because it is an internal structure field
329 // it is ok to have such fields, if we just use them as markers of field size and nothing more complex
330 size = alignSize = parseInt(field.substr(1))/8;
331 assert(size % 1 === 0, 'cannot handle non-byte-size field ' + field);
332 } else {
333 assert(false, 'invalid type for calculateStructAlignment');
334 }
335 if (type.packed) alignSize = 1;
336 type.alignSize = Math.max(type.alignSize, alignSize);
337 var curr = Runtime.alignMemory(type.flatSize, alignSize); // if necessary, place this on aligned memory
338 type.flatSize = curr + size;
339 if (prev >= 0) {
340 diffs.push(curr-prev);
341 }
342 prev = curr;
343 return curr;
344 });
345 if (type.name_ && type.name_[0] === '[') {
346 // arrays have 2 elements, so we get the proper difference. then we scale here. that way we avoid
347 // allocating a potentially huge array for [999999 x i8] etc.
348 type.flatSize = parseInt(type.name_.substr(1))*type.flatSize/2;
349 }
350 type.flatSize = Runtime.alignMemory(type.flatSize, type.alignSize);
351 if (diffs.length == 0) {
352 type.flatFactor = type.flatSize;
353 } else if (Runtime.dedup(diffs).length == 1) {
354 type.flatFactor = diffs[0];
355 }
356 type.needsFlattening = (type.flatFactor != 1);
357 return type.flatIndexes;
358 },
359 generateStructInfo: function (struct, typeName, offset) {
360 var type, alignment;
361 if (typeName) {
362 offset = offset || 0;
363 type = (typeof Types === 'undefined' ? Runtime.typeInfo : Types.types)[typeName];
364 if (!type) return null;
365 if (type.fields.length != struct.length) {
366 printErr('Number of named fields must match the type for ' + typeName + ': possibly duplicate struct names. Cannot return structInfo');
367 return null;
368 }
369 alignment = type.flatIndexes;
370 } else {
371 var type = { fields: struct.map(function(item) { return item[0] }) };
372 alignment = Runtime.calculateStructAlignment(type);
373 }
374 var ret = {
375 __size__: type.flatSize
376 };
377 if (typeName) {
378 struct.forEach(function(item, i) {
379 if (typeof item === 'string') {
380 ret[item] = alignment[i] + offset;
381 } else {
382 // embedded struct
383 var key;
384 for (var k in item) key = k;
385 ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], alignment[i]);
386 }
387 });
388 } else {
389 struct.forEach(function(item, i) {
390 ret[item[1]] = alignment[i];
391 });
392 }
393 return ret;
394 },
395 dynCall: function (sig, ptr, args) {
396 if (args && args.length) {
397 if (!args.splice) args = Array.prototype.slice.call(args);
398 args.splice(0, 0, ptr);
399 return Module['dynCall_' + sig].apply(null, args);
400 } else {
401 return Module['dynCall_' + sig].call(null, ptr);
402 }
403 },
404 functionPointers: [],
405 addFunction: function (func) {
406 for (var i = 0; i < Runtime.functionPointers.length; i++) {
407 if (!Runtime.functionPointers[i]) {
408 Runtime.functionPointers[i] = func;
409 return 2*(1 + i);
410 }
411 }
412 throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
413 },
414 removeFunction: function (index) {
415 Runtime.functionPointers[(index-2)/2] = null;
416 },
417 getAsmConst: function (code, numArgs) {
418 // code is a constant string on the heap, so we can cache these
419 if (!Runtime.asmConstCache) Runtime.asmConstCache = {};
420 var func = Runtime.asmConstCache[code];
421 if (func) return func;
422 var args = [];
423 for (var i = 0; i < numArgs; i++) {
424 args.push(String.fromCharCode(36) + i); // $0, $1 etc
425 }
426 var source = Pointer_stringify(code);
427 if (source[0] === '"') {
428 // tolerate EM_ASM("..code..") even though EM_ASM(..code..) is correct
429 if (source.indexOf('"', 1) === source.length-1) {
430 source = source.substr(1, source.length-2);
431 } else {
432 // something invalid happened, e.g. EM_ASM("..code($0)..", input)
433 abort('invalid EM_ASM input |' + source + '|. Please use EM_ASM(..code..) (no quotes) or EM_ASM({ ..code($0).. }, input) (to input values)');
434 }
435 }
436 try {
437 var evalled = eval('(function(' + args.join(',') + '){ ' + source + ' })'); // new Function does not allow upvars in node
438 } catch(e) {
439 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.)');
440 throw e;
441 }
442 return Runtime.asmConstCache[code] = evalled;
443 },
444 warnOnce: function (text) {
445 if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
446 if (!Runtime.warnOnce.shown[text]) {
447 Runtime.warnOnce.shown[text] = 1;
448 Module.printErr(text);
449 }
450 },
451 funcWrappers: {},
452 getFuncWrapper: function (func, sig) {
453 assert(sig);
454 if (!Runtime.funcWrappers[func]) {
455 Runtime.funcWrappers[func] = function dynCall_wrapper() {
456 return Runtime.dynCall(sig, func, arguments);
457 };
458 }
459 return Runtime.funcWrappers[func];
460 },
461 UTF8Processor: function () {
462 var buffer = [];
463 var needed = 0;
464 this.processCChar = function (code) {
465 code = code & 0xFF;
466
467 if (buffer.length == 0) {
468 if ((code & 0x80) == 0x00) { // 0xxxxxxx
469 return String.fromCharCode(code);
470 }
471 buffer.push(code);
472 if ((code & 0xE0) == 0xC0) { // 110xxxxx
473 needed = 1;
474 } else if ((code & 0xF0) == 0xE0) { // 1110xxxx
475 needed = 2;
476 } else { // 11110xxx
477 needed = 3;
478 }
479 return '';
480 }
481
482 if (needed) {
483 buffer.push(code);
484 needed--;
485 if (needed > 0) return '';
486 }
487
488 var c1 = buffer[0];
489 var c2 = buffer[1];
490 var c3 = buffer[2];
491 var c4 = buffer[3];
492 var ret;
493 if (buffer.length == 2) {
494 ret = String.fromCharCode(((c1 & 0x1F) << 6) | (c2 & 0x3F));
495 } else if (buffer.length == 3) {
496 ret = String.fromCharCode(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
497 } else {
498 // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
499 var codePoint = ((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) |
500 ((c3 & 0x3F) << 6) | (c4 & 0x3F);
501 ret = String.fromCharCode(
502 Math.floor((codePoint - 0x10000) / 0x400) + 0xD800,
503 (codePoint - 0x10000) % 0x400 + 0xDC00);
504 }
505 buffer.length = 0;
506 return ret;
507 }
508 this.processJSString = function processJSString(string) {
509 /* TODO: use TextEncoder when present,
510 var encoder = new TextEncoder();
511 encoder['encoding'] = "utf-8";
512 var utf8Array = encoder['encode'](aMsg.data);
513 */
514 string = unescape(encodeURIComponent(string));
515 var ret = [];
516 for (var i = 0; i < string.length; i++) {
517 ret.push(string.charCodeAt(i));
518 }
519 return ret;
520 }
521 },
522 getCompilerSetting: function (name) {
523 throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work';
524 },
525 stackAlloc: function (size) { var ret = STACKTOP;STACKTOP = (STACKTOP + size)|0;STACKTOP = (((STACKTOP)+7)&-8); return ret; },
526 staticAlloc: function (size) { var ret = STATICTOP;STATICTOP = (STATICTOP + size)|0;STATICTOP = (((STATICTOP)+7)&-8); return ret; },
527 dynamicAlloc: function (size) { var ret = DYNAMICTOP;DYNAMICTOP = (DYNAMICTOP + size)|0;DYNAMICTOP = (((DYNAMICTOP)+7)&-8); if (DYNAMICTOP >= TOTAL_MEMORY) enlargeMemory();; return ret; },
528 alignMemory: function (size,quantum) { var ret = size = Math.ceil((size)/(quantum ? quantum : 8))*(quantum ? quantum : 8); return ret; },
529 makeBigInt: function (low,high,unsigned) { var ret = (unsigned ? ((+((low>>>0)))+((+((high>>>0)))*(+4294967296))) : ((+((low>>>0)))+((+((high|0)))*(+4294967296)))); return ret; },
530 GLOBAL_BASE: 8,
531 QUANTUM_SIZE: 4,
532 __dummy__: 0
533}
534
535
536Module['Runtime'] = Runtime;
537
538
539
540
541
542
543
544
545
546//========================================
547// Runtime essentials
548//========================================
549
550var __THREW__ = 0; // Used in checking for thrown exceptions.
551
552var ABORT = false; // whether we are quitting the application. no code should run after this. set in exit() and abort()
553var EXITSTATUS = 0;
554
555var undef = 0;
556// tempInt is used for 32-bit signed values or smaller. tempBigInt is used
557// for 32-bit unsigned values or more than 32 bits. TODO: audit all uses of tempInt
558var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI, tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD, tempDouble, tempFloat;
559var tempI64, tempI64b;
560var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRet7, tempRet8, tempRet9;
561
562function assert(condition, text) {
563 if (!condition) {
564 abort('Assertion failed: ' + text);
565 }
566}
567
568var globalScope = this;
569
570// C calling interface. A convenient way to call C functions (in C files, or
571// defined with extern "C").
572//
573// Note: LLVM optimizations can inline and remove functions, after which you will not be
574// able to call them. Closure can also do so. To avoid that, add your function to
575// the exports using something like
576//
577// -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
578//
579// @param ident The name of the C function (note that C++ functions will be name-mangled - use extern "C")
580// @param returnType The return type of the function, one of the JS types 'number', 'string' or 'array' (use 'number' for any C pointer, and
581// 'array' for JavaScript arrays and typed arrays; note that arrays are 8-bit).
582// @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,
583// except that 'array' is not possible (there is no way for us to know the length of the array)
584// @param args An array of the arguments to the function, as native JS values (as in returnType)
585// Note that string arguments will be stored on the stack (the JS string will become a C string on the stack).
586// @return The return value, as a native JS value (as in returnType)
587function ccall(ident, returnType, argTypes, args) {
588 return ccallFunc(getCFunc(ident), returnType, argTypes, args);
589}
590Module["ccall"] = ccall;
591
592// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
593function getCFunc(ident) {
594 try {
595 var func = Module['_' + ident]; // closure exported function
596 if (!func) func = eval('_' + ident); // explicit lookup
597 } catch(e) {
598 }
599 assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
600 return func;
601}
602
603// Internal function that does a C call using a function, not an identifier
604function ccallFunc(func, returnType, argTypes, args) {
605 var stack = 0;
606 function toC(value, type) {
607 if (type == 'string') {
608 if (value === null || value === undefined || value === 0) return 0; // null string
609 value = intArrayFromString(value);
610 type = 'array';
611 }
612 if (type == 'array') {
613 if (!stack) stack = Runtime.stackSave();
614 var ret = Runtime.stackAlloc(value.length);
615 writeArrayToMemory(value, ret);
616 return ret;
617 }
618 return value;
619 }
620 function fromC(value, type) {
621 if (type == 'string') {
622 return Pointer_stringify(value);
623 }
624 assert(type != 'array');
625 return value;
626 }
627 var i = 0;
628 var cArgs = args ? args.map(function(arg) {
629 return toC(arg, argTypes[i++]);
630 }) : [];
631 var ret = fromC(func.apply(null, cArgs), returnType);
632 if (stack) Runtime.stackRestore(stack);
633 return ret;
634}
635
636// Returns a native JS wrapper for a C function. This is similar to ccall, but
637// returns a function you can call repeatedly in a normal way. For example:
638//
639// var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
640// alert(my_function(5, 22));
641// alert(my_function(99, 12));
642//
643function cwrap(ident, returnType, argTypes) {
644 var func = getCFunc(ident);
645 return function() {
646 return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(arguments));
647 }
648}
649Module["cwrap"] = cwrap;
650
651// Sets a value in memory in a dynamic way at run-time. Uses the
652// type data. This is the same as makeSetValue, except that
653// makeSetValue is done at compile-time and generates the needed
654// code then, whereas this function picks the right code at
655// run-time.
656// Note that setValue and getValue only do *aligned* writes and reads!
657// Note that ccall uses JS types as for defining types, while setValue and
658// getValue need LLVM types ('i8', 'i32') - this is a lower-level operation
659function setValue(ptr, value, type, noSafe) {
660 type = type || 'i8';
661 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
662 switch(type) {
663 case 'i1': HEAP8[(ptr)]=value; break;
664 case 'i8': HEAP8[(ptr)]=value; break;
665 case 'i16': HEAP16[((ptr)>>1)]=value; break;
666 case 'i32': HEAP32[((ptr)>>2)]=value; break;
667 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;
668 case 'float': HEAPF32[((ptr)>>2)]=value; break;
669 case 'double': HEAPF64[((ptr)>>3)]=value; break;
670 default: abort('invalid type for setValue: ' + type);
671 }
672}
673Module['setValue'] = setValue;
674
675// Parallel to setValue.
676function getValue(ptr, type, noSafe) {
677 type = type || 'i8';
678 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
679 switch(type) {
680 case 'i1': return HEAP8[(ptr)];
681 case 'i8': return HEAP8[(ptr)];
682 case 'i16': return HEAP16[((ptr)>>1)];
683 case 'i32': return HEAP32[((ptr)>>2)];
684 case 'i64': return HEAP32[((ptr)>>2)];
685 case 'float': return HEAPF32[((ptr)>>2)];
686 case 'double': return HEAPF64[((ptr)>>3)];
687 default: abort('invalid type for setValue: ' + type);
688 }
689 return null;
690}
691Module['getValue'] = getValue;
692
693var ALLOC_NORMAL = 0; // Tries to use _malloc()
694var ALLOC_STACK = 1; // Lives for the duration of the current function call
695var ALLOC_STATIC = 2; // Cannot be freed
696var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
697var ALLOC_NONE = 4; // Do not allocate
698Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
699Module['ALLOC_STACK'] = ALLOC_STACK;
700Module['ALLOC_STATIC'] = ALLOC_STATIC;
701Module['ALLOC_DYNAMIC'] = ALLOC_DYNAMIC;
702Module['ALLOC_NONE'] = ALLOC_NONE;
703
704// allocate(): This is for internal use. You can use it yourself as well, but the interface
705// is a little tricky (see docs right below). The reason is that it is optimized
706// for multiple syntaxes to save space in generated code. So you should
707// normally not use allocate(), and instead allocate memory using _malloc(),
708// initialize it with setValue(), and so forth.
709// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
710// in *bytes* (note that this is sometimes confusing: the next parameter does not
711// affect this!)
712// @types: Either an array of types, one for each byte (or 0 if no type at that position),
713// or a single type which is used for the entire block. This only matters if there
714// is initial data - if @slab is a number, then this does not matter at all and is
715// ignored.
716// @allocator: How to allocate memory, see ALLOC_*
717function allocate(slab, types, allocator, ptr) {
718 var zeroinit, size;
719 if (typeof slab === 'number') {
720 zeroinit = true;
721 size = slab;
722 } else {
723 zeroinit = false;
724 size = slab.length;
725 }
726
727 var singleType = typeof types === 'string' ? types : null;
728
729 var ret;
730 if (allocator == ALLOC_NONE) {
731 ret = ptr;
732 } else {
733 ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
734 }
735
736 if (zeroinit) {
737 var ptr = ret, stop;
738 assert((ret & 3) == 0);
739 stop = ret + (size & ~3);
740 for (; ptr < stop; ptr += 4) {
741 HEAP32[((ptr)>>2)]=0;
742 }
743 stop = ret + size;
744 while (ptr < stop) {
745 HEAP8[((ptr++)|0)]=0;
746 }
747 return ret;
748 }
749
750 if (singleType === 'i8') {
751 if (slab.subarray || slab.slice) {
752 HEAPU8.set(slab, ret);
753 } else {
754 HEAPU8.set(new Uint8Array(slab), ret);
755 }
756 return ret;
757 }
758
759 var i = 0, type, typeSize, previousType;
760 while (i < size) {
761 var curr = slab[i];
762
763 if (typeof curr === 'function') {
764 curr = Runtime.getFunctionIndex(curr);
765 }
766
767 type = singleType || types[i];
768 if (type === 0) {
769 i++;
770 continue;
771 }
772
773 if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
774
775 setValue(ret+i, curr, type);
776
777 // no need to look up size unless type changes, so cache it
778 if (previousType !== type) {
779 typeSize = Runtime.getNativeTypeSize(type);
780 previousType = type;
781 }
782 i += typeSize;
783 }
784
785 return ret;
786}
787Module['allocate'] = allocate;
788
789function Pointer_stringify(ptr, /* optional */ length) {
790 // TODO: use TextDecoder
791 // Find the length, and check for UTF while doing so
792 var hasUtf = false;
793 var t;
794 var i = 0;
795 while (1) {
796 t = HEAPU8[(((ptr)+(i))|0)];
797 if (t >= 128) hasUtf = true;
798 else if (t == 0 && !length) break;
799 i++;
800 if (length && i == length) break;
801 }
802 if (!length) length = i;
803
804 var ret = '';
805
806 if (!hasUtf) {
807 var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
808 var curr;
809 while (length > 0) {
810 curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
811 ret = ret ? ret + curr : curr;
812 ptr += MAX_CHUNK;
813 length -= MAX_CHUNK;
814 }
815 return ret;
816 }
817
818 var utf8 = new Runtime.UTF8Processor();
819 for (i = 0; i < length; i++) {
820 t = HEAPU8[(((ptr)+(i))|0)];
821 ret += utf8.processCChar(t);
822 }
823 return ret;
824}
825Module['Pointer_stringify'] = Pointer_stringify;
826
827// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
828// a copy of that string as a Javascript String object.
829function UTF16ToString(ptr) {
830 var i = 0;
831
832 var str = '';
833 while (1) {
834 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
835 if (codeUnit == 0)
836 return str;
837 ++i;
838 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
839 str += String.fromCharCode(codeUnit);
840 }
841}
842Module['UTF16ToString'] = UTF16ToString;
843
844// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
845// null-terminated and encoded in UTF16LE form. The copy will require at most (str.length*2+1)*2 bytes of space in the HEAP.
846function stringToUTF16(str, outPtr) {
847 for(var i = 0; i < str.length; ++i) {
848 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
849 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
850 HEAP16[(((outPtr)+(i*2))>>1)]=codeUnit;
851 }
852 // Null-terminate the pointer to the HEAP.
853 HEAP16[(((outPtr)+(str.length*2))>>1)]=0;
854}
855Module['stringToUTF16'] = stringToUTF16;
856
857// Given a pointer 'ptr' to a null-terminated UTF32LE-encoded string in the emscripten HEAP, returns
858// a copy of that string as a Javascript String object.
859function UTF32ToString(ptr) {
860 var i = 0;
861
862 var str = '';
863 while (1) {
864 var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
865 if (utf32 == 0)
866 return str;
867 ++i;
868 // 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.
869 if (utf32 >= 0x10000) {
870 var ch = utf32 - 0x10000;
871 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
872 } else {
873 str += String.fromCharCode(utf32);
874 }
875 }
876}
877Module['UTF32ToString'] = UTF32ToString;
878
879// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
880// null-terminated and encoded in UTF32LE form. The copy will require at most (str.length+1)*4 bytes of space in the HEAP,
881// 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.
882function stringToUTF32(str, outPtr) {
883 var iChar = 0;
884 for(var iCodeUnit = 0; iCodeUnit < str.length; ++iCodeUnit) {
885 // 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.
886 var codeUnit = str.charCodeAt(iCodeUnit); // possibly a lead surrogate
887 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
888 var trailSurrogate = str.charCodeAt(++iCodeUnit);
889 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
890 }
891 HEAP32[(((outPtr)+(iChar*4))>>2)]=codeUnit;
892 ++iChar;
893 }
894 // Null-terminate the pointer to the HEAP.
895 HEAP32[(((outPtr)+(iChar*4))>>2)]=0;
896}
897Module['stringToUTF32'] = stringToUTF32;
898
899function demangle(func) {
900 var i = 3;
901 // params, etc.
902 var basicTypes = {
903 'v': 'void',
904 'b': 'bool',
905 'c': 'char',
906 's': 'short',
907 'i': 'int',
908 'l': 'long',
909 'f': 'float',
910 'd': 'double',
911 'w': 'wchar_t',
912 'a': 'signed char',
913 'h': 'unsigned char',
914 't': 'unsigned short',
915 'j': 'unsigned int',
916 'm': 'unsigned long',
917 'x': 'long long',
918 'y': 'unsigned long long',
919 'z': '...'
920 };
921 var subs = [];
922 var first = true;
923 function dump(x) {
924 //return;
925 if (x) Module.print(x);
926 Module.print(func);
927 var pre = '';
928 for (var a = 0; a < i; a++) pre += ' ';
929 Module.print (pre + '^');
930 }
931 function parseNested() {
932 i++;
933 if (func[i] === 'K') i++; // ignore const
934 var parts = [];
935 while (func[i] !== 'E') {
936 if (func[i] === 'S') { // substitution
937 i++;
938 var next = func.indexOf('_', i);
939 var num = func.substring(i, next) || 0;
940 parts.push(subs[num] || '?');
941 i = next+1;
942 continue;
943 }
944 if (func[i] === 'C') { // constructor
945 parts.push(parts[parts.length-1]);
946 i += 2;
947 continue;
948 }
949 var size = parseInt(func.substr(i));
950 var pre = size.toString().length;
951 if (!size || !pre) { i--; break; } // counter i++ below us
952 var curr = func.substr(i + pre, size);
953 parts.push(curr);
954 subs.push(curr);
955 i += pre + size;
956 }
957 i++; // skip E
958 return parts;
959 }
960 function parse(rawList, limit, allowVoid) { // main parser
961 limit = limit || Infinity;
962 var ret = '', list = [];
963 function flushList() {
964 return '(' + list.join(', ') + ')';
965 }
966 var name;
967 if (func[i] === 'N') {
968 // namespaced N-E
969 name = parseNested().join('::');
970 limit--;
971 if (limit === 0) return rawList ? [name] : name;
972 } else {
973 // not namespaced
974 if (func[i] === 'K' || (first && func[i] === 'L')) i++; // ignore const and first 'L'
975 var size = parseInt(func.substr(i));
976 if (size) {
977 var pre = size.toString().length;
978 name = func.substr(i + pre, size);
979 i += pre + size;
980 }
981 }
982 first = false;
983 if (func[i] === 'I') {
984 i++;
985 var iList = parse(true);
986 var iRet = parse(true, 1, true);
987 ret += iRet[0] + ' ' + name + '<' + iList.join(', ') + '>';
988 } else {
989 ret = name;
990 }
991 paramLoop: while (i < func.length && limit-- > 0) {
992 //dump('paramLoop');
993 var c = func[i++];
994 if (c in basicTypes) {
995 list.push(basicTypes[c]);
996 } else {
997 switch (c) {
998 case 'P': list.push(parse(true, 1, true)[0] + '*'); break; // pointer
999 case 'R': list.push(parse(true, 1, true)[0] + '&'); break; // reference
1000 case 'L': { // literal
1001 i++; // skip basic type
1002 var end = func.indexOf('E', i);
1003 var size = end - i;
1004 list.push(func.substr(i, size));
1005 i += size + 2; // size + 'EE'
1006 break;
1007 }
1008 case 'A': { // array
1009 var size = parseInt(func.substr(i));
1010 i += size.toString().length;
1011 if (func[i] !== '_') throw '?';
1012 i++; // skip _
1013 list.push(parse(true, 1, true)[0] + ' [' + size + ']');
1014 break;
1015 }
1016 case 'E': break paramLoop;
1017 default: ret += '?' + c; break paramLoop;
1018 }
1019 }
1020 }
1021 if (!allowVoid && list.length === 1 && list[0] === 'void') list = []; // avoid (void)
1022 if (rawList) {
1023 if (ret) {
1024 list.push(ret + '?');
1025 }
1026 return list;
1027 } else {
1028 return ret + flushList();
1029 }
1030 }
1031 try {
1032 // Special-case the entry point, since its name differs from other name mangling.
1033 if (func == 'Object._main' || func == '_main') {
1034 return 'main()';
1035 }
1036 if (typeof func === 'number') func = Pointer_stringify(func);
1037 if (func[0] !== '_') return func;
1038 if (func[1] !== '_') return func; // C function
1039 if (func[2] !== 'Z') return func;
1040 switch (func[3]) {
1041 case 'n': return 'operator new()';
1042 case 'd': return 'operator delete()';
1043 }
1044 return parse();
1045 } catch(e) {
1046 return func;
1047 }
1048}
1049
1050function demangleAll(text) {
1051 return text.replace(/__Z[\w\d_]+/g, function(x) { var y = demangle(x); return x === y ? x : (x + ' [' + y + ']') });
1052}
1053
1054function stackTrace() {
1055 var stack = new Error().stack;
1056 return stack ? demangleAll(stack) : '(no stack trace available)'; // Stack trace is not available at least on IE10 and Safari 6.
1057}
1058
1059// Memory management
1060
1061var PAGE_SIZE = 4096;
1062function alignMemoryPage(x) {
1063 return (x+4095)&-4096;
1064}
1065
1066var HEAP;
1067var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
1068
1069var STATIC_BASE = 0, STATICTOP = 0, staticSealed = false; // static area
1070var STACK_BASE = 0, STACKTOP = 0, STACK_MAX = 0; // stack area
1071var DYNAMIC_BASE = 0, DYNAMICTOP = 0; // dynamic area handled by sbrk
1072
1073function enlargeMemory() {
1074 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.');
1075}
1076
1077var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
1078var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 134217728;
1079var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
1080
1081var totalMemory = 4096;
1082while (totalMemory < TOTAL_MEMORY || totalMemory < 2*TOTAL_STACK) {
1083 if (totalMemory < 16*1024*1024) {
1084 totalMemory *= 2;
1085 } else {
1086 totalMemory += 16*1024*1024
1087 }
1088}
1089if (totalMemory !== TOTAL_MEMORY) {
1090 Module.printErr('increasing TOTAL_MEMORY to ' + totalMemory + ' to be more reasonable');
1091 TOTAL_MEMORY = totalMemory;
1092}
1093
1094// Initialize the runtime's memory
1095// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1096assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
1097 'JS engine does not provide full typed array support');
1098
1099var buffer = new ArrayBuffer(TOTAL_MEMORY);
1100HEAP8 = new Int8Array(buffer);
1101HEAP16 = new Int16Array(buffer);
1102HEAP32 = new Int32Array(buffer);
1103HEAPU8 = new Uint8Array(buffer);
1104HEAPU16 = new Uint16Array(buffer);
1105HEAPU32 = new Uint32Array(buffer);
1106HEAPF32 = new Float32Array(buffer);
1107HEAPF64 = new Float64Array(buffer);
1108
1109// Endianness check (note: assumes compiler arch was little-endian)
1110HEAP32[0] = 255;
1111assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a little-endian system');
1112
1113Module['HEAP'] = HEAP;
1114Module['HEAP8'] = HEAP8;
1115Module['HEAP16'] = HEAP16;
1116Module['HEAP32'] = HEAP32;
1117Module['HEAPU8'] = HEAPU8;
1118Module['HEAPU16'] = HEAPU16;
1119Module['HEAPU32'] = HEAPU32;
1120Module['HEAPF32'] = HEAPF32;
1121Module['HEAPF64'] = HEAPF64;
1122
1123function callRuntimeCallbacks(callbacks) {
1124 while(callbacks.length > 0) {
1125 var callback = callbacks.shift();
1126 if (typeof callback == 'function') {
1127 callback();
1128 continue;
1129 }
1130 var func = callback.func;
1131 if (typeof func === 'number') {
1132 if (callback.arg === undefined) {
1133 Runtime.dynCall('v', func);
1134 } else {
1135 Runtime.dynCall('vi', func, [callback.arg]);
1136 }
1137 } else {
1138 func(callback.arg === undefined ? null : callback.arg);
1139 }
1140 }
1141}
1142
1143var __ATPRERUN__ = []; // functions called before the runtime is initialized
1144var __ATINIT__ = []; // functions called during startup
1145var __ATMAIN__ = []; // functions called when main() is to be run
1146var __ATEXIT__ = []; // functions called during shutdown
1147var __ATPOSTRUN__ = []; // functions called after the runtime has exited
1148
1149var runtimeInitialized = false;
1150
1151function preRun() {
1152 // compatibility - merge in anything from Module['preRun'] at this time
1153 if (Module['preRun']) {
1154 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1155 while (Module['preRun'].length) {
1156 addOnPreRun(Module['preRun'].shift());
1157 }
1158 }
1159 callRuntimeCallbacks(__ATPRERUN__);
1160}
1161
1162function ensureInitRuntime() {
1163 if (runtimeInitialized) return;
1164 runtimeInitialized = true;
1165 callRuntimeCallbacks(__ATINIT__);
1166}
1167
1168function preMain() {
1169 callRuntimeCallbacks(__ATMAIN__);
1170}
1171
1172function exitRuntime() {
1173 callRuntimeCallbacks(__ATEXIT__);
1174}
1175
1176function postRun() {
1177 // compatibility - merge in anything from Module['postRun'] at this time
1178 if (Module['postRun']) {
1179 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1180 while (Module['postRun'].length) {
1181 addOnPostRun(Module['postRun'].shift());
1182 }
1183 }
1184 callRuntimeCallbacks(__ATPOSTRUN__);
1185}
1186
1187function addOnPreRun(cb) {
1188 __ATPRERUN__.unshift(cb);
1189}
1190Module['addOnPreRun'] = Module.addOnPreRun = addOnPreRun;
1191
1192function addOnInit(cb) {
1193 __ATINIT__.unshift(cb);
1194}
1195Module['addOnInit'] = Module.addOnInit = addOnInit;
1196
1197function addOnPreMain(cb) {
1198 __ATMAIN__.unshift(cb);
1199}
1200Module['addOnPreMain'] = Module.addOnPreMain = addOnPreMain;
1201
1202function addOnExit(cb) {
1203 __ATEXIT__.unshift(cb);
1204}
1205Module['addOnExit'] = Module.addOnExit = addOnExit;
1206
1207function addOnPostRun(cb) {
1208 __ATPOSTRUN__.unshift(cb);
1209}
1210Module['addOnPostRun'] = Module.addOnPostRun = addOnPostRun;
1211
1212// Tools
1213
1214// This processes a JS string into a C-line array of numbers, 0-terminated.
1215// For LLVM-originating strings, see parser.js:parseLLVMString function
1216function intArrayFromString(stringy, dontAddNull, length /* optional */) {
1217 var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
1218 if (length) {
1219 ret.length = length;
1220 }
1221 if (!dontAddNull) {
1222 ret.push(0);
1223 }
1224 return ret;
1225}
1226Module['intArrayFromString'] = intArrayFromString;
1227
1228function intArrayToString(array) {
1229 var ret = [];
1230 for (var i = 0; i < array.length; i++) {
1231 var chr = array[i];
1232 if (chr > 0xFF) {
1233 chr &= 0xFF;
1234 }
1235 ret.push(String.fromCharCode(chr));
1236 }
1237 return ret.join('');
1238}
1239Module['intArrayToString'] = intArrayToString;
1240
1241// Write a Javascript array to somewhere in the heap
1242function writeStringToMemory(string, buffer, dontAddNull) {
1243 var array = intArrayFromString(string, dontAddNull);
1244 var i = 0;
1245 while (i < array.length) {
1246 var chr = array[i];
1247 HEAP8[(((buffer)+(i))|0)]=chr;
1248 i = i + 1;
1249 }
1250}
1251Module['writeStringToMemory'] = writeStringToMemory;
1252
1253function writeArrayToMemory(array, buffer) {
1254 for (var i = 0; i < array.length; i++) {
1255 HEAP8[(((buffer)+(i))|0)]=array[i];
1256 }
1257}
1258Module['writeArrayToMemory'] = writeArrayToMemory;
1259
1260function writeAsciiToMemory(str, buffer, dontAddNull) {
1261 for (var i = 0; i < str.length; i++) {
1262 HEAP8[(((buffer)+(i))|0)]=str.charCodeAt(i);
1263 }
1264 if (!dontAddNull) HEAP8[(((buffer)+(str.length))|0)]=0;
1265}
1266Module['writeAsciiToMemory'] = writeAsciiToMemory;
1267
1268function unSign(value, bits, ignore) {
1269 if (value >= 0) {
1270 return value;
1271 }
1272 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
1273 : Math.pow(2, bits) + value;
1274}
1275function reSign(value, bits, ignore) {
1276 if (value <= 0) {
1277 return value;
1278 }
1279 var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1280 : Math.pow(2, bits-1);
1281 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
1282 // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1283 // TODO: In i64 mode 1, resign the two parts separately and safely
1284 value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1285 }
1286 return value;
1287}
1288
1289// check for imul support, and also for correctness ( https://bugs.webkit.org/show_bug.cgi?id=126345 )
1290if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
1291 var ah = a >>> 16;
1292 var al = a & 0xffff;
1293 var bh = b >>> 16;
1294 var bl = b & 0xffff;
1295 return (al*bl + ((ah*bl + al*bh) << 16))|0;
1296};
1297Math.imul = Math['imul'];
1298
1299
1300var Math_abs = Math.abs;
1301var Math_cos = Math.cos;
1302var Math_sin = Math.sin;
1303var Math_tan = Math.tan;
1304var Math_acos = Math.acos;
1305var Math_asin = Math.asin;
1306var Math_atan = Math.atan;
1307var Math_atan2 = Math.atan2;
1308var Math_exp = Math.exp;
1309var Math_log = Math.log;
1310var Math_sqrt = Math.sqrt;
1311var Math_ceil = Math.ceil;
1312var Math_floor = Math.floor;
1313var Math_pow = Math.pow;
1314var Math_imul = Math.imul;
1315var Math_fround = Math.fround;
1316var Math_min = Math.min;
1317
1318// A counter of dependencies for calling run(). If we need to
1319// do asynchronous work before running, increment this and
1320// decrement it. Incrementing must happen in a place like
1321// PRE_RUN_ADDITIONS (used by emcc to add file preloading).
1322// Note that you can add dependencies in preRun, even though
1323// it happens right before run - run will be postponed until
1324// the dependencies are met.
1325var runDependencies = 0;
1326var runDependencyWatcher = null;
1327var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1328
1329function addRunDependency(id) {
1330 runDependencies++;
1331 if (Module['monitorRunDependencies']) {
1332 Module['monitorRunDependencies'](runDependencies);
1333 }
1334}
1335Module['addRunDependency'] = addRunDependency;
1336function removeRunDependency(id) {
1337 runDependencies--;
1338 if (Module['monitorRunDependencies']) {
1339 Module['monitorRunDependencies'](runDependencies);
1340 }
1341 if (runDependencies == 0) {
1342 if (runDependencyWatcher !== null) {
1343 clearInterval(runDependencyWatcher);
1344 runDependencyWatcher = null;
1345 }
1346 if (dependenciesFulfilled) {
1347 var callback = dependenciesFulfilled;
1348 dependenciesFulfilled = null;
1349 callback(); // can add another dependenciesFulfilled
1350 }
1351 }
1352}
1353Module['removeRunDependency'] = removeRunDependency;
1354
1355Module["preloadedImages"] = {}; // maps url to image data
1356Module["preloadedAudios"] = {}; // maps url to audio data
1357
1358
1359var memoryInitializer = null;
1360
1361// === Body ===
1362
1363
1364
1365
1366
1367STATIC_BASE = 8;
1368
1369STATICTOP = STATIC_BASE + Runtime.alignMemory(35);
1370/* global initializers */ __ATINIT__.push();
1371
1372
1373/* memory initializer */ allocate([101,114,114,111,114,58,32,37,100,92,110,0,0,0,0,0,108,97,115,116,112,114,105,109,101,58,32,37,100,46,10,0], "i8", ALLOC_NONE, Runtime.GLOBAL_BASE);
1374
1375
1376
1377
1378var tempDoublePtr = Runtime.alignMemory(allocate(12, "i8", ALLOC_STATIC), 8);
1379
1380assert(tempDoublePtr % 8 == 0);
1381
1382function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1383
1384 HEAP8[tempDoublePtr] = HEAP8[ptr];
1385
1386 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1387
1388 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1389
1390 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1391
1392}
1393
1394function copyTempDouble(ptr) {
1395
1396 HEAP8[tempDoublePtr] = HEAP8[ptr];
1397
1398 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1399
1400 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1401
1402 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1403
1404 HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1405
1406 HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1407
1408 HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1409
1410 HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1411
1412}
1413
1414
1415 function _malloc(bytes) {
1416 /* Over-allocate to make sure it is byte-aligned by 8.
1417 * This will leak memory, but this is only the dummy
1418 * implementation (replaced by dlmalloc normally) so
1419 * not an issue.
1420 */
1421 var ptr = Runtime.dynamicAlloc(bytes + 8);
1422 return (ptr+8) & 0xFFFFFFF8;
1423 }
1424 Module["_malloc"] = _malloc;
1425
1426
1427 Module["_memset"] = _memset;
1428
1429 function _free() {
1430 }
1431 Module["_free"] = _free;
1432
1433
1434 function _emscripten_memcpy_big(dest, src, num) {
1435 HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
1436 return dest;
1437 }
1438 Module["_memcpy"] = _memcpy;
1439
1440
1441
1442
1443 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};
1444
1445 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"};
1446
1447
1448 var ___errno_state=0;function ___setErrNo(value) {
1449 // For convenient setting and returning of errno.
1450 HEAP32[((___errno_state)>>2)]=value;
1451 return value;
1452 }
1453
1454 var TTY={ttys:[],init:function () {
1455 // https://github.com/kripken/emscripten/pull/1555
1456 // if (ENVIRONMENT_IS_NODE) {
1457 // // currently, FS.init does not distinguish if process.stdin is a file or TTY
1458 // // device, it always assumes it's a TTY device. because of this, we're forcing
1459 // // process.stdin to UTF8 encoding to at least make stdin reading compatible
1460 // // with text files until FS.init can be refactored.
1461 // process['stdin']['setEncoding']('utf8');
1462 // }
1463 },shutdown:function () {
1464 // https://github.com/kripken/emscripten/pull/1555
1465 // if (ENVIRONMENT_IS_NODE) {
1466 // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
1467 // // 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
1468 // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
1469 // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
1470 // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
1471 // process['stdin']['pause']();
1472 // }
1473 },register:function (dev, ops) {
1474 TTY.ttys[dev] = { input: [], output: [], ops: ops };
1475 FS.registerDevice(dev, TTY.stream_ops);
1476 },stream_ops:{open:function (stream) {
1477 var tty = TTY.ttys[stream.node.rdev];
1478 if (!tty) {
1479 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1480 }
1481 stream.tty = tty;
1482 stream.seekable = false;
1483 },close:function (stream) {
1484 // flush any pending line data
1485 if (stream.tty.output.length) {
1486 stream.tty.ops.put_char(stream.tty, 10);
1487 }
1488 },read:function (stream, buffer, offset, length, pos /* ignored */) {
1489 if (!stream.tty || !stream.tty.ops.get_char) {
1490 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1491 }
1492 var bytesRead = 0;
1493 for (var i = 0; i < length; i++) {
1494 var result;
1495 try {
1496 result = stream.tty.ops.get_char(stream.tty);
1497 } catch (e) {
1498 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1499 }
1500 if (result === undefined && bytesRead === 0) {
1501 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
1502 }
1503 if (result === null || result === undefined) break;
1504 bytesRead++;
1505 buffer[offset+i] = result;
1506 }
1507 if (bytesRead) {
1508 stream.node.timestamp = Date.now();
1509 }
1510 return bytesRead;
1511 },write:function (stream, buffer, offset, length, pos) {
1512 if (!stream.tty || !stream.tty.ops.put_char) {
1513 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1514 }
1515 for (var i = 0; i < length; i++) {
1516 try {
1517 stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
1518 } catch (e) {
1519 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1520 }
1521 }
1522 if (length) {
1523 stream.node.timestamp = Date.now();
1524 }
1525 return i;
1526 }},default_tty_ops:{get_char:function (tty) {
1527 if (!tty.input.length) {
1528 var result = null;
1529 if (ENVIRONMENT_IS_NODE) {
1530 result = process['stdin']['read']();
1531 if (!result) {
1532 if (process['stdin']['_readableState'] && process['stdin']['_readableState']['ended']) {
1533 return null; // EOF
1534 }
1535 return undefined; // no data available
1536 }
1537 } else if (typeof window != 'undefined' &&
1538 typeof window.prompt == 'function') {
1539 // Browser.
1540 result = window.prompt('Input: '); // returns null on cancel
1541 if (result !== null) {
1542 result += '\n';
1543 }
1544 } else if (typeof readline == 'function') {
1545 // Command line.
1546 result = readline();
1547 if (result !== null) {
1548 result += '\n';
1549 }
1550 }
1551 if (!result) {
1552 return null;
1553 }
1554 tty.input = intArrayFromString(result, true);
1555 }
1556 return tty.input.shift();
1557 },put_char:function (tty, val) {
1558 if (val === null || val === 10) {
1559 Module['print'](tty.output.join(''));
1560 tty.output = [];
1561 } else {
1562 tty.output.push(TTY.utf8.processCChar(val));
1563 }
1564 }},default_tty1_ops:{put_char:function (tty, val) {
1565 if (val === null || val === 10) {
1566 Module['printErr'](tty.output.join(''));
1567 tty.output = [];
1568 } else {
1569 tty.output.push(TTY.utf8.processCChar(val));
1570 }
1571 }}};
1572
1573 var MEMFS={ops_table:null,CONTENT_OWNING:1,CONTENT_FLEXIBLE:2,CONTENT_FIXED:3,mount:function (mount) {
1574 return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
1575 },createNode:function (parent, name, mode, dev) {
1576 if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
1577 // no supported
1578 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
1579 }
1580 if (!MEMFS.ops_table) {
1581 MEMFS.ops_table = {
1582 dir: {
1583 node: {
1584 getattr: MEMFS.node_ops.getattr,
1585 setattr: MEMFS.node_ops.setattr,
1586 lookup: MEMFS.node_ops.lookup,
1587 mknod: MEMFS.node_ops.mknod,
1588 rename: MEMFS.node_ops.rename,
1589 unlink: MEMFS.node_ops.unlink,
1590 rmdir: MEMFS.node_ops.rmdir,
1591 readdir: MEMFS.node_ops.readdir,
1592 symlink: MEMFS.node_ops.symlink
1593 },
1594 stream: {
1595 llseek: MEMFS.stream_ops.llseek
1596 }
1597 },
1598 file: {
1599 node: {
1600 getattr: MEMFS.node_ops.getattr,
1601 setattr: MEMFS.node_ops.setattr
1602 },
1603 stream: {
1604 llseek: MEMFS.stream_ops.llseek,
1605 read: MEMFS.stream_ops.read,
1606 write: MEMFS.stream_ops.write,
1607 allocate: MEMFS.stream_ops.allocate,
1608 mmap: MEMFS.stream_ops.mmap
1609 }
1610 },
1611 link: {
1612 node: {
1613 getattr: MEMFS.node_ops.getattr,
1614 setattr: MEMFS.node_ops.setattr,
1615 readlink: MEMFS.node_ops.readlink
1616 },
1617 stream: {}
1618 },
1619 chrdev: {
1620 node: {
1621 getattr: MEMFS.node_ops.getattr,
1622 setattr: MEMFS.node_ops.setattr
1623 },
1624 stream: FS.chrdev_stream_ops
1625 },
1626 };
1627 }
1628 var node = FS.createNode(parent, name, mode, dev);
1629 if (FS.isDir(node.mode)) {
1630 node.node_ops = MEMFS.ops_table.dir.node;
1631 node.stream_ops = MEMFS.ops_table.dir.stream;
1632 node.contents = {};
1633 } else if (FS.isFile(node.mode)) {
1634 node.node_ops = MEMFS.ops_table.file.node;
1635 node.stream_ops = MEMFS.ops_table.file.stream;
1636 node.contents = [];
1637 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1638 } else if (FS.isLink(node.mode)) {
1639 node.node_ops = MEMFS.ops_table.link.node;
1640 node.stream_ops = MEMFS.ops_table.link.stream;
1641 } else if (FS.isChrdev(node.mode)) {
1642 node.node_ops = MEMFS.ops_table.chrdev.node;
1643 node.stream_ops = MEMFS.ops_table.chrdev.stream;
1644 }
1645 node.timestamp = Date.now();
1646 // add the new node to the parent
1647 if (parent) {
1648 parent.contents[name] = node;
1649 }
1650 return node;
1651 },ensureFlexible:function (node) {
1652 if (node.contentMode !== MEMFS.CONTENT_FLEXIBLE) {
1653 var contents = node.contents;
1654 node.contents = Array.prototype.slice.call(contents);
1655 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1656 }
1657 },node_ops:{getattr:function (node) {
1658 var attr = {};
1659 // device numbers reuse inode numbers.
1660 attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1661 attr.ino = node.id;
1662 attr.mode = node.mode;
1663 attr.nlink = 1;
1664 attr.uid = 0;
1665 attr.gid = 0;
1666 attr.rdev = node.rdev;
1667 if (FS.isDir(node.mode)) {
1668 attr.size = 4096;
1669 } else if (FS.isFile(node.mode)) {
1670 attr.size = node.contents.length;
1671 } else if (FS.isLink(node.mode)) {
1672 attr.size = node.link.length;
1673 } else {
1674 attr.size = 0;
1675 }
1676 attr.atime = new Date(node.timestamp);
1677 attr.mtime = new Date(node.timestamp);
1678 attr.ctime = new Date(node.timestamp);
1679 // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
1680 // but this is not required by the standard.
1681 attr.blksize = 4096;
1682 attr.blocks = Math.ceil(attr.size / attr.blksize);
1683 return attr;
1684 },setattr:function (node, attr) {
1685 if (attr.mode !== undefined) {
1686 node.mode = attr.mode;
1687 }
1688 if (attr.timestamp !== undefined) {
1689 node.timestamp = attr.timestamp;
1690 }
1691 if (attr.size !== undefined) {
1692 MEMFS.ensureFlexible(node);
1693 var contents = node.contents;
1694 if (attr.size < contents.length) contents.length = attr.size;
1695 else while (attr.size > contents.length) contents.push(0);
1696 }
1697 },lookup:function (parent, name) {
1698 throw FS.genericErrors[ERRNO_CODES.ENOENT];
1699 },mknod:function (parent, name, mode, dev) {
1700 return MEMFS.createNode(parent, name, mode, dev);
1701 },rename:function (old_node, new_dir, new_name) {
1702 // if we're overwriting a directory at new_name, make sure it's empty.
1703 if (FS.isDir(old_node.mode)) {
1704 var new_node;
1705 try {
1706 new_node = FS.lookupNode(new_dir, new_name);
1707 } catch (e) {
1708 }
1709 if (new_node) {
1710 for (var i in new_node.contents) {
1711 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1712 }
1713 }
1714 }
1715 // do the internal rewiring
1716 delete old_node.parent.contents[old_node.name];
1717 old_node.name = new_name;
1718 new_dir.contents[new_name] = old_node;
1719 old_node.parent = new_dir;
1720 },unlink:function (parent, name) {
1721 delete parent.contents[name];
1722 },rmdir:function (parent, name) {
1723 var node = FS.lookupNode(parent, name);
1724 for (var i in node.contents) {
1725 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1726 }
1727 delete parent.contents[name];
1728 },readdir:function (node) {
1729 var entries = ['.', '..']
1730 for (var key in node.contents) {
1731 if (!node.contents.hasOwnProperty(key)) {
1732 continue;
1733 }
1734 entries.push(key);
1735 }
1736 return entries;
1737 },symlink:function (parent, newname, oldpath) {
1738 var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
1739 node.link = oldpath;
1740 return node;
1741 },readlink:function (node) {
1742 if (!FS.isLink(node.mode)) {
1743 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1744 }
1745 return node.link;
1746 }},stream_ops:{read:function (stream, buffer, offset, length, position) {
1747 var contents = stream.node.contents;
1748 if (position >= contents.length)
1749 return 0;
1750 var size = Math.min(contents.length - position, length);
1751 assert(size >= 0);
1752 if (size > 8 && contents.subarray) { // non-trivial, and typed array
1753 buffer.set(contents.subarray(position, position + size), offset);
1754 } else
1755 {
1756 for (var i = 0; i < size; i++) {
1757 buffer[offset + i] = contents[position + i];
1758 }
1759 }
1760 return size;
1761 },write:function (stream, buffer, offset, length, position, canOwn) {
1762 var node = stream.node;
1763 node.timestamp = Date.now();
1764 var contents = node.contents;
1765 if (length && contents.length === 0 && position === 0 && buffer.subarray) {
1766 // just replace it with the new data
1767 if (canOwn && offset === 0) {
1768 node.contents = buffer; // this could be a subarray of Emscripten HEAP, or allocated from some other source.
1769 node.contentMode = (buffer.buffer === HEAP8.buffer) ? MEMFS.CONTENT_OWNING : MEMFS.CONTENT_FIXED;
1770 } else {
1771 node.contents = new Uint8Array(buffer.subarray(offset, offset+length));
1772 node.contentMode = MEMFS.CONTENT_FIXED;
1773 }
1774 return length;
1775 }
1776 MEMFS.ensureFlexible(node);
1777 var contents = node.contents;
1778 while (contents.length < position) contents.push(0);
1779 for (var i = 0; i < length; i++) {
1780 contents[position + i] = buffer[offset + i];
1781 }
1782 return length;
1783 },llseek:function (stream, offset, whence) {
1784 var position = offset;
1785 if (whence === 1) { // SEEK_CUR.
1786 position += stream.position;
1787 } else if (whence === 2) { // SEEK_END.
1788 if (FS.isFile(stream.node.mode)) {
1789 position += stream.node.contents.length;
1790 }
1791 }
1792 if (position < 0) {
1793 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1794 }
1795 stream.ungotten = [];
1796 stream.position = position;
1797 return position;
1798 },allocate:function (stream, offset, length) {
1799 MEMFS.ensureFlexible(stream.node);
1800 var contents = stream.node.contents;
1801 var limit = offset + length;
1802 while (limit > contents.length) contents.push(0);
1803 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
1804 if (!FS.isFile(stream.node.mode)) {
1805 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1806 }
1807 var ptr;
1808 var allocated;
1809 var contents = stream.node.contents;
1810 // Only make a new copy when MAP_PRIVATE is specified.
1811 if ( !(flags & 2) &&
1812 (contents.buffer === buffer || contents.buffer === buffer.buffer) ) {
1813 // We can't emulate MAP_SHARED when the file is not backed by the buffer
1814 // we're mapping to (e.g. the HEAP buffer).
1815 allocated = false;
1816 ptr = contents.byteOffset;
1817 } else {
1818 // Try to avoid unnecessary slices.
1819 if (position > 0 || position + length < contents.length) {
1820 if (contents.subarray) {
1821 contents = contents.subarray(position, position + length);
1822 } else {
1823 contents = Array.prototype.slice.call(contents, position, position + length);
1824 }
1825 }
1826 allocated = true;
1827 ptr = _malloc(length);
1828 if (!ptr) {
1829 throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
1830 }
1831 buffer.set(contents, ptr);
1832 }
1833 return { ptr: ptr, allocated: allocated };
1834 }}};
1835
1836 var IDBFS={dbs:{},indexedDB:function () {
1837 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
1838 },DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function (mount) {
1839 // reuse all of the core MEMFS functionality
1840 return MEMFS.mount.apply(null, arguments);
1841 },syncfs:function (mount, populate, callback) {
1842 IDBFS.getLocalSet(mount, function(err, local) {
1843 if (err) return callback(err);
1844
1845 IDBFS.getRemoteSet(mount, function(err, remote) {
1846 if (err) return callback(err);
1847
1848 var src = populate ? remote : local;
1849 var dst = populate ? local : remote;
1850
1851 IDBFS.reconcile(src, dst, callback);
1852 });
1853 });
1854 },getDB:function (name, callback) {
1855 // check the cache first
1856 var db = IDBFS.dbs[name];
1857 if (db) {
1858 return callback(null, db);
1859 }
1860
1861 var req;
1862 try {
1863 req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
1864 } catch (e) {
1865 return callback(e);
1866 }
1867 req.onupgradeneeded = function(e) {
1868 var db = e.target.result;
1869 var transaction = e.target.transaction;
1870
1871 var fileStore;
1872
1873 if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
1874 fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
1875 } else {
1876 fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
1877 }
1878
1879 fileStore.createIndex('timestamp', 'timestamp', { unique: false });
1880 };
1881 req.onsuccess = function() {
1882 db = req.result;
1883
1884 // add to the cache
1885 IDBFS.dbs[name] = db;
1886 callback(null, db);
1887 };
1888 req.onerror = function() {
1889 callback(this.error);
1890 };
1891 },getLocalSet:function (mount, callback) {
1892 var entries = {};
1893
1894 function isRealDir(p) {
1895 return p !== '.' && p !== '..';
1896 };
1897 function toAbsolute(root) {
1898 return function(p) {
1899 return PATH.join2(root, p);
1900 }
1901 };
1902
1903 var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
1904
1905 while (check.length) {
1906 var path = check.pop();
1907 var stat;
1908
1909 try {
1910 stat = FS.stat(path);
1911 } catch (e) {
1912 return callback(e);
1913 }
1914
1915 if (FS.isDir(stat.mode)) {
1916 check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
1917 }
1918
1919 entries[path] = { timestamp: stat.mtime };
1920 }
1921
1922 return callback(null, { type: 'local', entries: entries });
1923 },getRemoteSet:function (mount, callback) {
1924 var entries = {};
1925
1926 IDBFS.getDB(mount.mountpoint, function(err, db) {
1927 if (err) return callback(err);
1928
1929 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
1930 transaction.onerror = function() { callback(this.error); };
1931
1932 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
1933 var index = store.index('timestamp');
1934
1935 index.openKeyCursor().onsuccess = function(event) {
1936 var cursor = event.target.result;
1937
1938 if (!cursor) {
1939 return callback(null, { type: 'remote', db: db, entries: entries });
1940 }
1941
1942 entries[cursor.primaryKey] = { timestamp: cursor.key };
1943
1944 cursor.continue();
1945 };
1946 });
1947 },loadLocalEntry:function (path, callback) {
1948 var stat, node;
1949
1950 try {
1951 var lookup = FS.lookupPath(path);
1952 node = lookup.node;
1953 stat = FS.stat(path);
1954 } catch (e) {
1955 return callback(e);
1956 }
1957
1958 if (FS.isDir(stat.mode)) {
1959 return callback(null, { timestamp: stat.mtime, mode: stat.mode });
1960 } else if (FS.isFile(stat.mode)) {
1961 return callback(null, { timestamp: stat.mtime, mode: stat.mode, contents: node.contents });
1962 } else {
1963 return callback(new Error('node type not supported'));
1964 }
1965 },storeLocalEntry:function (path, entry, callback) {
1966 try {
1967 if (FS.isDir(entry.mode)) {
1968 FS.mkdir(path, entry.mode);
1969 } else if (FS.isFile(entry.mode)) {
1970 FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: true });
1971 } else {
1972 return callback(new Error('node type not supported'));
1973 }
1974
1975 FS.utime(path, entry.timestamp, entry.timestamp);
1976 } catch (e) {
1977 return callback(e);
1978 }
1979
1980 callback(null);
1981 },removeLocalEntry:function (path, callback) {
1982 try {
1983 var lookup = FS.lookupPath(path);
1984 var stat = FS.stat(path);
1985
1986 if (FS.isDir(stat.mode)) {
1987 FS.rmdir(path);
1988 } else if (FS.isFile(stat.mode)) {
1989 FS.unlink(path);
1990 }
1991 } catch (e) {
1992 return callback(e);
1993 }
1994
1995 callback(null);
1996 },loadRemoteEntry:function (store, path, callback) {
1997 var req = store.get(path);
1998 req.onsuccess = function(event) { callback(null, event.target.result); };
1999 req.onerror = function() { callback(this.error); };
2000 },storeRemoteEntry:function (store, path, entry, callback) {
2001 var req = store.put(entry, path);
2002 req.onsuccess = function() { callback(null); };
2003 req.onerror = function() { callback(this.error); };
2004 },removeRemoteEntry:function (store, path, callback) {
2005 var req = store.delete(path);
2006 req.onsuccess = function() { callback(null); };
2007 req.onerror = function() { callback(this.error); };
2008 },reconcile:function (src, dst, callback) {
2009 var total = 0;
2010
2011 var create = [];
2012 Object.keys(src.entries).forEach(function (key) {
2013 var e = src.entries[key];
2014 var e2 = dst.entries[key];
2015 if (!e2 || e.timestamp > e2.timestamp) {
2016 create.push(key);
2017 total++;
2018 }
2019 });
2020
2021 var remove = [];
2022 Object.keys(dst.entries).forEach(function (key) {
2023 var e = dst.entries[key];
2024 var e2 = src.entries[key];
2025 if (!e2) {
2026 remove.push(key);
2027 total++;
2028 }
2029 });
2030
2031 if (!total) {
2032 return callback(null);
2033 }
2034
2035 var errored = false;
2036 var completed = 0;
2037 var db = src.type === 'remote' ? src.db : dst.db;
2038 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
2039 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2040
2041 function done(err) {
2042 if (err) {
2043 if (!done.errored) {
2044 done.errored = true;
2045 return callback(err);
2046 }
2047 return;
2048 }
2049 if (++completed >= total) {
2050 return callback(null);
2051 }
2052 };
2053
2054 transaction.onerror = function() { done(this.error); };
2055
2056 // sort paths in ascending order so directory entries are created
2057 // before the files inside them
2058 create.sort().forEach(function (path) {
2059 if (dst.type === 'local') {
2060 IDBFS.loadRemoteEntry(store, path, function (err, entry) {
2061 if (err) return done(err);
2062 IDBFS.storeLocalEntry(path, entry, done);
2063 });
2064 } else {
2065 IDBFS.loadLocalEntry(path, function (err, entry) {
2066 if (err) return done(err);
2067 IDBFS.storeRemoteEntry(store, path, entry, done);
2068 });
2069 }
2070 });
2071
2072 // sort paths in descending order so files are deleted before their
2073 // parent directories
2074 remove.sort().reverse().forEach(function(path) {
2075 if (dst.type === 'local') {
2076 IDBFS.removeLocalEntry(path, done);
2077 } else {
2078 IDBFS.removeRemoteEntry(store, path, done);
2079 }
2080 });
2081 }};
2082
2083 var NODEFS={isWindows:false,staticInit:function () {
2084 NODEFS.isWindows = !!process.platform.match(/^win/);
2085 },mount:function (mount) {
2086 assert(ENVIRONMENT_IS_NODE);
2087 return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
2088 },createNode:function (parent, name, mode, dev) {
2089 if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
2090 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2091 }
2092 var node = FS.createNode(parent, name, mode);
2093 node.node_ops = NODEFS.node_ops;
2094 node.stream_ops = NODEFS.stream_ops;
2095 return node;
2096 },getMode:function (path) {
2097 var stat;
2098 try {
2099 stat = fs.lstatSync(path);
2100 if (NODEFS.isWindows) {
2101 // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
2102 // propagate write bits to execute bits.
2103 stat.mode = stat.mode | ((stat.mode & 146) >> 1);
2104 }
2105 } catch (e) {
2106 if (!e.code) throw e;
2107 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2108 }
2109 return stat.mode;
2110 },realPath:function (node) {
2111 var parts = [];
2112 while (node.parent !== node) {
2113 parts.push(node.name);
2114 node = node.parent;
2115 }
2116 parts.push(node.mount.opts.root);
2117 parts.reverse();
2118 return PATH.join.apply(null, parts);
2119 },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) {
2120 if (flags in NODEFS.flagsToPermissionStringMap) {
2121 return NODEFS.flagsToPermissionStringMap[flags];
2122 } else {
2123 return flags;
2124 }
2125 },node_ops:{getattr:function (node) {
2126 var path = NODEFS.realPath(node);
2127 var stat;
2128 try {
2129 stat = fs.lstatSync(path);
2130 } catch (e) {
2131 if (!e.code) throw e;
2132 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2133 }
2134 // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
2135 // See http://support.microsoft.com/kb/140365
2136 if (NODEFS.isWindows && !stat.blksize) {
2137 stat.blksize = 4096;
2138 }
2139 if (NODEFS.isWindows && !stat.blocks) {
2140 stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
2141 }
2142 return {
2143 dev: stat.dev,
2144 ino: stat.ino,
2145 mode: stat.mode,
2146 nlink: stat.nlink,
2147 uid: stat.uid,
2148 gid: stat.gid,
2149 rdev: stat.rdev,
2150 size: stat.size,
2151 atime: stat.atime,
2152 mtime: stat.mtime,
2153 ctime: stat.ctime,
2154 blksize: stat.blksize,
2155 blocks: stat.blocks
2156 };
2157 },setattr:function (node, attr) {
2158 var path = NODEFS.realPath(node);
2159 try {
2160 if (attr.mode !== undefined) {
2161 fs.chmodSync(path, attr.mode);
2162 // update the common node structure mode as well
2163 node.mode = attr.mode;
2164 }
2165 if (attr.timestamp !== undefined) {
2166 var date = new Date(attr.timestamp);
2167 fs.utimesSync(path, date, date);
2168 }
2169 if (attr.size !== undefined) {
2170 fs.truncateSync(path, attr.size);
2171 }
2172 } catch (e) {
2173 if (!e.code) throw e;
2174 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2175 }
2176 },lookup:function (parent, name) {
2177 var path = PATH.join2(NODEFS.realPath(parent), name);
2178 var mode = NODEFS.getMode(path);
2179 return NODEFS.createNode(parent, name, mode);
2180 },mknod:function (parent, name, mode, dev) {
2181 var node = NODEFS.createNode(parent, name, mode, dev);
2182 // create the backing node for this in the fs root as well
2183 var path = NODEFS.realPath(node);
2184 try {
2185 if (FS.isDir(node.mode)) {
2186 fs.mkdirSync(path, node.mode);
2187 } else {
2188 fs.writeFileSync(path, '', { mode: node.mode });
2189 }
2190 } catch (e) {
2191 if (!e.code) throw e;
2192 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2193 }
2194 return node;
2195 },rename:function (oldNode, newDir, newName) {
2196 var oldPath = NODEFS.realPath(oldNode);
2197 var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
2198 try {
2199 fs.renameSync(oldPath, newPath);
2200 } catch (e) {
2201 if (!e.code) throw e;
2202 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2203 }
2204 },unlink:function (parent, name) {
2205 var path = PATH.join2(NODEFS.realPath(parent), name);
2206 try {
2207 fs.unlinkSync(path);
2208 } catch (e) {
2209 if (!e.code) throw e;
2210 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2211 }
2212 },rmdir:function (parent, name) {
2213 var path = PATH.join2(NODEFS.realPath(parent), name);
2214 try {
2215 fs.rmdirSync(path);
2216 } catch (e) {
2217 if (!e.code) throw e;
2218 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2219 }
2220 },readdir:function (node) {
2221 var path = NODEFS.realPath(node);
2222 try {
2223 return fs.readdirSync(path);
2224 } catch (e) {
2225 if (!e.code) throw e;
2226 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2227 }
2228 },symlink:function (parent, newName, oldPath) {
2229 var newPath = PATH.join2(NODEFS.realPath(parent), newName);
2230 try {
2231 fs.symlinkSync(oldPath, newPath);
2232 } catch (e) {
2233 if (!e.code) throw e;
2234 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2235 }
2236 },readlink:function (node) {
2237 var path = NODEFS.realPath(node);
2238 try {
2239 return fs.readlinkSync(path);
2240 } catch (e) {
2241 if (!e.code) throw e;
2242 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2243 }
2244 }},stream_ops:{open:function (stream) {
2245 var path = NODEFS.realPath(stream.node);
2246 try {
2247 if (FS.isFile(stream.node.mode)) {
2248 stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
2249 }
2250 } catch (e) {
2251 if (!e.code) throw e;
2252 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2253 }
2254 },close:function (stream) {
2255 try {
2256 if (FS.isFile(stream.node.mode) && stream.nfd) {
2257 fs.closeSync(stream.nfd);
2258 }
2259 } catch (e) {
2260 if (!e.code) throw e;
2261 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2262 }
2263 },read:function (stream, buffer, offset, length, position) {
2264 // FIXME this is terrible.
2265 var nbuffer = new Buffer(length);
2266 var res;
2267 try {
2268 res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
2269 } catch (e) {
2270 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2271 }
2272 if (res > 0) {
2273 for (var i = 0; i < res; i++) {
2274 buffer[offset + i] = nbuffer[i];
2275 }
2276 }
2277 return res;
2278 },write:function (stream, buffer, offset, length, position) {
2279 // FIXME this is terrible.
2280 var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
2281 var res;
2282 try {
2283 res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
2284 } catch (e) {
2285 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2286 }
2287 return res;
2288 },llseek:function (stream, offset, whence) {
2289 var position = offset;
2290 if (whence === 1) { // SEEK_CUR.
2291 position += stream.position;
2292 } else if (whence === 2) { // SEEK_END.
2293 if (FS.isFile(stream.node.mode)) {
2294 try {
2295 var stat = fs.fstatSync(stream.nfd);
2296 position += stat.size;
2297 } catch (e) {
2298 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2299 }
2300 }
2301 }
2302
2303 if (position < 0) {
2304 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2305 }
2306
2307 stream.position = position;
2308 return position;
2309 }}};
2310
2311 var _stdin=allocate(1, "i32*", ALLOC_STATIC);
2312
2313 var _stdout=allocate(1, "i32*", ALLOC_STATIC);
2314
2315 var _stderr=allocate(1, "i32*", ALLOC_STATIC);
2316
2317 function _fflush(stream) {
2318 // int fflush(FILE *stream);
2319 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fflush.html
2320 // we don't currently perform any user-space buffering of data
2321 }var FS={root:null,mounts:[],devices:[null],streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},handleFSError:function (e) {
2322 if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
2323 return ___setErrNo(e.errno);
2324 },lookupPath:function (path, opts) {
2325 path = PATH.resolve(FS.cwd(), path);
2326 opts = opts || {};
2327
2328 var defaults = {
2329 follow_mount: true,
2330 recurse_count: 0
2331 };
2332 for (var key in defaults) {
2333 if (opts[key] === undefined) {
2334 opts[key] = defaults[key];
2335 }
2336 }
2337
2338 if (opts.recurse_count > 8) { // max recursive lookup of 8
2339 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2340 }
2341
2342 // split the path
2343 var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2344 return !!p;
2345 }), false);
2346
2347 // start at the root
2348 var current = FS.root;
2349 var current_path = '/';
2350
2351 for (var i = 0; i < parts.length; i++) {
2352 var islast = (i === parts.length-1);
2353 if (islast && opts.parent) {
2354 // stop resolving
2355 break;
2356 }
2357
2358 current = FS.lookupNode(current, parts[i]);
2359 current_path = PATH.join2(current_path, parts[i]);
2360
2361 // jump to the mount's root node if this is a mountpoint
2362 if (FS.isMountpoint(current)) {
2363 if (!islast || (islast && opts.follow_mount)) {
2364 current = current.mounted.root;
2365 }
2366 }
2367
2368 // by default, lookupPath will not follow a symlink if it is the final path component.
2369 // setting opts.follow = true will override this behavior.
2370 if (!islast || opts.follow) {
2371 var count = 0;
2372 while (FS.isLink(current.mode)) {
2373 var link = FS.readlink(current_path);
2374 current_path = PATH.resolve(PATH.dirname(current_path), link);
2375
2376 var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
2377 current = lookup.node;
2378
2379 if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
2380 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2381 }
2382 }
2383 }
2384 }
2385
2386 return { path: current_path, node: current };
2387 },getPath:function (node) {
2388 var path;
2389 while (true) {
2390 if (FS.isRoot(node)) {
2391 var mount = node.mount.mountpoint;
2392 if (!path) return mount;
2393 return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
2394 }
2395 path = path ? node.name + '/' + path : node.name;
2396 node = node.parent;
2397 }
2398 },hashName:function (parentid, name) {
2399 var hash = 0;
2400
2401
2402 for (var i = 0; i < name.length; i++) {
2403 hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2404 }
2405 return ((parentid + hash) >>> 0) % FS.nameTable.length;
2406 },hashAddNode:function (node) {
2407 var hash = FS.hashName(node.parent.id, node.name);
2408 node.name_next = FS.nameTable[hash];
2409 FS.nameTable[hash] = node;
2410 },hashRemoveNode:function (node) {
2411 var hash = FS.hashName(node.parent.id, node.name);
2412 if (FS.nameTable[hash] === node) {
2413 FS.nameTable[hash] = node.name_next;
2414 } else {
2415 var current = FS.nameTable[hash];
2416 while (current) {
2417 if (current.name_next === node) {
2418 current.name_next = node.name_next;
2419 break;
2420 }
2421 current = current.name_next;
2422 }
2423 }
2424 },lookupNode:function (parent, name) {
2425 var err = FS.mayLookup(parent);
2426 if (err) {
2427 throw new FS.ErrnoError(err);
2428 }
2429 var hash = FS.hashName(parent.id, name);
2430 for (var node = FS.nameTable[hash]; node; node = node.name_next) {
2431 var nodeName = node.name;
2432 if (node.parent.id === parent.id && nodeName === name) {
2433 return node;
2434 }
2435 }
2436 // if we failed to find it in the cache, call into the VFS
2437 return FS.lookup(parent, name);
2438 },createNode:function (parent, name, mode, rdev) {
2439 if (!FS.FSNode) {
2440 FS.FSNode = function(parent, name, mode, rdev) {
2441 if (!parent) {
2442 parent = this; // root node sets parent to itself
2443 }
2444 this.parent = parent;
2445 this.mount = parent.mount;
2446 this.mounted = null;
2447 this.id = FS.nextInode++;
2448 this.name = name;
2449 this.mode = mode;
2450 this.node_ops = {};
2451 this.stream_ops = {};
2452 this.rdev = rdev;
2453 };
2454
2455 FS.FSNode.prototype = {};
2456
2457 // compatibility
2458 var readMode = 292 | 73;
2459 var writeMode = 146;
2460
2461 // NOTE we must use Object.defineProperties instead of individual calls to
2462 // Object.defineProperty in order to make closure compiler happy
2463 Object.defineProperties(FS.FSNode.prototype, {
2464 read: {
2465 get: function() { return (this.mode & readMode) === readMode; },
2466 set: function(val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
2467 },
2468 write: {
2469 get: function() { return (this.mode & writeMode) === writeMode; },
2470 set: function(val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
2471 },
2472 isFolder: {
2473 get: function() { return FS.isDir(this.mode); },
2474 },
2475 isDevice: {
2476 get: function() { return FS.isChrdev(this.mode); },
2477 },
2478 });
2479 }
2480
2481 var node = new FS.FSNode(parent, name, mode, rdev);
2482
2483 FS.hashAddNode(node);
2484
2485 return node;
2486 },destroyNode:function (node) {
2487 FS.hashRemoveNode(node);
2488 },isRoot:function (node) {
2489 return node === node.parent;
2490 },isMountpoint:function (node) {
2491 return !!node.mounted;
2492 },isFile:function (mode) {
2493 return (mode & 61440) === 32768;
2494 },isDir:function (mode) {
2495 return (mode & 61440) === 16384;
2496 },isLink:function (mode) {
2497 return (mode & 61440) === 40960;
2498 },isChrdev:function (mode) {
2499 return (mode & 61440) === 8192;
2500 },isBlkdev:function (mode) {
2501 return (mode & 61440) === 24576;
2502 },isFIFO:function (mode) {
2503 return (mode & 61440) === 4096;
2504 },isSocket:function (mode) {
2505 return (mode & 49152) === 49152;
2506 },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) {
2507 var flags = FS.flagModes[str];
2508 if (typeof flags === 'undefined') {
2509 throw new Error('Unknown file open mode: ' + str);
2510 }
2511 return flags;
2512 },flagsToPermissionString:function (flag) {
2513 var accmode = flag & 2097155;
2514 var perms = ['r', 'w', 'rw'][accmode];
2515 if ((flag & 512)) {
2516 perms += 'w';
2517 }
2518 return perms;
2519 },nodePermissions:function (node, perms) {
2520 if (FS.ignorePermissions) {
2521 return 0;
2522 }
2523 // return 0 if any user, group or owner bits are set.
2524 if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
2525 return ERRNO_CODES.EACCES;
2526 } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
2527 return ERRNO_CODES.EACCES;
2528 } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
2529 return ERRNO_CODES.EACCES;
2530 }
2531 return 0;
2532 },mayLookup:function (dir) {
2533 return FS.nodePermissions(dir, 'x');
2534 },mayCreate:function (dir, name) {
2535 try {
2536 var node = FS.lookupNode(dir, name);
2537 return ERRNO_CODES.EEXIST;
2538 } catch (e) {
2539 }
2540 return FS.nodePermissions(dir, 'wx');
2541 },mayDelete:function (dir, name, isdir) {
2542 var node;
2543 try {
2544 node = FS.lookupNode(dir, name);
2545 } catch (e) {
2546 return e.errno;
2547 }
2548 var err = FS.nodePermissions(dir, 'wx');
2549 if (err) {
2550 return err;
2551 }
2552 if (isdir) {
2553 if (!FS.isDir(node.mode)) {
2554 return ERRNO_CODES.ENOTDIR;
2555 }
2556 if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2557 return ERRNO_CODES.EBUSY;
2558 }
2559 } else {
2560 if (FS.isDir(node.mode)) {
2561 return ERRNO_CODES.EISDIR;
2562 }
2563 }
2564 return 0;
2565 },mayOpen:function (node, flags) {
2566 if (!node) {
2567 return ERRNO_CODES.ENOENT;
2568 }
2569 if (FS.isLink(node.mode)) {
2570 return ERRNO_CODES.ELOOP;
2571 } else if (FS.isDir(node.mode)) {
2572 if ((flags & 2097155) !== 0 || // opening for write
2573 (flags & 512)) {
2574 return ERRNO_CODES.EISDIR;
2575 }
2576 }
2577 return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
2578 },MAX_OPEN_FDS:4096,nextfd:function (fd_start, fd_end) {
2579 fd_start = fd_start || 0;
2580 fd_end = fd_end || FS.MAX_OPEN_FDS;
2581 for (var fd = fd_start; fd <= fd_end; fd++) {
2582 if (!FS.streams[fd]) {
2583 return fd;
2584 }
2585 }
2586 throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
2587 },getStream:function (fd) {
2588 return FS.streams[fd];
2589 },createStream:function (stream, fd_start, fd_end) {
2590 if (!FS.FSStream) {
2591 FS.FSStream = function(){};
2592 FS.FSStream.prototype = {};
2593 // compatibility
2594 Object.defineProperties(FS.FSStream.prototype, {
2595 object: {
2596 get: function() { return this.node; },
2597 set: function(val) { this.node = val; }
2598 },
2599 isRead: {
2600 get: function() { return (this.flags & 2097155) !== 1; }
2601 },
2602 isWrite: {
2603 get: function() { return (this.flags & 2097155) !== 0; }
2604 },
2605 isAppend: {
2606 get: function() { return (this.flags & 1024); }
2607 }
2608 });
2609 }
2610 if (0) {
2611 // reuse the object
2612 stream.__proto__ = FS.FSStream.prototype;
2613 } else {
2614 var newStream = new FS.FSStream();
2615 for (var p in stream) {
2616 newStream[p] = stream[p];
2617 }
2618 stream = newStream;
2619 }
2620 var fd = FS.nextfd(fd_start, fd_end);
2621 stream.fd = fd;
2622 FS.streams[fd] = stream;
2623 return stream;
2624 },closeStream:function (fd) {
2625 FS.streams[fd] = null;
2626 },getStreamFromPtr:function (ptr) {
2627 return FS.streams[ptr - 1];
2628 },getPtrForStream:function (stream) {
2629 return stream ? stream.fd + 1 : 0;
2630 },chrdev_stream_ops:{open:function (stream) {
2631 var device = FS.getDevice(stream.node.rdev);
2632 // override node's stream ops with the device's
2633 stream.stream_ops = device.stream_ops;
2634 // forward the open call
2635 if (stream.stream_ops.open) {
2636 stream.stream_ops.open(stream);
2637 }
2638 },llseek:function () {
2639 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
2640 }},major:function (dev) {
2641 return ((dev) >> 8);
2642 },minor:function (dev) {
2643 return ((dev) & 0xff);
2644 },makedev:function (ma, mi) {
2645 return ((ma) << 8 | (mi));
2646 },registerDevice:function (dev, ops) {
2647 FS.devices[dev] = { stream_ops: ops };
2648 },getDevice:function (dev) {
2649 return FS.devices[dev];
2650 },getMounts:function (mount) {
2651 var mounts = [];
2652 var check = [mount];
2653
2654 while (check.length) {
2655 var m = check.pop();
2656
2657 mounts.push(m);
2658
2659 check.push.apply(check, m.mounts);
2660 }
2661
2662 return mounts;
2663 },syncfs:function (populate, callback) {
2664 if (typeof(populate) === 'function') {
2665 callback = populate;
2666 populate = false;
2667 }
2668
2669 var mounts = FS.getMounts(FS.root.mount);
2670 var completed = 0;
2671
2672 function done(err) {
2673 if (err) {
2674 if (!done.errored) {
2675 done.errored = true;
2676 return callback(err);
2677 }
2678 return;
2679 }
2680 if (++completed >= mounts.length) {
2681 callback(null);
2682 }
2683 };
2684
2685 // sync all mounts
2686 mounts.forEach(function (mount) {
2687 if (!mount.type.syncfs) {
2688 return done(null);
2689 }
2690 mount.type.syncfs(mount, populate, done);
2691 });
2692 },mount:function (type, opts, mountpoint) {
2693 var root = mountpoint === '/';
2694 var pseudo = !mountpoint;
2695 var node;
2696
2697 if (root && FS.root) {
2698 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2699 } else if (!root && !pseudo) {
2700 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2701
2702 mountpoint = lookup.path; // use the absolute path
2703 node = lookup.node;
2704
2705 if (FS.isMountpoint(node)) {
2706 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2707 }
2708
2709 if (!FS.isDir(node.mode)) {
2710 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2711 }
2712 }
2713
2714 var mount = {
2715 type: type,
2716 opts: opts,
2717 mountpoint: mountpoint,
2718 mounts: []
2719 };
2720
2721 // create a root node for the fs
2722 var mountRoot = type.mount(mount);
2723 mountRoot.mount = mount;
2724 mount.root = mountRoot;
2725
2726 if (root) {
2727 FS.root = mountRoot;
2728 } else if (node) {
2729 // set as a mountpoint
2730 node.mounted = mount;
2731
2732 // add the new mount to the current mount's children
2733 if (node.mount) {
2734 node.mount.mounts.push(mount);
2735 }
2736 }
2737
2738 return mountRoot;
2739 },unmount:function (mountpoint) {
2740 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2741
2742 if (!FS.isMountpoint(lookup.node)) {
2743 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2744 }
2745
2746 // destroy the nodes for this mount, and all its child mounts
2747 var node = lookup.node;
2748 var mount = node.mounted;
2749 var mounts = FS.getMounts(mount);
2750
2751 Object.keys(FS.nameTable).forEach(function (hash) {
2752 var current = FS.nameTable[hash];
2753
2754 while (current) {
2755 var next = current.name_next;
2756
2757 if (mounts.indexOf(current.mount) !== -1) {
2758 FS.destroyNode(current);
2759 }
2760
2761 current = next;
2762 }
2763 });
2764
2765 // no longer a mountpoint
2766 node.mounted = null;
2767
2768 // remove this mount from the child mounts
2769 var idx = node.mount.mounts.indexOf(mount);
2770 assert(idx !== -1);
2771 node.mount.mounts.splice(idx, 1);
2772 },lookup:function (parent, name) {
2773 return parent.node_ops.lookup(parent, name);
2774 },mknod:function (path, mode, dev) {
2775 var lookup = FS.lookupPath(path, { parent: true });
2776 var parent = lookup.node;
2777 var name = PATH.basename(path);
2778 var err = FS.mayCreate(parent, name);
2779 if (err) {
2780 throw new FS.ErrnoError(err);
2781 }
2782 if (!parent.node_ops.mknod) {
2783 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2784 }
2785 return parent.node_ops.mknod(parent, name, mode, dev);
2786 },create:function (path, mode) {
2787 mode = mode !== undefined ? mode : 438 /* 0666 */;
2788 mode &= 4095;
2789 mode |= 32768;
2790 return FS.mknod(path, mode, 0);
2791 },mkdir:function (path, mode) {
2792 mode = mode !== undefined ? mode : 511 /* 0777 */;
2793 mode &= 511 | 512;
2794 mode |= 16384;
2795 return FS.mknod(path, mode, 0);
2796 },mkdev:function (path, mode, dev) {
2797 if (typeof(dev) === 'undefined') {
2798 dev = mode;
2799 mode = 438 /* 0666 */;
2800 }
2801 mode |= 8192;
2802 return FS.mknod(path, mode, dev);
2803 },symlink:function (oldpath, newpath) {
2804 var lookup = FS.lookupPath(newpath, { parent: true });
2805 var parent = lookup.node;
2806 var newname = PATH.basename(newpath);
2807 var err = FS.mayCreate(parent, newname);
2808 if (err) {
2809 throw new FS.ErrnoError(err);
2810 }
2811 if (!parent.node_ops.symlink) {
2812 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2813 }
2814 return parent.node_ops.symlink(parent, newname, oldpath);
2815 },rename:function (old_path, new_path) {
2816 var old_dirname = PATH.dirname(old_path);
2817 var new_dirname = PATH.dirname(new_path);
2818 var old_name = PATH.basename(old_path);
2819 var new_name = PATH.basename(new_path);
2820 // parents must exist
2821 var lookup, old_dir, new_dir;
2822 try {
2823 lookup = FS.lookupPath(old_path, { parent: true });
2824 old_dir = lookup.node;
2825 lookup = FS.lookupPath(new_path, { parent: true });
2826 new_dir = lookup.node;
2827 } catch (e) {
2828 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2829 }
2830 // need to be part of the same mount
2831 if (old_dir.mount !== new_dir.mount) {
2832 throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
2833 }
2834 // source must exist
2835 var old_node = FS.lookupNode(old_dir, old_name);
2836 // old path should not be an ancestor of the new path
2837 var relative = PATH.relative(old_path, new_dirname);
2838 if (relative.charAt(0) !== '.') {
2839 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2840 }
2841 // new path should not be an ancestor of the old path
2842 relative = PATH.relative(new_path, old_dirname);
2843 if (relative.charAt(0) !== '.') {
2844 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
2845 }
2846 // see if the new path already exists
2847 var new_node;
2848 try {
2849 new_node = FS.lookupNode(new_dir, new_name);
2850 } catch (e) {
2851 // not fatal
2852 }
2853 // early out if nothing needs to change
2854 if (old_node === new_node) {
2855 return;
2856 }
2857 // we'll need to delete the old entry
2858 var isdir = FS.isDir(old_node.mode);
2859 var err = FS.mayDelete(old_dir, old_name, isdir);
2860 if (err) {
2861 throw new FS.ErrnoError(err);
2862 }
2863 // need delete permissions if we'll be overwriting.
2864 // need create permissions if new doesn't already exist.
2865 err = new_node ?
2866 FS.mayDelete(new_dir, new_name, isdir) :
2867 FS.mayCreate(new_dir, new_name);
2868 if (err) {
2869 throw new FS.ErrnoError(err);
2870 }
2871 if (!old_dir.node_ops.rename) {
2872 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2873 }
2874 if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
2875 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2876 }
2877 // if we are going to change the parent, check write permissions
2878 if (new_dir !== old_dir) {
2879 err = FS.nodePermissions(old_dir, 'w');
2880 if (err) {
2881 throw new FS.ErrnoError(err);
2882 }
2883 }
2884 // remove the node from the lookup hash
2885 FS.hashRemoveNode(old_node);
2886 // do the underlying fs rename
2887 try {
2888 old_dir.node_ops.rename(old_node, new_dir, new_name);
2889 } catch (e) {
2890 throw e;
2891 } finally {
2892 // add the node back to the hash (in case node_ops.rename
2893 // changed its name)
2894 FS.hashAddNode(old_node);
2895 }
2896 },rmdir:function (path) {
2897 var lookup = FS.lookupPath(path, { parent: true });
2898 var parent = lookup.node;
2899 var name = PATH.basename(path);
2900 var node = FS.lookupNode(parent, name);
2901 var err = FS.mayDelete(parent, name, true);
2902 if (err) {
2903 throw new FS.ErrnoError(err);
2904 }
2905 if (!parent.node_ops.rmdir) {
2906 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2907 }
2908 if (FS.isMountpoint(node)) {
2909 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2910 }
2911 parent.node_ops.rmdir(parent, name);
2912 FS.destroyNode(node);
2913 },readdir:function (path) {
2914 var lookup = FS.lookupPath(path, { follow: true });
2915 var node = lookup.node;
2916 if (!node.node_ops.readdir) {
2917 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2918 }
2919 return node.node_ops.readdir(node);
2920 },unlink:function (path) {
2921 var lookup = FS.lookupPath(path, { parent: true });
2922 var parent = lookup.node;
2923 var name = PATH.basename(path);
2924 var node = FS.lookupNode(parent, name);
2925 var err = FS.mayDelete(parent, name, false);
2926 if (err) {
2927 // POSIX says unlink should set EPERM, not EISDIR
2928 if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
2929 throw new FS.ErrnoError(err);
2930 }
2931 if (!parent.node_ops.unlink) {
2932 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2933 }
2934 if (FS.isMountpoint(node)) {
2935 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2936 }
2937 parent.node_ops.unlink(parent, name);
2938 FS.destroyNode(node);
2939 },readlink:function (path) {
2940 var lookup = FS.lookupPath(path);
2941 var link = lookup.node;
2942 if (!link.node_ops.readlink) {
2943 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2944 }
2945 return link.node_ops.readlink(link);
2946 },stat:function (path, dontFollow) {
2947 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2948 var node = lookup.node;
2949 if (!node.node_ops.getattr) {
2950 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2951 }
2952 return node.node_ops.getattr(node);
2953 },lstat:function (path) {
2954 return FS.stat(path, true);
2955 },chmod:function (path, mode, dontFollow) {
2956 var node;
2957 if (typeof path === 'string') {
2958 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2959 node = lookup.node;
2960 } else {
2961 node = path;
2962 }
2963 if (!node.node_ops.setattr) {
2964 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2965 }
2966 node.node_ops.setattr(node, {
2967 mode: (mode & 4095) | (node.mode & ~4095),
2968 timestamp: Date.now()
2969 });
2970 },lchmod:function (path, mode) {
2971 FS.chmod(path, mode, true);
2972 },fchmod:function (fd, mode) {
2973 var stream = FS.getStream(fd);
2974 if (!stream) {
2975 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2976 }
2977 FS.chmod(stream.node, mode);
2978 },chown:function (path, uid, gid, dontFollow) {
2979 var node;
2980 if (typeof path === 'string') {
2981 var lookup = FS.lookupPath(path, { follow: !dontFollow });
2982 node = lookup.node;
2983 } else {
2984 node = path;
2985 }
2986 if (!node.node_ops.setattr) {
2987 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2988 }
2989 node.node_ops.setattr(node, {
2990 timestamp: Date.now()
2991 // we ignore the uid / gid for now
2992 });
2993 },lchown:function (path, uid, gid) {
2994 FS.chown(path, uid, gid, true);
2995 },fchown:function (fd, uid, gid) {
2996 var stream = FS.getStream(fd);
2997 if (!stream) {
2998 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
2999 }
3000 FS.chown(stream.node, uid, gid);
3001 },truncate:function (path, len) {
3002 if (len < 0) {
3003 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3004 }
3005 var node;
3006 if (typeof path === 'string') {
3007 var lookup = FS.lookupPath(path, { follow: true });
3008 node = lookup.node;
3009 } else {
3010 node = path;
3011 }
3012 if (!node.node_ops.setattr) {
3013 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3014 }
3015 if (FS.isDir(node.mode)) {
3016 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3017 }
3018 if (!FS.isFile(node.mode)) {
3019 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3020 }
3021 var err = FS.nodePermissions(node, 'w');
3022 if (err) {
3023 throw new FS.ErrnoError(err);
3024 }
3025 node.node_ops.setattr(node, {
3026 size: len,
3027 timestamp: Date.now()
3028 });
3029 },ftruncate:function (fd, len) {
3030 var stream = FS.getStream(fd);
3031 if (!stream) {
3032 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3033 }
3034 if ((stream.flags & 2097155) === 0) {
3035 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3036 }
3037 FS.truncate(stream.node, len);
3038 },utime:function (path, atime, mtime) {
3039 var lookup = FS.lookupPath(path, { follow: true });
3040 var node = lookup.node;
3041 node.node_ops.setattr(node, {
3042 timestamp: Math.max(atime, mtime)
3043 });
3044 },open:function (path, flags, mode, fd_start, fd_end) {
3045 flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3046 mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3047 if ((flags & 64)) {
3048 mode = (mode & 4095) | 32768;
3049 } else {
3050 mode = 0;
3051 }
3052 var node;
3053 if (typeof path === 'object') {
3054 node = path;
3055 } else {
3056 path = PATH.normalize(path);
3057 try {
3058 var lookup = FS.lookupPath(path, {
3059 follow: !(flags & 131072)
3060 });
3061 node = lookup.node;
3062 } catch (e) {
3063 // ignore
3064 }
3065 }
3066 // perhaps we need to create the node
3067 if ((flags & 64)) {
3068 if (node) {
3069 // if O_CREAT and O_EXCL are set, error out if the node already exists
3070 if ((flags & 128)) {
3071 throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
3072 }
3073 } else {
3074 // node doesn't exist, try to create it
3075 node = FS.mknod(path, mode, 0);
3076 }
3077 }
3078 if (!node) {
3079 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3080 }
3081 // can't truncate a device
3082 if (FS.isChrdev(node.mode)) {
3083 flags &= ~512;
3084 }
3085 // check permissions
3086 var err = FS.mayOpen(node, flags);
3087 if (err) {
3088 throw new FS.ErrnoError(err);
3089 }
3090 // do truncation if necessary
3091 if ((flags & 512)) {
3092 FS.truncate(node, 0);
3093 }
3094 // we've already handled these, don't pass down to the underlying vfs
3095 flags &= ~(128 | 512);
3096
3097 // register the stream with the filesystem
3098 var stream = FS.createStream({
3099 node: node,
3100 path: FS.getPath(node), // we want the absolute path to the node
3101 flags: flags,
3102 seekable: true,
3103 position: 0,
3104 stream_ops: node.stream_ops,
3105 // used by the file family libc calls (fopen, fwrite, ferror, etc.)
3106 ungotten: [],
3107 error: false
3108 }, fd_start, fd_end);
3109 // call the new stream's open function
3110 if (stream.stream_ops.open) {
3111 stream.stream_ops.open(stream);
3112 }
3113 if (Module['logReadFiles'] && !(flags & 1)) {
3114 if (!FS.readFiles) FS.readFiles = {};
3115 if (!(path in FS.readFiles)) {
3116 FS.readFiles[path] = 1;
3117 Module['printErr']('read file: ' + path);
3118 }
3119 }
3120 return stream;
3121 },close:function (stream) {
3122 try {
3123 if (stream.stream_ops.close) {
3124 stream.stream_ops.close(stream);
3125 }
3126 } catch (e) {
3127 throw e;
3128 } finally {
3129 FS.closeStream(stream.fd);
3130 }
3131 },llseek:function (stream, offset, whence) {
3132 if (!stream.seekable || !stream.stream_ops.llseek) {
3133 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3134 }
3135 return stream.stream_ops.llseek(stream, offset, whence);
3136 },read:function (stream, buffer, offset, length, position) {
3137 if (length < 0 || position < 0) {
3138 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3139 }
3140 if ((stream.flags & 2097155) === 1) {
3141 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3142 }
3143 if (FS.isDir(stream.node.mode)) {
3144 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3145 }
3146 if (!stream.stream_ops.read) {
3147 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3148 }
3149 var seeking = true;
3150 if (typeof position === 'undefined') {
3151 position = stream.position;
3152 seeking = false;
3153 } else if (!stream.seekable) {
3154 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3155 }
3156 var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
3157 if (!seeking) stream.position += bytesRead;
3158 return bytesRead;
3159 },write:function (stream, buffer, offset, length, position, canOwn) {
3160 if (length < 0 || position < 0) {
3161 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3162 }
3163 if ((stream.flags & 2097155) === 0) {
3164 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3165 }
3166 if (FS.isDir(stream.node.mode)) {
3167 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3168 }
3169 if (!stream.stream_ops.write) {
3170 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3171 }
3172 var seeking = true;
3173 if (typeof position === 'undefined') {
3174 position = stream.position;
3175 seeking = false;
3176 } else if (!stream.seekable) {
3177 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3178 }
3179 if (stream.flags & 1024) {
3180 // seek to the end before writing in append mode
3181 FS.llseek(stream, 0, 2);
3182 }
3183 var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
3184 if (!seeking) stream.position += bytesWritten;
3185 return bytesWritten;
3186 },allocate:function (stream, offset, length) {
3187 if (offset < 0 || length <= 0) {
3188 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3189 }
3190 if ((stream.flags & 2097155) === 0) {
3191 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3192 }
3193 if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
3194 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3195 }
3196 if (!stream.stream_ops.allocate) {
3197 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
3198 }
3199 stream.stream_ops.allocate(stream, offset, length);
3200 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
3201 // TODO if PROT is PROT_WRITE, make sure we have write access
3202 if ((stream.flags & 2097155) === 1) {
3203 throw new FS.ErrnoError(ERRNO_CODES.EACCES);
3204 }
3205 if (!stream.stream_ops.mmap) {
3206 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3207 }
3208 return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
3209 },ioctl:function (stream, cmd, arg) {
3210 if (!stream.stream_ops.ioctl) {
3211 throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
3212 }
3213 return stream.stream_ops.ioctl(stream, cmd, arg);
3214 },readFile:function (path, opts) {
3215 opts = opts || {};
3216 opts.flags = opts.flags || 'r';
3217 opts.encoding = opts.encoding || 'binary';
3218 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3219 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3220 }
3221 var ret;
3222 var stream = FS.open(path, opts.flags);
3223 var stat = FS.stat(path);
3224 var length = stat.size;
3225 var buf = new Uint8Array(length);
3226 FS.read(stream, buf, 0, length, 0);
3227 if (opts.encoding === 'utf8') {
3228 ret = '';
3229 var utf8 = new Runtime.UTF8Processor();
3230 for (var i = 0; i < length; i++) {
3231 ret += utf8.processCChar(buf[i]);
3232 }
3233 } else if (opts.encoding === 'binary') {
3234 ret = buf;
3235 }
3236 FS.close(stream);
3237 return ret;
3238 },writeFile:function (path, data, opts) {
3239 opts = opts || {};
3240 opts.flags = opts.flags || 'w';
3241 opts.encoding = opts.encoding || 'utf8';
3242 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3243 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3244 }
3245 var stream = FS.open(path, opts.flags, opts.mode);
3246 if (opts.encoding === 'utf8') {
3247 var utf8 = new Runtime.UTF8Processor();
3248 var buf = new Uint8Array(utf8.processJSString(data));
3249 FS.write(stream, buf, 0, buf.length, 0, opts.canOwn);
3250 } else if (opts.encoding === 'binary') {
3251 FS.write(stream, data, 0, data.length, 0, opts.canOwn);
3252 }
3253 FS.close(stream);
3254 },cwd:function () {
3255 return FS.currentPath;
3256 },chdir:function (path) {
3257 var lookup = FS.lookupPath(path, { follow: true });
3258 if (!FS.isDir(lookup.node.mode)) {
3259 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3260 }
3261 var err = FS.nodePermissions(lookup.node, 'x');
3262 if (err) {
3263 throw new FS.ErrnoError(err);
3264 }
3265 FS.currentPath = lookup.path;
3266 },createDefaultDirectories:function () {
3267 FS.mkdir('/tmp');
3268 },createDefaultDevices:function () {
3269 // create /dev
3270 FS.mkdir('/dev');
3271 // setup /dev/null
3272 FS.registerDevice(FS.makedev(1, 3), {
3273 read: function() { return 0; },
3274 write: function() { return 0; }
3275 });
3276 FS.mkdev('/dev/null', FS.makedev(1, 3));
3277 // setup /dev/tty and /dev/tty1
3278 // stderr needs to print output using Module['printErr']
3279 // so we register a second tty just for it.
3280 TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
3281 TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
3282 FS.mkdev('/dev/tty', FS.makedev(5, 0));
3283 FS.mkdev('/dev/tty1', FS.makedev(6, 0));
3284 // we're not going to emulate the actual shm device,
3285 // just create the tmp dirs that reside in it commonly
3286 FS.mkdir('/dev/shm');
3287 FS.mkdir('/dev/shm/tmp');
3288 },createStandardStreams:function () {
3289 // TODO deprecate the old functionality of a single
3290 // input / output callback and that utilizes FS.createDevice
3291 // and instead require a unique set of stream ops
3292
3293 // by default, we symlink the standard streams to the
3294 // default tty devices. however, if the standard streams
3295 // have been overwritten we create a unique device for
3296 // them instead.
3297 if (Module['stdin']) {
3298 FS.createDevice('/dev', 'stdin', Module['stdin']);
3299 } else {
3300 FS.symlink('/dev/tty', '/dev/stdin');
3301 }
3302 if (Module['stdout']) {
3303 FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3304 } else {
3305 FS.symlink('/dev/tty', '/dev/stdout');
3306 }
3307 if (Module['stderr']) {
3308 FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3309 } else {
3310 FS.symlink('/dev/tty1', '/dev/stderr');
3311 }
3312
3313 // open default streams for the stdin, stdout and stderr devices
3314 var stdin = FS.open('/dev/stdin', 'r');
3315 HEAP32[((_stdin)>>2)]=FS.getPtrForStream(stdin);
3316 assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
3317
3318 var stdout = FS.open('/dev/stdout', 'w');
3319 HEAP32[((_stdout)>>2)]=FS.getPtrForStream(stdout);
3320 assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
3321
3322 var stderr = FS.open('/dev/stderr', 'w');
3323 HEAP32[((_stderr)>>2)]=FS.getPtrForStream(stderr);
3324 assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
3325 },ensureErrnoError:function () {
3326 if (FS.ErrnoError) return;
3327 FS.ErrnoError = function ErrnoError(errno) {
3328 this.errno = errno;
3329 for (var key in ERRNO_CODES) {
3330 if (ERRNO_CODES[key] === errno) {
3331 this.code = key;
3332 break;
3333 }
3334 }
3335 this.message = ERRNO_MESSAGES[errno];
3336 };
3337 FS.ErrnoError.prototype = new Error();
3338 FS.ErrnoError.prototype.constructor = FS.ErrnoError;
3339 // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
3340 [ERRNO_CODES.ENOENT].forEach(function(code) {
3341 FS.genericErrors[code] = new FS.ErrnoError(code);
3342 FS.genericErrors[code].stack = '<generic error, no stack>';
3343 });
3344 },staticInit:function () {
3345 FS.ensureErrnoError();
3346
3347 FS.nameTable = new Array(4096);
3348
3349 FS.mount(MEMFS, {}, '/');
3350
3351 FS.createDefaultDirectories();
3352 FS.createDefaultDevices();
3353 },init:function (input, output, error) {
3354 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)');
3355 FS.init.initialized = true;
3356
3357 FS.ensureErrnoError();
3358
3359 // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
3360 Module['stdin'] = input || Module['stdin'];
3361 Module['stdout'] = output || Module['stdout'];
3362 Module['stderr'] = error || Module['stderr'];
3363
3364 FS.createStandardStreams();
3365 },quit:function () {
3366 FS.init.initialized = false;
3367 for (var i = 0; i < FS.streams.length; i++) {
3368 var stream = FS.streams[i];
3369 if (!stream) {
3370 continue;
3371 }
3372 FS.close(stream);
3373 }
3374 },getMode:function (canRead, canWrite) {
3375 var mode = 0;
3376 if (canRead) mode |= 292 | 73;
3377 if (canWrite) mode |= 146;
3378 return mode;
3379 },joinPath:function (parts, forceRelative) {
3380 var path = PATH.join.apply(null, parts);
3381 if (forceRelative && path[0] == '/') path = path.substr(1);
3382 return path;
3383 },absolutePath:function (relative, base) {
3384 return PATH.resolve(base, relative);
3385 },standardizePath:function (path) {
3386 return PATH.normalize(path);
3387 },findObject:function (path, dontResolveLastLink) {
3388 var ret = FS.analyzePath(path, dontResolveLastLink);
3389 if (ret.exists) {
3390 return ret.object;
3391 } else {
3392 ___setErrNo(ret.error);
3393 return null;
3394 }
3395 },analyzePath:function (path, dontResolveLastLink) {
3396 // operate from within the context of the symlink's target
3397 try {
3398 var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3399 path = lookup.path;
3400 } catch (e) {
3401 }
3402 var ret = {
3403 isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
3404 parentExists: false, parentPath: null, parentObject: null
3405 };
3406 try {
3407 var lookup = FS.lookupPath(path, { parent: true });
3408 ret.parentExists = true;
3409 ret.parentPath = lookup.path;
3410 ret.parentObject = lookup.node;
3411 ret.name = PATH.basename(path);
3412 lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3413 ret.exists = true;
3414 ret.path = lookup.path;
3415 ret.object = lookup.node;
3416 ret.name = lookup.node.name;
3417 ret.isRoot = lookup.path === '/';
3418 } catch (e) {
3419 ret.error = e.errno;
3420 };
3421 return ret;
3422 },createFolder:function (parent, name, canRead, canWrite) {
3423 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3424 var mode = FS.getMode(canRead, canWrite);
3425 return FS.mkdir(path, mode);
3426 },createPath:function (parent, path, canRead, canWrite) {
3427 parent = typeof parent === 'string' ? parent : FS.getPath(parent);
3428 var parts = path.split('/').reverse();
3429 while (parts.length) {
3430 var part = parts.pop();
3431 if (!part) continue;
3432 var current = PATH.join2(parent, part);
3433 try {
3434 FS.mkdir(current);
3435 } catch (e) {
3436 // ignore EEXIST
3437 }
3438 parent = current;
3439 }
3440 return current;
3441 },createFile:function (parent, name, properties, canRead, canWrite) {
3442 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3443 var mode = FS.getMode(canRead, canWrite);
3444 return FS.create(path, mode);
3445 },createDataFile:function (parent, name, data, canRead, canWrite, canOwn) {
3446 var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
3447 var mode = FS.getMode(canRead, canWrite);
3448 var node = FS.create(path, mode);
3449 if (data) {
3450 if (typeof data === 'string') {
3451 var arr = new Array(data.length);
3452 for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
3453 data = arr;
3454 }
3455 // make sure we can write to the file
3456 FS.chmod(node, mode | 146);
3457 var stream = FS.open(node, 'w');
3458 FS.write(stream, data, 0, data.length, 0, canOwn);
3459 FS.close(stream);
3460 FS.chmod(node, mode);
3461 }
3462 return node;
3463 },createDevice:function (parent, name, input, output) {
3464 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3465 var mode = FS.getMode(!!input, !!output);
3466 if (!FS.createDevice.major) FS.createDevice.major = 64;
3467 var dev = FS.makedev(FS.createDevice.major++, 0);
3468 // Create a fake device that a set of stream ops to emulate
3469 // the old behavior.
3470 FS.registerDevice(dev, {
3471 open: function(stream) {
3472 stream.seekable = false;
3473 },
3474 close: function(stream) {
3475 // flush any pending line data
3476 if (output && output.buffer && output.buffer.length) {
3477 output(10);
3478 }
3479 },
3480 read: function(stream, buffer, offset, length, pos /* ignored */) {
3481 var bytesRead = 0;
3482 for (var i = 0; i < length; i++) {
3483 var result;
3484 try {
3485 result = input();
3486 } catch (e) {
3487 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3488 }
3489 if (result === undefined && bytesRead === 0) {
3490 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
3491 }
3492 if (result === null || result === undefined) break;
3493 bytesRead++;
3494 buffer[offset+i] = result;
3495 }
3496 if (bytesRead) {
3497 stream.node.timestamp = Date.now();
3498 }
3499 return bytesRead;
3500 },
3501 write: function(stream, buffer, offset, length, pos) {
3502 for (var i = 0; i < length; i++) {
3503 try {
3504 output(buffer[offset+i]);
3505 } catch (e) {
3506 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3507 }
3508 }
3509 if (length) {
3510 stream.node.timestamp = Date.now();
3511 }
3512 return i;
3513 }
3514 });
3515 return FS.mkdev(path, mode, dev);
3516 },createLink:function (parent, name, target, canRead, canWrite) {
3517 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3518 return FS.symlink(target, path);
3519 },forceLoadFile:function (obj) {
3520 if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
3521 var success = true;
3522 if (typeof XMLHttpRequest !== 'undefined') {
3523 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.");
3524 } else if (Module['read']) {
3525 // Command-line.
3526 try {
3527 // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
3528 // read() will try to parse UTF8.
3529 obj.contents = intArrayFromString(Module['read'](obj.url), true);
3530 } catch (e) {
3531 success = false;
3532 }
3533 } else {
3534 throw new Error('Cannot load without read() or XMLHttpRequest.');
3535 }
3536 if (!success) ___setErrNo(ERRNO_CODES.EIO);
3537 return success;
3538 },createLazyFile:function (parent, name, url, canRead, canWrite) {
3539 // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
3540 function LazyUint8Array() {
3541 this.lengthKnown = false;
3542 this.chunks = []; // Loaded chunks. Index is the chunk number
3543 }
3544 LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
3545 if (idx > this.length-1 || idx < 0) {
3546 return undefined;
3547 }
3548 var chunkOffset = idx % this.chunkSize;
3549 var chunkNum = Math.floor(idx / this.chunkSize);
3550 return this.getter(chunkNum)[chunkOffset];
3551 }
3552 LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
3553 this.getter = getter;
3554 }
3555 LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
3556 // Find length
3557 var xhr = new XMLHttpRequest();
3558 xhr.open('HEAD', url, false);
3559 xhr.send(null);
3560 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3561 var datalength = Number(xhr.getResponseHeader("Content-length"));
3562 var header;
3563 var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
3564 var chunkSize = 1024*1024; // Chunk size in bytes
3565
3566 if (!hasByteServing) chunkSize = datalength;
3567
3568 // Function to get a range from the remote URL.
3569 var doXHR = (function(from, to) {
3570 if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
3571 if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
3572
3573 // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
3574 var xhr = new XMLHttpRequest();
3575 xhr.open('GET', url, false);
3576 if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
3577
3578 // Some hints to the browser that we want binary data.
3579 if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
3580 if (xhr.overrideMimeType) {
3581 xhr.overrideMimeType('text/plain; charset=x-user-defined');
3582 }
3583
3584 xhr.send(null);
3585 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3586 if (xhr.response !== undefined) {
3587 return new Uint8Array(xhr.response || []);
3588 } else {
3589 return intArrayFromString(xhr.responseText || '', true);
3590 }
3591 });
3592 var lazyArray = this;
3593 lazyArray.setDataGetter(function(chunkNum) {
3594 var start = chunkNum * chunkSize;
3595 var end = (chunkNum+1) * chunkSize - 1; // including this byte
3596 end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
3597 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
3598 lazyArray.chunks[chunkNum] = doXHR(start, end);
3599 }
3600 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3601 return lazyArray.chunks[chunkNum];
3602 });
3603
3604 this._length = datalength;
3605 this._chunkSize = chunkSize;
3606 this.lengthKnown = true;
3607 }
3608 if (typeof XMLHttpRequest !== 'undefined') {
3609 if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
3610 var lazyArray = new LazyUint8Array();
3611 Object.defineProperty(lazyArray, "length", {
3612 get: function() {
3613 if(!this.lengthKnown) {
3614 this.cacheLength();
3615 }
3616 return this._length;
3617 }
3618 });
3619 Object.defineProperty(lazyArray, "chunkSize", {
3620 get: function() {
3621 if(!this.lengthKnown) {
3622 this.cacheLength();
3623 }
3624 return this._chunkSize;
3625 }
3626 });
3627
3628 var properties = { isDevice: false, contents: lazyArray };
3629 } else {
3630 var properties = { isDevice: false, url: url };
3631 }
3632
3633 var node = FS.createFile(parent, name, properties, canRead, canWrite);
3634 // This is a total hack, but I want to get this lazy file code out of the
3635 // core of MEMFS. If we want to keep this lazy file concept I feel it should
3636 // be its own thin LAZYFS proxying calls to MEMFS.
3637 if (properties.contents) {
3638 node.contents = properties.contents;
3639 } else if (properties.url) {
3640 node.contents = null;
3641 node.url = properties.url;
3642 }
3643 // override each stream op with one that tries to force load the lazy file first
3644 var stream_ops = {};
3645 var keys = Object.keys(node.stream_ops);
3646 keys.forEach(function(key) {
3647 var fn = node.stream_ops[key];
3648 stream_ops[key] = function forceLoadLazyFile() {
3649 if (!FS.forceLoadFile(node)) {
3650 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3651 }
3652 return fn.apply(null, arguments);
3653 };
3654 });
3655 // use a custom read function
3656 stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
3657 if (!FS.forceLoadFile(node)) {
3658 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3659 }
3660 var contents = stream.node.contents;
3661 if (position >= contents.length)
3662 return 0;
3663 var size = Math.min(contents.length - position, length);
3664 assert(size >= 0);
3665 if (contents.slice) { // normal array
3666 for (var i = 0; i < size; i++) {
3667 buffer[offset + i] = contents[position + i];
3668 }
3669 } else {
3670 for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
3671 buffer[offset + i] = contents.get(position + i);
3672 }
3673 }
3674 return size;
3675 };
3676 node.stream_ops = stream_ops;
3677 return node;
3678 },createPreloadedFile:function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn) {
3679 Browser.init();
3680 // TODO we should allow people to just pass in a complete filename instead
3681 // of parent and name being that we just join them anyways
3682 var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
3683 function processData(byteArray) {
3684 function finish(byteArray) {
3685 if (!dontCreateFile) {
3686 FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
3687 }
3688 if (onload) onload();
3689 removeRunDependency('cp ' + fullname);
3690 }
3691 var handled = false;
3692 Module['preloadPlugins'].forEach(function(plugin) {
3693 if (handled) return;
3694 if (plugin['canHandle'](fullname)) {
3695 plugin['handle'](byteArray, fullname, finish, function() {
3696 if (onerror) onerror();
3697 removeRunDependency('cp ' + fullname);
3698 });
3699 handled = true;
3700 }
3701 });
3702 if (!handled) finish(byteArray);
3703 }
3704 addRunDependency('cp ' + fullname);
3705 if (typeof url == 'string') {
3706 Browser.asyncLoad(url, function(byteArray) {
3707 processData(byteArray);
3708 }, onerror);
3709 } else {
3710 processData(url);
3711 }
3712 },indexedDB:function () {
3713 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
3714 },DB_NAME:function () {
3715 return 'EM_FS_' + window.location.pathname;
3716 },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function (paths, onload, onerror) {
3717 onload = onload || function(){};
3718 onerror = onerror || function(){};
3719 var indexedDB = FS.indexedDB();
3720 try {
3721 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3722 } catch (e) {
3723 return onerror(e);
3724 }
3725 openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
3726 console.log('creating db');
3727 var db = openRequest.result;
3728 db.createObjectStore(FS.DB_STORE_NAME);
3729 };
3730 openRequest.onsuccess = function openRequest_onsuccess() {
3731 var db = openRequest.result;
3732 var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
3733 var files = transaction.objectStore(FS.DB_STORE_NAME);
3734 var ok = 0, fail = 0, total = paths.length;
3735 function finish() {
3736 if (fail == 0) onload(); else onerror();
3737 }
3738 paths.forEach(function(path) {
3739 var putRequest = files.put(FS.analyzePath(path).object.contents, path);
3740 putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
3741 putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
3742 });
3743 transaction.onerror = onerror;
3744 };
3745 openRequest.onerror = onerror;
3746 },loadFilesFromDB:function (paths, onload, onerror) {
3747 onload = onload || function(){};
3748 onerror = onerror || function(){};
3749 var indexedDB = FS.indexedDB();
3750 try {
3751 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3752 } catch (e) {
3753 return onerror(e);
3754 }
3755 openRequest.onupgradeneeded = onerror; // no database to load from
3756 openRequest.onsuccess = function openRequest_onsuccess() {
3757 var db = openRequest.result;
3758 try {
3759 var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
3760 } catch(e) {
3761 onerror(e);
3762 return;
3763 }
3764 var files = transaction.objectStore(FS.DB_STORE_NAME);
3765 var ok = 0, fail = 0, total = paths.length;
3766 function finish() {
3767 if (fail == 0) onload(); else onerror();
3768 }
3769 paths.forEach(function(path) {
3770 var getRequest = files.get(path);
3771 getRequest.onsuccess = function getRequest_onsuccess() {
3772 if (FS.analyzePath(path).exists) {
3773 FS.unlink(path);
3774 }
3775 FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
3776 ok++;
3777 if (ok + fail == total) finish();
3778 };
3779 getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
3780 });
3781 transaction.onerror = onerror;
3782 };
3783 openRequest.onerror = onerror;
3784 }};var PATH={splitPath:function (filename) {
3785 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3786 return splitPathRe.exec(filename).slice(1);
3787 },normalizeArray:function (parts, allowAboveRoot) {
3788 // if the path tries to go above the root, `up` ends up > 0
3789 var up = 0;
3790 for (var i = parts.length - 1; i >= 0; i--) {
3791 var last = parts[i];
3792 if (last === '.') {
3793 parts.splice(i, 1);
3794 } else if (last === '..') {
3795 parts.splice(i, 1);
3796 up++;
3797 } else if (up) {
3798 parts.splice(i, 1);
3799 up--;
3800 }
3801 }
3802 // if the path is allowed to go above the root, restore leading ..s
3803 if (allowAboveRoot) {
3804 for (; up--; up) {
3805 parts.unshift('..');
3806 }
3807 }
3808 return parts;
3809 },normalize:function (path) {
3810 var isAbsolute = path.charAt(0) === '/',
3811 trailingSlash = path.substr(-1) === '/';
3812 // Normalize the path
3813 path = PATH.normalizeArray(path.split('/').filter(function(p) {
3814 return !!p;
3815 }), !isAbsolute).join('/');
3816 if (!path && !isAbsolute) {
3817 path = '.';
3818 }
3819 if (path && trailingSlash) {
3820 path += '/';
3821 }
3822 return (isAbsolute ? '/' : '') + path;
3823 },dirname:function (path) {
3824 var result = PATH.splitPath(path),
3825 root = result[0],
3826 dir = result[1];
3827 if (!root && !dir) {
3828 // No dirname whatsoever
3829 return '.';
3830 }
3831 if (dir) {
3832 // It has a dirname, strip trailing slash
3833 dir = dir.substr(0, dir.length - 1);
3834 }
3835 return root + dir;
3836 },basename:function (path) {
3837 // EMSCRIPTEN return '/'' for '/', not an empty string
3838 if (path === '/') return '/';
3839 var lastSlash = path.lastIndexOf('/');
3840 if (lastSlash === -1) return path;
3841 return path.substr(lastSlash+1);
3842 },extname:function (path) {
3843 return PATH.splitPath(path)[3];
3844 },join:function () {
3845 var paths = Array.prototype.slice.call(arguments, 0);
3846 return PATH.normalize(paths.join('/'));
3847 },join2:function (l, r) {
3848 return PATH.normalize(l + '/' + r);
3849 },resolve:function () {
3850 var resolvedPath = '',
3851 resolvedAbsolute = false;
3852 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3853 var path = (i >= 0) ? arguments[i] : FS.cwd();
3854 // Skip empty and invalid entries
3855 if (typeof path !== 'string') {
3856 throw new TypeError('Arguments to path.resolve must be strings');
3857 } else if (!path) {
3858 continue;
3859 }
3860 resolvedPath = path + '/' + resolvedPath;
3861 resolvedAbsolute = path.charAt(0) === '/';
3862 }
3863 // At this point the path should be resolved to a full absolute path, but
3864 // handle relative paths to be safe (might happen when process.cwd() fails)
3865 resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
3866 return !!p;
3867 }), !resolvedAbsolute).join('/');
3868 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3869 },relative:function (from, to) {
3870 from = PATH.resolve(from).substr(1);
3871 to = PATH.resolve(to).substr(1);
3872 function trim(arr) {
3873 var start = 0;
3874 for (; start < arr.length; start++) {
3875 if (arr[start] !== '') break;
3876 }
3877 var end = arr.length - 1;
3878 for (; end >= 0; end--) {
3879 if (arr[end] !== '') break;
3880 }
3881 if (start > end) return [];
3882 return arr.slice(start, end - start + 1);
3883 }
3884 var fromParts = trim(from.split('/'));
3885 var toParts = trim(to.split('/'));
3886 var length = Math.min(fromParts.length, toParts.length);
3887 var samePartsLength = length;
3888 for (var i = 0; i < length; i++) {
3889 if (fromParts[i] !== toParts[i]) {
3890 samePartsLength = i;
3891 break;
3892 }
3893 }
3894 var outputParts = [];
3895 for (var i = samePartsLength; i < fromParts.length; i++) {
3896 outputParts.push('..');
3897 }
3898 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3899 return outputParts.join('/');
3900 }};var Browser={mainLoop:{scheduler:null,method:"",shouldPause:false,paused:false,queue:[],pause:function () {
3901 Browser.mainLoop.shouldPause = true;
3902 },resume:function () {
3903 if (Browser.mainLoop.paused) {
3904 Browser.mainLoop.paused = false;
3905 Browser.mainLoop.scheduler();
3906 }
3907 Browser.mainLoop.shouldPause = false;
3908 },updateStatus:function () {
3909 if (Module['setStatus']) {
3910 var message = Module['statusMessage'] || 'Please wait...';
3911 var remaining = Browser.mainLoop.remainingBlockers;
3912 var expected = Browser.mainLoop.expectedBlockers;
3913 if (remaining) {
3914 if (remaining < expected) {
3915 Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
3916 } else {
3917 Module['setStatus'](message);
3918 }
3919 } else {
3920 Module['setStatus']('');
3921 }
3922 }
3923 }},isFullScreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function () {
3924 if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
3925
3926 if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
3927 Browser.initted = true;
3928
3929 try {
3930 new Blob();
3931 Browser.hasBlobConstructor = true;
3932 } catch(e) {
3933 Browser.hasBlobConstructor = false;
3934 console.log("warning: no blob constructor, cannot create blobs with mimetypes");
3935 }
3936 Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
3937 Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
3938 if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
3939 console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
3940 Module.noImageDecoding = true;
3941 }
3942
3943 // Support for plugins that can process preloaded files. You can add more of these to
3944 // your app by creating and appending to Module.preloadPlugins.
3945 //
3946 // Each plugin is asked if it can handle a file based on the file's name. If it can,
3947 // it is given the file's raw data. When it is done, it calls a callback with the file's
3948 // (possibly modified) data. For example, a plugin might decompress a file, or it
3949 // might create some side data structure for use later (like an Image element, etc.).
3950
3951 var imagePlugin = {};
3952 imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
3953 return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
3954 };
3955 imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
3956 var b = null;
3957 if (Browser.hasBlobConstructor) {
3958 try {
3959 b = new Blob([byteArray], { type: Browser.getMimetype(name) });
3960 if (b.size !== byteArray.length) { // Safari bug #118630
3961 // Safari's Blob can only take an ArrayBuffer
3962 b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
3963 }
3964 } catch(e) {
3965 Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
3966 }
3967 }
3968 if (!b) {
3969 var bb = new Browser.BlobBuilder();
3970 bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
3971 b = bb.getBlob();
3972 }
3973 var url = Browser.URLObject.createObjectURL(b);
3974 var img = new Image();
3975 img.onload = function img_onload() {
3976 assert(img.complete, 'Image ' + name + ' could not be decoded');
3977 var canvas = document.createElement('canvas');
3978 canvas.width = img.width;
3979 canvas.height = img.height;
3980 var ctx = canvas.getContext('2d');
3981 ctx.drawImage(img, 0, 0);
3982 Module["preloadedImages"][name] = canvas;
3983 Browser.URLObject.revokeObjectURL(url);
3984 if (onload) onload(byteArray);
3985 };
3986 img.onerror = function img_onerror(event) {
3987 console.log('Image ' + url + ' could not be decoded');
3988 if (onerror) onerror();
3989 };
3990 img.src = url;
3991 };
3992 Module['preloadPlugins'].push(imagePlugin);
3993
3994 var audioPlugin = {};
3995 audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
3996 return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
3997 };
3998 audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
3999 var done = false;
4000 function finish(audio) {
4001 if (done) return;
4002 done = true;
4003 Module["preloadedAudios"][name] = audio;
4004 if (onload) onload(byteArray);
4005 }
4006 function fail() {
4007 if (done) return;
4008 done = true;
4009 Module["preloadedAudios"][name] = new Audio(); // empty shim
4010 if (onerror) onerror();
4011 }
4012 if (Browser.hasBlobConstructor) {
4013 try {
4014 var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4015 } catch(e) {
4016 return fail();
4017 }
4018 var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
4019 var audio = new Audio();
4020 audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
4021 audio.onerror = function audio_onerror(event) {
4022 if (done) return;
4023 console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
4024 function encode64(data) {
4025 var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4026 var PAD = '=';
4027 var ret = '';
4028 var leftchar = 0;
4029 var leftbits = 0;
4030 for (var i = 0; i < data.length; i++) {
4031 leftchar = (leftchar << 8) | data[i];
4032 leftbits += 8;
4033 while (leftbits >= 6) {
4034 var curr = (leftchar >> (leftbits-6)) & 0x3f;
4035 leftbits -= 6;
4036 ret += BASE[curr];
4037 }
4038 }
4039 if (leftbits == 2) {
4040 ret += BASE[(leftchar&3) << 4];
4041 ret += PAD + PAD;
4042 } else if (leftbits == 4) {
4043 ret += BASE[(leftchar&0xf) << 2];
4044 ret += PAD;
4045 }
4046 return ret;
4047 }
4048 audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
4049 finish(audio); // we don't wait for confirmation this worked - but it's worth trying
4050 };
4051 audio.src = url;
4052 // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
4053 Browser.safeSetTimeout(function() {
4054 finish(audio); // try to use it even though it is not necessarily ready to play
4055 }, 10000);
4056 } else {
4057 return fail();
4058 }
4059 };
4060 Module['preloadPlugins'].push(audioPlugin);
4061
4062 // Canvas event setup
4063
4064 var canvas = Module['canvas'];
4065
4066 // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
4067 // Module['forcedAspectRatio'] = 4 / 3;
4068
4069 canvas.requestPointerLock = canvas['requestPointerLock'] ||
4070 canvas['mozRequestPointerLock'] ||
4071 canvas['webkitRequestPointerLock'] ||
4072 canvas['msRequestPointerLock'] ||
4073 function(){};
4074 canvas.exitPointerLock = document['exitPointerLock'] ||
4075 document['mozExitPointerLock'] ||
4076 document['webkitExitPointerLock'] ||
4077 document['msExitPointerLock'] ||
4078 function(){}; // no-op if function does not exist
4079 canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
4080
4081 function pointerLockChange() {
4082 Browser.pointerLock = document['pointerLockElement'] === canvas ||
4083 document['mozPointerLockElement'] === canvas ||
4084 document['webkitPointerLockElement'] === canvas ||
4085 document['msPointerLockElement'] === canvas;
4086 }
4087
4088 document.addEventListener('pointerlockchange', pointerLockChange, false);
4089 document.addEventListener('mozpointerlockchange', pointerLockChange, false);
4090 document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
4091 document.addEventListener('mspointerlockchange', pointerLockChange, false);
4092
4093 if (Module['elementPointerLock']) {
4094 canvas.addEventListener("click", function(ev) {
4095 if (!Browser.pointerLock && canvas.requestPointerLock) {
4096 canvas.requestPointerLock();
4097 ev.preventDefault();
4098 }
4099 }, false);
4100 }
4101 },createContext:function (canvas, useWebGL, setInModule, webGLContextAttributes) {
4102 var ctx;
4103 var errorInfo = '?';
4104 function onContextCreationError(event) {
4105 errorInfo = event.statusMessage || errorInfo;
4106 }
4107 try {
4108 if (useWebGL) {
4109 var contextAttributes = {
4110 antialias: false,
4111 alpha: false
4112 };
4113
4114 if (webGLContextAttributes) {
4115 for (var attribute in webGLContextAttributes) {
4116 contextAttributes[attribute] = webGLContextAttributes[attribute];
4117 }
4118 }
4119
4120
4121 canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
4122 try {
4123 ['experimental-webgl', 'webgl'].some(function(webglId) {
4124 return ctx = canvas.getContext(webglId, contextAttributes);
4125 });
4126 } finally {
4127 canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
4128 }
4129 } else {
4130 ctx = canvas.getContext('2d');
4131 }
4132 if (!ctx) throw ':(';
4133 } catch (e) {
4134 Module.print('Could not create canvas: ' + [errorInfo, e]);
4135 return null;
4136 }
4137 if (useWebGL) {
4138 // Set the background of the WebGL canvas to black
4139 canvas.style.backgroundColor = "black";
4140
4141 // Warn on context loss
4142 canvas.addEventListener('webglcontextlost', function(event) {
4143 alert('WebGL context lost. You will need to reload the page.');
4144 }, false);
4145 }
4146 if (setInModule) {
4147 GLctx = Module.ctx = ctx;
4148 Module.useWebGL = useWebGL;
4149 Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
4150 Browser.init();
4151 }
4152 return ctx;
4153 },destroyContext:function (canvas, useWebGL, setInModule) {},fullScreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullScreen:function (lockPointer, resizeCanvas) {
4154 Browser.lockPointer = lockPointer;
4155 Browser.resizeCanvas = resizeCanvas;
4156 if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
4157 if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
4158
4159 var canvas = Module['canvas'];
4160 function fullScreenChange() {
4161 Browser.isFullScreen = false;
4162 var canvasContainer = canvas.parentNode;
4163 if ((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
4164 document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
4165 document['fullScreenElement'] || document['fullscreenElement'] ||
4166 document['msFullScreenElement'] || document['msFullscreenElement'] ||
4167 document['webkitCurrentFullScreenElement']) === canvasContainer) {
4168 canvas.cancelFullScreen = document['cancelFullScreen'] ||
4169 document['mozCancelFullScreen'] ||
4170 document['webkitCancelFullScreen'] ||
4171 document['msExitFullscreen'] ||
4172 document['exitFullscreen'] ||
4173 function() {};
4174 canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
4175 if (Browser.lockPointer) canvas.requestPointerLock();
4176 Browser.isFullScreen = true;
4177 if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
4178 } else {
4179
4180 // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
4181 canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
4182 canvasContainer.parentNode.removeChild(canvasContainer);
4183
4184 if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
4185 }
4186 if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScreen);
4187 Browser.updateCanvasDimensions(canvas);
4188 }
4189
4190 if (!Browser.fullScreenHandlersInstalled) {
4191 Browser.fullScreenHandlersInstalled = true;
4192 document.addEventListener('fullscreenchange', fullScreenChange, false);
4193 document.addEventListener('mozfullscreenchange', fullScreenChange, false);
4194 document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
4195 document.addEventListener('MSFullscreenChange', fullScreenChange, false);
4196 }
4197
4198 // 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
4199 var canvasContainer = document.createElement("div");
4200 canvas.parentNode.insertBefore(canvasContainer, canvas);
4201 canvasContainer.appendChild(canvas);
4202
4203 // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
4204 canvasContainer.requestFullScreen = canvasContainer['requestFullScreen'] ||
4205 canvasContainer['mozRequestFullScreen'] ||
4206 canvasContainer['msRequestFullscreen'] ||
4207 (canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
4208 canvasContainer.requestFullScreen();
4209 },requestAnimationFrame:function requestAnimationFrame(func) {
4210 if (typeof window === 'undefined') { // Provide fallback to setTimeout if window is undefined (e.g. in Node.js)
4211 setTimeout(func, 1000/60);
4212 } else {
4213 if (!window.requestAnimationFrame) {
4214 window.requestAnimationFrame = window['requestAnimationFrame'] ||
4215 window['mozRequestAnimationFrame'] ||
4216 window['webkitRequestAnimationFrame'] ||
4217 window['msRequestAnimationFrame'] ||
4218 window['oRequestAnimationFrame'] ||
4219 window['setTimeout'];
4220 }
4221 window.requestAnimationFrame(func);
4222 }
4223 },safeCallback:function (func) {
4224 return function() {
4225 if (!ABORT) return func.apply(null, arguments);
4226 };
4227 },safeRequestAnimationFrame:function (func) {
4228 return Browser.requestAnimationFrame(function() {
4229 if (!ABORT) func();
4230 });
4231 },safeSetTimeout:function (func, timeout) {
4232 return setTimeout(function() {
4233 if (!ABORT) func();
4234 }, timeout);
4235 },safeSetInterval:function (func, timeout) {
4236 return setInterval(function() {
4237 if (!ABORT) func();
4238 }, timeout);
4239 },getMimetype:function (name) {
4240 return {
4241 'jpg': 'image/jpeg',
4242 'jpeg': 'image/jpeg',
4243 'png': 'image/png',
4244 'bmp': 'image/bmp',
4245 'ogg': 'audio/ogg',
4246 'wav': 'audio/wav',
4247 'mp3': 'audio/mpeg'
4248 }[name.substr(name.lastIndexOf('.')+1)];
4249 },getUserMedia:function (func) {
4250 if(!window.getUserMedia) {
4251 window.getUserMedia = navigator['getUserMedia'] ||
4252 navigator['mozGetUserMedia'];
4253 }
4254 window.getUserMedia(func);
4255 },getMovementX:function (event) {
4256 return event['movementX'] ||
4257 event['mozMovementX'] ||
4258 event['webkitMovementX'] ||
4259 0;
4260 },getMovementY:function (event) {
4261 return event['movementY'] ||
4262 event['mozMovementY'] ||
4263 event['webkitMovementY'] ||
4264 0;
4265 },getMouseWheelDelta:function (event) {
4266 return Math.max(-1, Math.min(1, event.type === 'DOMMouseScroll' ? event.detail : -event.wheelDelta));
4267 },mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,calculateMouseEvent:function (event) { // event should be mousemove, mousedown or mouseup
4268 if (Browser.pointerLock) {
4269 // When the pointer is locked, calculate the coordinates
4270 // based on the movement of the mouse.
4271 // Workaround for Firefox bug 764498
4272 if (event.type != 'mousemove' &&
4273 ('mozMovementX' in event)) {
4274 Browser.mouseMovementX = Browser.mouseMovementY = 0;
4275 } else {
4276 Browser.mouseMovementX = Browser.getMovementX(event);
4277 Browser.mouseMovementY = Browser.getMovementY(event);
4278 }
4279
4280 // check if SDL is available
4281 if (typeof SDL != "undefined") {
4282 Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
4283 Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
4284 } else {
4285 // just add the mouse delta to the current absolut mouse position
4286 // FIXME: ideally this should be clamped against the canvas size and zero
4287 Browser.mouseX += Browser.mouseMovementX;
4288 Browser.mouseY += Browser.mouseMovementY;
4289 }
4290 } else {
4291 // Otherwise, calculate the movement based on the changes
4292 // in the coordinates.
4293 var rect = Module["canvas"].getBoundingClientRect();
4294 var x, y;
4295
4296 // Neither .scrollX or .pageXOffset are defined in a spec, but
4297 // we prefer .scrollX because it is currently in a spec draft.
4298 // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
4299 var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
4300 var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
4301 if (event.type == 'touchstart' ||
4302 event.type == 'touchend' ||
4303 event.type == 'touchmove') {
4304 var t = event.touches.item(0);
4305 if (t) {
4306 x = t.pageX - (scrollX + rect.left);
4307 y = t.pageY - (scrollY + rect.top);
4308 } else {
4309 return;
4310 }
4311 } else {
4312 x = event.pageX - (scrollX + rect.left);
4313 y = event.pageY - (scrollY + rect.top);
4314 }
4315
4316 // the canvas might be CSS-scaled compared to its backbuffer;
4317 // SDL-using content will want mouse coordinates in terms
4318 // of backbuffer units.
4319 var cw = Module["canvas"].width;
4320 var ch = Module["canvas"].height;
4321 x = x * (cw / rect.width);
4322 y = y * (ch / rect.height);
4323
4324 Browser.mouseMovementX = x - Browser.mouseX;
4325 Browser.mouseMovementY = y - Browser.mouseY;
4326 Browser.mouseX = x;
4327 Browser.mouseY = y;
4328 }
4329 },xhrLoad:function (url, onload, onerror) {
4330 var xhr = new XMLHttpRequest();
4331 xhr.open('GET', url, true);
4332 xhr.responseType = 'arraybuffer';
4333 xhr.onload = function xhr_onload() {
4334 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
4335 onload(xhr.response);
4336 } else {
4337 onerror();
4338 }
4339 };
4340 xhr.onerror = onerror;
4341 xhr.send(null);
4342 },asyncLoad:function (url, onload, onerror, noRunDep) {
4343 Browser.xhrLoad(url, function(arrayBuffer) {
4344 assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
4345 onload(new Uint8Array(arrayBuffer));
4346 if (!noRunDep) removeRunDependency('al ' + url);
4347 }, function(event) {
4348 if (onerror) {
4349 onerror();
4350 } else {
4351 throw 'Loading data file "' + url + '" failed.';
4352 }
4353 });
4354 if (!noRunDep) addRunDependency('al ' + url);
4355 },resizeListeners:[],updateResizeListeners:function () {
4356 var canvas = Module['canvas'];
4357 Browser.resizeListeners.forEach(function(listener) {
4358 listener(canvas.width, canvas.height);
4359 });
4360 },setCanvasSize:function (width, height, noUpdates) {
4361 var canvas = Module['canvas'];
4362 Browser.updateCanvasDimensions(canvas, width, height);
4363 if (!noUpdates) Browser.updateResizeListeners();
4364 },windowedWidth:0,windowedHeight:0,setFullScreenCanvasSize:function () {
4365 // check if SDL is available
4366 if (typeof SDL != "undefined") {
4367 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
4368 flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
4369 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
4370 }
4371 Browser.updateResizeListeners();
4372 },setWindowedCanvasSize:function () {
4373 // check if SDL is available
4374 if (typeof SDL != "undefined") {
4375 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
4376 flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
4377 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
4378 }
4379 Browser.updateResizeListeners();
4380 },updateCanvasDimensions:function (canvas, wNative, hNative) {
4381 if (wNative && hNative) {
4382 canvas.widthNative = wNative;
4383 canvas.heightNative = hNative;
4384 } else {
4385 wNative = canvas.widthNative;
4386 hNative = canvas.heightNative;
4387 }
4388 var w = wNative;
4389 var h = hNative;
4390 if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
4391 if (w/h < Module['forcedAspectRatio']) {
4392 w = Math.round(h * Module['forcedAspectRatio']);
4393 } else {
4394 h = Math.round(w / Module['forcedAspectRatio']);
4395 }
4396 }
4397 if (((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
4398 document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
4399 document['fullScreenElement'] || document['fullscreenElement'] ||
4400 document['msFullScreenElement'] || document['msFullscreenElement'] ||
4401 document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
4402 var factor = Math.min(screen.width / w, screen.height / h);
4403 w = Math.round(w * factor);
4404 h = Math.round(h * factor);
4405 }
4406 if (Browser.resizeCanvas) {
4407 if (canvas.width != w) canvas.width = w;
4408 if (canvas.height != h) canvas.height = h;
4409 if (typeof canvas.style != 'undefined') {
4410 canvas.style.removeProperty( "width");
4411 canvas.style.removeProperty("height");
4412 }
4413 } else {
4414 if (canvas.width != wNative) canvas.width = wNative;
4415 if (canvas.height != hNative) canvas.height = hNative;
4416 if (typeof canvas.style != 'undefined') {
4417 if (w != wNative || h != hNative) {
4418 canvas.style.setProperty( "width", w + "px", "important");
4419 canvas.style.setProperty("height", h + "px", "important");
4420 } else {
4421 canvas.style.removeProperty( "width");
4422 canvas.style.removeProperty("height");
4423 }
4424 }
4425 }
4426 }};
4427
4428
4429
4430
4431
4432
4433
4434 function _mkport() { throw 'TODO' }var SOCKFS={mount:function (mount) {
4435 return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
4436 },createSocket:function (family, type, protocol) {
4437 var streaming = type == 1;
4438 if (protocol) {
4439 assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
4440 }
4441
4442 // create our internal socket structure
4443 var sock = {
4444 family: family,
4445 type: type,
4446 protocol: protocol,
4447 server: null,
4448 peers: {},
4449 pending: [],
4450 recv_queue: [],
4451 sock_ops: SOCKFS.websocket_sock_ops
4452 };
4453
4454 // create the filesystem node to store the socket structure
4455 var name = SOCKFS.nextname();
4456 var node = FS.createNode(SOCKFS.root, name, 49152, 0);
4457 node.sock = sock;
4458
4459 // and the wrapping stream that enables library functions such
4460 // as read and write to indirectly interact with the socket
4461 var stream = FS.createStream({
4462 path: name,
4463 node: node,
4464 flags: FS.modeStringToFlags('r+'),
4465 seekable: false,
4466 stream_ops: SOCKFS.stream_ops
4467 });
4468
4469 // map the new stream to the socket structure (sockets have a 1:1
4470 // relationship with a stream)
4471 sock.stream = stream;
4472
4473 return sock;
4474 },getSocket:function (fd) {
4475 var stream = FS.getStream(fd);
4476 if (!stream || !FS.isSocket(stream.node.mode)) {
4477 return null;
4478 }
4479 return stream.node.sock;
4480 },stream_ops:{poll:function (stream) {
4481 var sock = stream.node.sock;
4482 return sock.sock_ops.poll(sock);
4483 },ioctl:function (stream, request, varargs) {
4484 var sock = stream.node.sock;
4485 return sock.sock_ops.ioctl(sock, request, varargs);
4486 },read:function (stream, buffer, offset, length, position /* ignored */) {
4487 var sock = stream.node.sock;
4488 var msg = sock.sock_ops.recvmsg(sock, length);
4489 if (!msg) {
4490 // socket is closed
4491 return 0;
4492 }
4493 buffer.set(msg.buffer, offset);
4494 return msg.buffer.length;
4495 },write:function (stream, buffer, offset, length, position /* ignored */) {
4496 var sock = stream.node.sock;
4497 return sock.sock_ops.sendmsg(sock, buffer, offset, length);
4498 },close:function (stream) {
4499 var sock = stream.node.sock;
4500 sock.sock_ops.close(sock);
4501 }},nextname:function () {
4502 if (!SOCKFS.nextname.current) {
4503 SOCKFS.nextname.current = 0;
4504 }
4505 return 'socket[' + (SOCKFS.nextname.current++) + ']';
4506 },websocket_sock_ops:{createPeer:function (sock, addr, port) {
4507 var ws;
4508
4509 if (typeof addr === 'object') {
4510 ws = addr;
4511 addr = null;
4512 port = null;
4513 }
4514
4515 if (ws) {
4516 // for sockets that've already connected (e.g. we're the server)
4517 // we can inspect the _socket property for the address
4518 if (ws._socket) {
4519 addr = ws._socket.remoteAddress;
4520 port = ws._socket.remotePort;
4521 }
4522 // if we're just now initializing a connection to the remote,
4523 // inspect the url property
4524 else {
4525 var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
4526 if (!result) {
4527 throw new Error('WebSocket URL must be in the format ws(s)://address:port');
4528 }
4529 addr = result[1];
4530 port = parseInt(result[2], 10);
4531 }
4532 } else {
4533 // create the actual websocket object and connect
4534 try {
4535 // runtimeConfig gets set to true if WebSocket runtime configuration is available.
4536 var runtimeConfig = (Module['websocket'] && ('object' === typeof Module['websocket']));
4537
4538 // The default value is 'ws://' the replace is needed because the compiler replaces "//" comments with '#'
4539 // comments without checking context, so we'd end up with ws:#, the replace swaps the "#" for "//" again.
4540 var url = 'ws:#'.replace('#', '//');
4541
4542 if (runtimeConfig) {
4543 if ('string' === typeof Module['websocket']['url']) {
4544 url = Module['websocket']['url']; // Fetch runtime WebSocket URL config.
4545 }
4546 }
4547
4548 if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
4549 url = url + addr + ':' + port;
4550 }
4551
4552 // Make the WebSocket subprotocol (Sec-WebSocket-Protocol) default to binary if no configuration is set.
4553 var subProtocols = 'binary'; // The default value is 'binary'
4554
4555 if (runtimeConfig) {
4556 if ('string' === typeof Module['websocket']['subprotocol']) {
4557 subProtocols = Module['websocket']['subprotocol']; // Fetch runtime WebSocket subprotocol config.
4558 }
4559 }
4560
4561 // The regex trims the string (removes spaces at the beginning and end, then splits the string by
4562 // <any space>,<any space> into an Array. Whitespace removal is important for Websockify and ws.
4563 subProtocols = subProtocols.replace(/^ +| +$/g,"").split(/ *, */);
4564
4565 // The node ws library API for specifying optional subprotocol is slightly different than the browser's.
4566 var opts = ENVIRONMENT_IS_NODE ? {'protocol': subProtocols.toString()} : subProtocols;
4567
4568 // If node we use the ws library.
4569 var WebSocket = ENVIRONMENT_IS_NODE ? require('ws') : window['WebSocket'];
4570 ws = new WebSocket(url, opts);
4571 ws.binaryType = 'arraybuffer';
4572 } catch (e) {
4573 throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
4574 }
4575 }
4576
4577
4578 var peer = {
4579 addr: addr,
4580 port: port,
4581 socket: ws,
4582 dgram_send_queue: []
4583 };
4584
4585 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4586 SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
4587
4588 // if this is a bound dgram socket, send the port number first to allow
4589 // us to override the ephemeral port reported to us by remotePort on the
4590 // remote end.
4591 if (sock.type === 2 && typeof sock.sport !== 'undefined') {
4592 peer.dgram_send_queue.push(new Uint8Array([
4593 255, 255, 255, 255,
4594 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0),
4595 ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
4596 ]));
4597 }
4598
4599 return peer;
4600 },getPeer:function (sock, addr, port) {
4601 return sock.peers[addr + ':' + port];
4602 },addPeer:function (sock, peer) {
4603 sock.peers[peer.addr + ':' + peer.port] = peer;
4604 },removePeer:function (sock, peer) {
4605 delete sock.peers[peer.addr + ':' + peer.port];
4606 },handlePeerEvents:function (sock, peer) {
4607 var first = true;
4608
4609 var handleOpen = function () {
4610 try {
4611 var queued = peer.dgram_send_queue.shift();
4612 while (queued) {
4613 peer.socket.send(queued);
4614 queued = peer.dgram_send_queue.shift();
4615 }
4616 } catch (e) {
4617 // not much we can do here in the way of proper error handling as we've already
4618 // lied and said this data was sent. shut it down.
4619 peer.socket.close();
4620 }
4621 };
4622
4623 function handleMessage(data) {
4624 assert(typeof data !== 'string' && data.byteLength !== undefined); // must receive an ArrayBuffer
4625 data = new Uint8Array(data); // make a typed array view on the array buffer
4626
4627
4628 // if this is the port message, override the peer's port with it
4629 var wasfirst = first;
4630 first = false;
4631 if (wasfirst &&
4632 data.length === 10 &&
4633 data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
4634 data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) && data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
4635 // update the peer's port and it's key in the peer map
4636 var newport = ((data[8] << 8) | data[9]);
4637 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4638 peer.port = newport;
4639 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4640 return;
4641 }
4642
4643 sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
4644 };
4645
4646 if (ENVIRONMENT_IS_NODE) {
4647 peer.socket.on('open', handleOpen);
4648 peer.socket.on('message', function(data, flags) {
4649 if (!flags.binary) {
4650 return;
4651 }
4652 handleMessage((new Uint8Array(data)).buffer); // copy from node Buffer -> ArrayBuffer
4653 });
4654 peer.socket.on('error', function() {
4655 // don't throw
4656 });
4657 } else {
4658 peer.socket.onopen = handleOpen;
4659 peer.socket.onmessage = function peer_socket_onmessage(event) {
4660 handleMessage(event.data);
4661 };
4662 }
4663 },poll:function (sock) {
4664 if (sock.type === 1 && sock.server) {
4665 // listen sockets should only say they're available for reading
4666 // if there are pending clients.
4667 return sock.pending.length ? (64 | 1) : 0;
4668 }
4669
4670 var mask = 0;
4671 var dest = sock.type === 1 ? // we only care about the socket state for connection-based sockets
4672 SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
4673 null;
4674
4675 if (sock.recv_queue.length ||
4676 !dest || // connection-less sockets are always ready to read
4677 (dest && dest.socket.readyState === dest.socket.CLOSING) ||
4678 (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
4679 mask |= (64 | 1);
4680 }
4681
4682 if (!dest || // connection-less sockets are always ready to write
4683 (dest && dest.socket.readyState === dest.socket.OPEN)) {
4684 mask |= 4;
4685 }
4686
4687 if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
4688 (dest && dest.socket.readyState === dest.socket.CLOSED)) {
4689 mask |= 16;
4690 }
4691
4692 return mask;
4693 },ioctl:function (sock, request, arg) {
4694 switch (request) {
4695 case 21531:
4696 var bytes = 0;
4697 if (sock.recv_queue.length) {
4698 bytes = sock.recv_queue[0].data.length;
4699 }
4700 HEAP32[((arg)>>2)]=bytes;
4701 return 0;
4702 default:
4703 return ERRNO_CODES.EINVAL;
4704 }
4705 },close:function (sock) {
4706 // if we've spawned a listen server, close it
4707 if (sock.server) {
4708 try {
4709 sock.server.close();
4710 } catch (e) {
4711 }
4712 sock.server = null;
4713 }
4714 // close any peer connections
4715 var peers = Object.keys(sock.peers);
4716 for (var i = 0; i < peers.length; i++) {
4717 var peer = sock.peers[peers[i]];
4718 try {
4719 peer.socket.close();
4720 } catch (e) {
4721 }
4722 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4723 }
4724 return 0;
4725 },bind:function (sock, addr, port) {
4726 if (typeof sock.saddr !== 'undefined' || typeof sock.sport !== 'undefined') {
4727 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already bound
4728 }
4729 sock.saddr = addr;
4730 sock.sport = port || _mkport();
4731 // in order to emulate dgram sockets, we need to launch a listen server when
4732 // binding on a connection-less socket
4733 // note: this is only required on the server side
4734 if (sock.type === 2) {
4735 // close the existing server if it exists
4736 if (sock.server) {
4737 sock.server.close();
4738 sock.server = null;
4739 }
4740 // swallow error operation not supported error that occurs when binding in the
4741 // browser where this isn't supported
4742 try {
4743 sock.sock_ops.listen(sock, 0);
4744 } catch (e) {
4745 if (!(e instanceof FS.ErrnoError)) throw e;
4746 if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
4747 }
4748 }
4749 },connect:function (sock, addr, port) {
4750 if (sock.server) {
4751 throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
4752 }
4753
4754 // TODO autobind
4755 // if (!sock.addr && sock.type == 2) {
4756 // }
4757
4758 // early out if we're already connected / in the middle of connecting
4759 if (typeof sock.daddr !== 'undefined' && typeof sock.dport !== 'undefined') {
4760 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
4761 if (dest) {
4762 if (dest.socket.readyState === dest.socket.CONNECTING) {
4763 throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
4764 } else {
4765 throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
4766 }
4767 }
4768 }
4769
4770 // add the socket to our peer list and set our
4771 // destination address / port to match
4772 var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4773 sock.daddr = peer.addr;
4774 sock.dport = peer.port;
4775
4776 // always "fail" in non-blocking mode
4777 throw new FS.ErrnoError(ERRNO_CODES.EINPROGRESS);
4778 },listen:function (sock, backlog) {
4779 if (!ENVIRONMENT_IS_NODE) {
4780 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
4781 }
4782 if (sock.server) {
4783 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already listening
4784 }
4785 var WebSocketServer = require('ws').Server;
4786 var host = sock.saddr;
4787 sock.server = new WebSocketServer({
4788 host: host,
4789 port: sock.sport
4790 // TODO support backlog
4791 });
4792
4793 sock.server.on('connection', function(ws) {
4794 if (sock.type === 1) {
4795 var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
4796
4797 // create a peer on the new socket
4798 var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
4799 newsock.daddr = peer.addr;
4800 newsock.dport = peer.port;
4801
4802 // push to queue for accept to pick up
4803 sock.pending.push(newsock);
4804 } else {
4805 // create a peer on the listen socket so calling sendto
4806 // with the listen socket and an address will resolve
4807 // to the correct client
4808 SOCKFS.websocket_sock_ops.createPeer(sock, ws);
4809 }
4810 });
4811 sock.server.on('closed', function() {
4812 sock.server = null;
4813 });
4814 sock.server.on('error', function() {
4815 // don't throw
4816 });
4817 },accept:function (listensock) {
4818 if (!listensock.server) {
4819 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4820 }
4821 var newsock = listensock.pending.shift();
4822 newsock.stream.flags = listensock.stream.flags;
4823 return newsock;
4824 },getname:function (sock, peer) {
4825 var addr, port;
4826 if (peer) {
4827 if (sock.daddr === undefined || sock.dport === undefined) {
4828 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4829 }
4830 addr = sock.daddr;
4831 port = sock.dport;
4832 } else {
4833 // TODO saddr and sport will be set for bind()'d UDP sockets, but what
4834 // should we be returning for TCP sockets that've been connect()'d?
4835 addr = sock.saddr || 0;
4836 port = sock.sport || 0;
4837 }
4838 return { addr: addr, port: port };
4839 },sendmsg:function (sock, buffer, offset, length, addr, port) {
4840 if (sock.type === 2) {
4841 // connection-less sockets will honor the message address,
4842 // and otherwise fall back to the bound destination address
4843 if (addr === undefined || port === undefined) {
4844 addr = sock.daddr;
4845 port = sock.dport;
4846 }
4847 // if there was no address to fall back to, error out
4848 if (addr === undefined || port === undefined) {
4849 throw new FS.ErrnoError(ERRNO_CODES.EDESTADDRREQ);
4850 }
4851 } else {
4852 // connection-based sockets will only use the bound
4853 addr = sock.daddr;
4854 port = sock.dport;
4855 }
4856
4857 // find the peer for the destination address
4858 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
4859
4860 // early out if not connected with a connection-based socket
4861 if (sock.type === 1) {
4862 if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4863 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4864 } else if (dest.socket.readyState === dest.socket.CONNECTING) {
4865 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4866 }
4867 }
4868
4869 // create a copy of the incoming data to send, as the WebSocket API
4870 // doesn't work entirely with an ArrayBufferView, it'll just send
4871 // the entire underlying buffer
4872 var data;
4873 if (buffer instanceof Array || buffer instanceof ArrayBuffer) {
4874 data = buffer.slice(offset, offset + length);
4875 } else { // ArrayBufferView
4876 data = buffer.buffer.slice(buffer.byteOffset + offset, buffer.byteOffset + offset + length);
4877 }
4878
4879 // if we're emulating a connection-less dgram socket and don't have
4880 // a cached connection, queue the buffer to send upon connect and
4881 // lie, saying the data was sent now.
4882 if (sock.type === 2) {
4883 if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
4884 // if we're not connected, open a new connection
4885 if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4886 dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4887 }
4888 dest.dgram_send_queue.push(data);
4889 return length;
4890 }
4891 }
4892
4893 try {
4894 // send the actual data
4895 dest.socket.send(data);
4896 return length;
4897 } catch (e) {
4898 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4899 }
4900 },recvmsg:function (sock, length) {
4901 // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
4902 if (sock.type === 1 && sock.server) {
4903 // tcp servers should not be recv()'ing on the listen socket
4904 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4905 }
4906
4907 var queued = sock.recv_queue.shift();
4908 if (!queued) {
4909 if (sock.type === 1) {
4910 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
4911
4912 if (!dest) {
4913 // if we have a destination address but are not connected, error out
4914 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4915 }
4916 else if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
4917 // return null if the socket has closed
4918 return null;
4919 }
4920 else {
4921 // else, our socket is in a valid state but truly has nothing available
4922 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4923 }
4924 } else {
4925 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4926 }
4927 }
4928
4929 // queued.data will be an ArrayBuffer if it's unadulterated, but if it's
4930 // requeued TCP data it'll be an ArrayBufferView
4931 var queuedLength = queued.data.byteLength || queued.data.length;
4932 var queuedOffset = queued.data.byteOffset || 0;
4933 var queuedBuffer = queued.data.buffer || queued.data;
4934 var bytesRead = Math.min(length, queuedLength);
4935 var res = {
4936 buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
4937 addr: queued.addr,
4938 port: queued.port
4939 };
4940
4941
4942 // push back any unread data for TCP connections
4943 if (sock.type === 1 && bytesRead < queuedLength) {
4944 var bytesRemaining = queuedLength - bytesRead;
4945 queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
4946 sock.recv_queue.unshift(queued);
4947 }
4948
4949 return res;
4950 }}};function _send(fd, buf, len, flags) {
4951 var sock = SOCKFS.getSocket(fd);
4952 if (!sock) {
4953 ___setErrNo(ERRNO_CODES.EBADF);
4954 return -1;
4955 }
4956 // TODO honor flags
4957 return _write(fd, buf, len);
4958 }
4959
4960 function _pwrite(fildes, buf, nbyte, offset) {
4961 // ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset);
4962 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4963 var stream = FS.getStream(fildes);
4964 if (!stream) {
4965 ___setErrNo(ERRNO_CODES.EBADF);
4966 return -1;
4967 }
4968 try {
4969 var slab = HEAP8;
4970 return FS.write(stream, slab, buf, nbyte, offset);
4971 } catch (e) {
4972 FS.handleFSError(e);
4973 return -1;
4974 }
4975 }function _write(fildes, buf, nbyte) {
4976 // ssize_t write(int fildes, const void *buf, size_t nbyte);
4977 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4978 var stream = FS.getStream(fildes);
4979 if (!stream) {
4980 ___setErrNo(ERRNO_CODES.EBADF);
4981 return -1;
4982 }
4983
4984
4985 try {
4986 var slab = HEAP8;
4987 return FS.write(stream, slab, buf, nbyte);
4988 } catch (e) {
4989 FS.handleFSError(e);
4990 return -1;
4991 }
4992 }
4993
4994 function _fileno(stream) {
4995 // int fileno(FILE *stream);
4996 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fileno.html
4997 stream = FS.getStreamFromPtr(stream);
4998 if (!stream) return -1;
4999 return stream.fd;
5000 }function _fwrite(ptr, size, nitems, stream) {
5001 // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
5002 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fwrite.html
5003 var bytesToWrite = nitems * size;
5004 if (bytesToWrite == 0) return 0;
5005 var fd = _fileno(stream);
5006 var bytesWritten = _write(fd, ptr, bytesToWrite);
5007 if (bytesWritten == -1) {
5008 var streamObj = FS.getStreamFromPtr(stream);
5009 if (streamObj) streamObj.error = true;
5010 return 0;
5011 } else {
5012 return Math.floor(bytesWritten / size);
5013 }
5014 }
5015
5016
5017
5018 Module["_strlen"] = _strlen;
5019
5020 function __reallyNegative(x) {
5021 return x < 0 || (x === 0 && (1/x) === -Infinity);
5022 }function __formatString(format, varargs) {
5023 var textIndex = format;
5024 var argIndex = 0;
5025 function getNextArg(type) {
5026 // NOTE: Explicitly ignoring type safety. Otherwise this fails:
5027 // int x = 4; printf("%c\n", (char)x);
5028 var ret;
5029 if (type === 'double') {
5030 ret = HEAPF64[(((varargs)+(argIndex))>>3)];
5031 } else if (type == 'i64') {
5032 ret = [HEAP32[(((varargs)+(argIndex))>>2)],
5033 HEAP32[(((varargs)+(argIndex+4))>>2)]];
5034
5035 } else {
5036 type = 'i32'; // varargs are always i32, i64, or double
5037 ret = HEAP32[(((varargs)+(argIndex))>>2)];
5038 }
5039 argIndex += Runtime.getNativeFieldSize(type);
5040 return ret;
5041 }
5042
5043 var ret = [];
5044 var curr, next, currArg;
5045 while(1) {
5046 var startTextIndex = textIndex;
5047 curr = HEAP8[(textIndex)];
5048 if (curr === 0) break;
5049 next = HEAP8[((textIndex+1)|0)];
5050 if (curr == 37) {
5051 // Handle flags.
5052 var flagAlwaysSigned = false;
5053 var flagLeftAlign = false;
5054 var flagAlternative = false;
5055 var flagZeroPad = false;
5056 var flagPadSign = false;
5057 flagsLoop: while (1) {
5058 switch (next) {
5059 case 43:
5060 flagAlwaysSigned = true;
5061 break;
5062 case 45:
5063 flagLeftAlign = true;
5064 break;
5065 case 35:
5066 flagAlternative = true;
5067 break;
5068 case 48:
5069 if (flagZeroPad) {
5070 break flagsLoop;
5071 } else {
5072 flagZeroPad = true;
5073 break;
5074 }
5075 case 32:
5076 flagPadSign = true;
5077 break;
5078 default:
5079 break flagsLoop;
5080 }
5081 textIndex++;
5082 next = HEAP8[((textIndex+1)|0)];
5083 }
5084
5085 // Handle width.
5086 var width = 0;
5087 if (next == 42) {
5088 width = getNextArg('i32');
5089 textIndex++;
5090 next = HEAP8[((textIndex+1)|0)];
5091 } else {
5092 while (next >= 48 && next <= 57) {
5093 width = width * 10 + (next - 48);
5094 textIndex++;
5095 next = HEAP8[((textIndex+1)|0)];
5096 }
5097 }
5098
5099 // Handle precision.
5100 var precisionSet = false, precision = -1;
5101 if (next == 46) {
5102 precision = 0;
5103 precisionSet = true;
5104 textIndex++;
5105 next = HEAP8[((textIndex+1)|0)];
5106 if (next == 42) {
5107 precision = getNextArg('i32');
5108 textIndex++;
5109 } else {
5110 while(1) {
5111 var precisionChr = HEAP8[((textIndex+1)|0)];
5112 if (precisionChr < 48 ||
5113 precisionChr > 57) break;
5114 precision = precision * 10 + (precisionChr - 48);
5115 textIndex++;
5116 }
5117 }
5118 next = HEAP8[((textIndex+1)|0)];
5119 }
5120 if (precision < 0) {
5121 precision = 6; // Standard default.
5122 precisionSet = false;
5123 }
5124
5125 // Handle integer sizes. WARNING: These assume a 32-bit architecture!
5126 var argSize;
5127 switch (String.fromCharCode(next)) {
5128 case 'h':
5129 var nextNext = HEAP8[((textIndex+2)|0)];
5130 if (nextNext == 104) {
5131 textIndex++;
5132 argSize = 1; // char (actually i32 in varargs)
5133 } else {
5134 argSize = 2; // short (actually i32 in varargs)
5135 }
5136 break;
5137 case 'l':
5138 var nextNext = HEAP8[((textIndex+2)|0)];
5139 if (nextNext == 108) {
5140 textIndex++;
5141 argSize = 8; // long long
5142 } else {
5143 argSize = 4; // long
5144 }
5145 break;
5146 case 'L': // long long
5147 case 'q': // int64_t
5148 case 'j': // intmax_t
5149 argSize = 8;
5150 break;
5151 case 'z': // size_t
5152 case 't': // ptrdiff_t
5153 case 'I': // signed ptrdiff_t or unsigned size_t
5154 argSize = 4;
5155 break;
5156 default:
5157 argSize = null;
5158 }
5159 if (argSize) textIndex++;
5160 next = HEAP8[((textIndex+1)|0)];
5161
5162 // Handle type specifier.
5163 switch (String.fromCharCode(next)) {
5164 case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': {
5165 // Integer.
5166 var signed = next == 100 || next == 105;
5167 argSize = argSize || 4;
5168 var currArg = getNextArg('i' + (argSize * 8));
5169 var argText;
5170 // Flatten i64-1 [low, high] into a (slightly rounded) double
5171 if (argSize == 8) {
5172 currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117);
5173 }
5174 // Truncate to requested size.
5175 if (argSize <= 4) {
5176 var limit = Math.pow(256, argSize) - 1;
5177 currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
5178 }
5179 // Format the number.
5180 var currAbsArg = Math.abs(currArg);
5181 var prefix = '';
5182 if (next == 100 || next == 105) {
5183 argText = reSign(currArg, 8 * argSize, 1).toString(10);
5184 } else if (next == 117) {
5185 argText = unSign(currArg, 8 * argSize, 1).toString(10);
5186 currArg = Math.abs(currArg);
5187 } else if (next == 111) {
5188 argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
5189 } else if (next == 120 || next == 88) {
5190 prefix = (flagAlternative && currArg != 0) ? '0x' : '';
5191 if (currArg < 0) {
5192 // Represent negative numbers in hex as 2's complement.
5193 currArg = -currArg;
5194 argText = (currAbsArg - 1).toString(16);
5195 var buffer = [];
5196 for (var i = 0; i < argText.length; i++) {
5197 buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
5198 }
5199 argText = buffer.join('');
5200 while (argText.length < argSize * 2) argText = 'f' + argText;
5201 } else {
5202 argText = currAbsArg.toString(16);
5203 }
5204 if (next == 88) {
5205 prefix = prefix.toUpperCase();
5206 argText = argText.toUpperCase();
5207 }
5208 } else if (next == 112) {
5209 if (currAbsArg === 0) {
5210 argText = '(nil)';
5211 } else {
5212 prefix = '0x';
5213 argText = currAbsArg.toString(16);
5214 }
5215 }
5216 if (precisionSet) {
5217 while (argText.length < precision) {
5218 argText = '0' + argText;
5219 }
5220 }
5221
5222 // Add sign if needed
5223 if (currArg >= 0) {
5224 if (flagAlwaysSigned) {
5225 prefix = '+' + prefix;
5226 } else if (flagPadSign) {
5227 prefix = ' ' + prefix;
5228 }
5229 }
5230
5231 // Move sign to prefix so we zero-pad after the sign
5232 if (argText.charAt(0) == '-') {
5233 prefix = '-' + prefix;
5234 argText = argText.substr(1);
5235 }
5236
5237 // Add padding.
5238 while (prefix.length + argText.length < width) {
5239 if (flagLeftAlign) {
5240 argText += ' ';
5241 } else {
5242 if (flagZeroPad) {
5243 argText = '0' + argText;
5244 } else {
5245 prefix = ' ' + prefix;
5246 }
5247 }
5248 }
5249
5250 // Insert the result into the buffer.
5251 argText = prefix + argText;
5252 argText.split('').forEach(function(chr) {
5253 ret.push(chr.charCodeAt(0));
5254 });
5255 break;
5256 }
5257 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': {
5258 // Float.
5259 var currArg = getNextArg('double');
5260 var argText;
5261 if (isNaN(currArg)) {
5262 argText = 'nan';
5263 flagZeroPad = false;
5264 } else if (!isFinite(currArg)) {
5265 argText = (currArg < 0 ? '-' : '') + 'inf';
5266 flagZeroPad = false;
5267 } else {
5268 var isGeneral = false;
5269 var effectivePrecision = Math.min(precision, 20);
5270
5271 // Convert g/G to f/F or e/E, as per:
5272 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
5273 if (next == 103 || next == 71) {
5274 isGeneral = true;
5275 precision = precision || 1;
5276 var exponent = parseInt(currArg.toExponential(effectivePrecision).split('e')[1], 10);
5277 if (precision > exponent && exponent >= -4) {
5278 next = ((next == 103) ? 'f' : 'F').charCodeAt(0);
5279 precision -= exponent + 1;
5280 } else {
5281 next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
5282 precision--;
5283 }
5284 effectivePrecision = Math.min(precision, 20);
5285 }
5286
5287 if (next == 101 || next == 69) {
5288 argText = currArg.toExponential(effectivePrecision);
5289 // Make sure the exponent has at least 2 digits.
5290 if (/[eE][-+]\d$/.test(argText)) {
5291 argText = argText.slice(0, -1) + '0' + argText.slice(-1);
5292 }
5293 } else if (next == 102 || next == 70) {
5294 argText = currArg.toFixed(effectivePrecision);
5295 if (currArg === 0 && __reallyNegative(currArg)) {
5296 argText = '-' + argText;
5297 }
5298 }
5299
5300 var parts = argText.split('e');
5301 if (isGeneral && !flagAlternative) {
5302 // Discard trailing zeros and periods.
5303 while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
5304 (parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.')) {
5305 parts[0] = parts[0].slice(0, -1);
5306 }
5307 } else {
5308 // Make sure we have a period in alternative mode.
5309 if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
5310 // Zero pad until required precision.
5311 while (precision > effectivePrecision++) parts[0] += '0';
5312 }
5313 argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
5314
5315 // Capitalize 'E' if needed.
5316 if (next == 69) argText = argText.toUpperCase();
5317
5318 // Add sign.
5319 if (currArg >= 0) {
5320 if (flagAlwaysSigned) {
5321 argText = '+' + argText;
5322 } else if (flagPadSign) {
5323 argText = ' ' + argText;
5324 }
5325 }
5326 }
5327
5328 // Add padding.
5329 while (argText.length < width) {
5330 if (flagLeftAlign) {
5331 argText += ' ';
5332 } else {
5333 if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
5334 argText = argText[0] + '0' + argText.slice(1);
5335 } else {
5336 argText = (flagZeroPad ? '0' : ' ') + argText;
5337 }
5338 }
5339 }
5340
5341 // Adjust case.
5342 if (next < 97) argText = argText.toUpperCase();
5343
5344 // Insert the result into the buffer.
5345 argText.split('').forEach(function(chr) {
5346 ret.push(chr.charCodeAt(0));
5347 });
5348 break;
5349 }
5350 case 's': {
5351 // String.
5352 var arg = getNextArg('i8*');
5353 var argLength = arg ? _strlen(arg) : '(null)'.length;
5354 if (precisionSet) argLength = Math.min(argLength, precision);
5355 if (!flagLeftAlign) {
5356 while (argLength < width--) {
5357 ret.push(32);
5358 }
5359 }
5360 if (arg) {
5361 for (var i = 0; i < argLength; i++) {
5362 ret.push(HEAPU8[((arg++)|0)]);
5363 }
5364 } else {
5365 ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true));
5366 }
5367 if (flagLeftAlign) {
5368 while (argLength < width--) {
5369 ret.push(32);
5370 }
5371 }
5372 break;
5373 }
5374 case 'c': {
5375 // Character.
5376 if (flagLeftAlign) ret.push(getNextArg('i8'));
5377 while (--width > 0) {
5378 ret.push(32);
5379 }
5380 if (!flagLeftAlign) ret.push(getNextArg('i8'));
5381 break;
5382 }
5383 case 'n': {
5384 // Write the length written so far to the next parameter.
5385 var ptr = getNextArg('i32*');
5386 HEAP32[((ptr)>>2)]=ret.length;
5387 break;
5388 }
5389 case '%': {
5390 // Literal percent sign.
5391 ret.push(curr);
5392 break;
5393 }
5394 default: {
5395 // Unknown specifiers remain untouched.
5396 for (var i = startTextIndex; i < textIndex + 2; i++) {
5397 ret.push(HEAP8[(i)]);
5398 }
5399 }
5400 }
5401 textIndex += 2;
5402 // TODO: Support a/A (hex float) and m (last error) specifiers.
5403 // TODO: Support %1${specifier} for arg selection.
5404 } else {
5405 ret.push(curr);
5406 textIndex += 1;
5407 }
5408 }
5409 return ret;
5410 }function _fprintf(stream, format, varargs) {
5411 // int fprintf(FILE *restrict stream, const char *restrict format, ...);
5412 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
5413 var result = __formatString(format, varargs);
5414 var stack = Runtime.stackSave();
5415 var ret = _fwrite(allocate(result, 'i8', ALLOC_STACK), 1, result.length, stream);
5416 Runtime.stackRestore(stack);
5417 return ret;
5418 }function _printf(format, varargs) {
5419 // int printf(const char *restrict format, ...);
5420 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
5421 var stdout = HEAP32[((_stdout)>>2)];
5422 return _fprintf(stdout, format, varargs);
5423 }
5424
5425
5426 var _sqrtf=Math_sqrt;
5427Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, resizeCanvas) { Browser.requestFullScreen(lockPointer, resizeCanvas) };
5428 Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
5429 Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };
5430 Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };
5431 Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };
5432 Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }
5433FS.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;
5434___errno_state = Runtime.staticAlloc(4); HEAP32[((___errno_state)>>2)]=0;
5435__ATINIT__.unshift({ func: function() { TTY.init() } });__ATEXIT__.push({ func: function() { TTY.shutdown() } });TTY.utf8 = new Runtime.UTF8Processor();
5436if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); NODEFS.staticInit(); }
5437__ATINIT__.push({ func: function() { SOCKFS.root = FS.mount(SOCKFS, {}, null); } });
5438STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
5439
5440staticSealed = true; // seal the static portion of memory
5441
5442STACK_MAX = STACK_BASE + 5242880;
5443
5444DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
5445
5446assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
5447
5448
5449var Math_min = Math.min;
5450function asmPrintInt(x, y) {
5451 Module.print('int ' + x + ',' + y);// + ' ' + new Error().stack);
5452}
5453function asmPrintFloat(x, y) {
5454 Module.print('float ' + x + ',' + y);// + ' ' + new Error().stack);
5455}
5456// EMSCRIPTEN_START_ASM
5457var asm = Wasm.instantiateModuleFromAsm((function Module(global, env, buffer) {
5458 'use asm';
5459 var HEAP8 = new global.Int8Array(buffer);
5460 var HEAP16 = new global.Int16Array(buffer);
5461 var HEAP32 = new global.Int32Array(buffer);
5462 var HEAPU8 = new global.Uint8Array(buffer);
5463 var HEAPU16 = new global.Uint16Array(buffer);
5464 var HEAPU32 = new global.Uint32Array(buffer);
5465 var HEAPF32 = new global.Float32Array(buffer);
5466 var HEAPF64 = new global.Float64Array(buffer);
5467
5468 var STACKTOP=env.STACKTOP|0;
5469 var STACK_MAX=env.STACK_MAX|0;
5470 var tempDoublePtr=env.tempDoublePtr|0;
5471 var ABORT=env.ABORT|0;
5472
5473 var __THREW__ = 0;
5474 var threwValue = 0;
5475 var setjmpId = 0;
5476 var undef = 0;
5477 var nan = +env.NaN, inf = +env.Infinity;
5478 var tempInt = 0, tempBigInt = 0, tempBigIntP = 0, tempBigIntS = 0, tempBigIntR = 0.0, tempBigIntI = 0, tempBigIntD = 0, tempValue = 0, tempDouble = 0.0;
5479
5480 var tempRet0 = 0;
5481 var tempRet1 = 0;
5482 var tempRet2 = 0;
5483 var tempRet3 = 0;
5484 var tempRet4 = 0;
5485 var tempRet5 = 0;
5486 var tempRet6 = 0;
5487 var tempRet7 = 0;
5488 var tempRet8 = 0;
5489 var tempRet9 = 0;
5490 var Math_floor=global.Math.floor;
5491 var Math_abs=global.Math.abs;
5492 var Math_sqrt=global.Math.sqrt;
5493 var Math_pow=global.Math.pow;
5494 var Math_cos=global.Math.cos;
5495 var Math_sin=global.Math.sin;
5496 var Math_tan=global.Math.tan;
5497 var Math_acos=global.Math.acos;
5498 var Math_asin=global.Math.asin;
5499 var Math_atan=global.Math.atan;
5500 var Math_atan2=global.Math.atan2;
5501 var Math_exp=global.Math.exp;
5502 var Math_log=global.Math.log;
5503 var Math_ceil=global.Math.ceil;
5504 var Math_imul=global.Math.imul;
5505 var abort=env.abort;
5506 var assert=env.assert;
5507 var asmPrintInt=env.asmPrintInt;
5508 var asmPrintFloat=env.asmPrintFloat;
5509 var Math_min=env.min;
5510 var _free=env._free;
5511 var _emscripten_memcpy_big=env._emscripten_memcpy_big;
5512 var _printf=env._printf;
5513 var _send=env._send;
5514 var _pwrite=env._pwrite;
5515 var _sqrtf=env._sqrtf;
5516 var __reallyNegative=env.__reallyNegative;
5517 var _fwrite=env._fwrite;
5518 var _malloc=env._malloc;
5519 var _mkport=env._mkport;
5520 var _fprintf=env._fprintf;
5521 var ___setErrNo=env.___setErrNo;
5522 var __formatString=env.__formatString;
5523 var _fileno=env._fileno;
5524 var _fflush=env._fflush;
5525 var _write=env._write;
5526 var tempFloat = 0.0;
5527
5528// EMSCRIPTEN_START_FUNCS
5529function _main(i3, i5) {
5530 i3 = i3 | 0;
5531 i5 = i5 | 0;
5532 var i1 = 0, i2 = 0, i4 = 0, i6 = 0, i7 = 0, d8 = 0.0;
5533 i1 = STACKTOP;
5534 STACKTOP = STACKTOP + 16 | 0;
5535 i2 = i1;
5536 L1 : do {
5537 if ((i3 | 0) > 1) {
5538 i3 = HEAP8[HEAP32[i5 + 4 >> 2] | 0] | 0;
5539 switch (i3 | 0) {
5540 case 50:
5541 {
5542 i3 = 13e4;
5543 break L1;
5544 }
5545 case 51:
5546 {
5547 i4 = 4;
5548 break L1;
5549 }
5550 case 52:
5551 {
5552 i3 = 61e4;
5553 break L1;
5554 }
5555 case 53:
5556 {
5557 i3 = 101e4;
5558 break L1;
5559 }
5560 case 49:
5561 {
5562 i3 = 33e3;
5563 break L1;
5564 }
5565 case 48:
5566 {
5567 i7 = 0;
5568 STACKTOP = i1;
5569 return i7 | 0;
5570 }
5571 default:
5572 {
5573 HEAP32[i2 >> 2] = i3 + -48;
5574 _printf(8, i2 | 0) | 0;
5575 i7 = -1;
5576 STACKTOP = i1;
5577 return i7 | 0;
5578 }
5579 }
5580 } else {
5581 i4 = 4;
5582 }
5583 } while (0);
5584 if ((i4 | 0) == 4) {
5585 i3 = 22e4;
5586 }
5587 i4 = 2;
5588 i5 = 0;
5589 while (1) {
5590 d8 = +Math_sqrt(+(+(i4 | 0)));
5591 L15 : do {
5592 if (d8 > 2.0) {
5593 i7 = 2;
5594 while (1) {
5595 i6 = i7 + 1 | 0;
5596 if (((i4 | 0) % (i7 | 0) | 0 | 0) == 0) {
5597 i6 = 0;
5598 break L15;
5599 }
5600 if (+(i6 | 0) < d8) {
5601 i7 = i6;
5602 } else {
5603 i6 = 1;
5604 break;
5605 }
5606 }
5607 } else {
5608 i6 = 1;
5609 }
5610 } while (0);
5611 i5 = i6 + i5 | 0;
5612 if ((i5 | 0) >= (i3 | 0)) {
5613 break;
5614 } else {
5615 i4 = i4 + 1 | 0;
5616 }
5617 }
5618 HEAP32[i2 >> 2] = i4;
5619 _printf(24, i2 | 0) | 0;
5620 i7 = 0;
5621 STACKTOP = i1;
5622 return i7 | 0;
5623}
5624function _memcpy(i3, i2, i1) {
5625 i3 = i3 | 0;
5626 i2 = i2 | 0;
5627 i1 = i1 | 0;
5628 var i4 = 0;
5629 if ((i1 | 0) >= 4096) return _emscripten_memcpy_big(i3 | 0, i2 | 0, i1 | 0) | 0;
5630 i4 = i3 | 0;
5631 if ((i3 & 3) == (i2 & 3)) {
5632 while (i3 & 3) {
5633 if ((i1 | 0) == 0) return i4 | 0;
5634 HEAP8[i3] = HEAP8[i2] | 0;
5635 i3 = i3 + 1 | 0;
5636 i2 = i2 + 1 | 0;
5637 i1 = i1 - 1 | 0;
5638 }
5639 while ((i1 | 0) >= 4) {
5640 HEAP32[i3 >> 2] = HEAP32[i2 >> 2];
5641 i3 = i3 + 4 | 0;
5642 i2 = i2 + 4 | 0;
5643 i1 = i1 - 4 | 0;
5644 }
5645 }
5646 while ((i1 | 0) > 0) {
5647 HEAP8[i3] = HEAP8[i2] | 0;
5648 i3 = i3 + 1 | 0;
5649 i2 = i2 + 1 | 0;
5650 i1 = i1 - 1 | 0;
5651 }
5652 return i4 | 0;
5653}
5654function runPostSets() {}
5655function _memset(i1, i4, i3) {
5656 i1 = i1 | 0;
5657 i4 = i4 | 0;
5658 i3 = i3 | 0;
5659 var i2 = 0, i5 = 0, i6 = 0, i7 = 0;
5660 i2 = i1 + i3 | 0;
5661 if ((i3 | 0) >= 20) {
5662 i4 = i4 & 255;
5663 i7 = i1 & 3;
5664 i6 = i4 | i4 << 8 | i4 << 16 | i4 << 24;
5665 i5 = i2 & ~3;
5666 if (i7) {
5667 i7 = i1 + 4 - i7 | 0;
5668 while ((i1 | 0) < (i7 | 0)) {
5669 HEAP8[i1] = i4;
5670 i1 = i1 + 1 | 0;
5671 }
5672 }
5673 while ((i1 | 0) < (i5 | 0)) {
5674 HEAP32[i1 >> 2] = i6;
5675 i1 = i1 + 4 | 0;
5676 }
5677 }
5678 while ((i1 | 0) < (i2 | 0)) {
5679 HEAP8[i1] = i4;
5680 i1 = i1 + 1 | 0;
5681 }
5682 return i1 - i3 | 0;
5683}
5684function copyTempDouble(i1) {
5685 i1 = i1 | 0;
5686 HEAP8[tempDoublePtr] = HEAP8[i1];
5687 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
5688 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
5689 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
5690 HEAP8[tempDoublePtr + 4 | 0] = HEAP8[i1 + 4 | 0];
5691 HEAP8[tempDoublePtr + 5 | 0] = HEAP8[i1 + 5 | 0];
5692 HEAP8[tempDoublePtr + 6 | 0] = HEAP8[i1 + 6 | 0];
5693 HEAP8[tempDoublePtr + 7 | 0] = HEAP8[i1 + 7 | 0];
5694}
5695function copyTempFloat(i1) {
5696 i1 = i1 | 0;
5697 HEAP8[tempDoublePtr] = HEAP8[i1];
5698 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
5699 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
5700 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
5701}
5702function stackAlloc(i1) {
5703 i1 = i1 | 0;
5704 var i2 = 0;
5705 i2 = STACKTOP;
5706 STACKTOP = STACKTOP + i1 | 0;
5707 STACKTOP = STACKTOP + 7 & -8;
5708 return i2 | 0;
5709}
5710function _strlen(i1) {
5711 i1 = i1 | 0;
5712 var i2 = 0;
5713 i2 = i1;
5714 while (HEAP8[i2] | 0) {
5715 i2 = i2 + 1 | 0;
5716 }
5717 return i2 - i1 | 0;
5718}
5719function setThrew(i1, i2) {
5720 i1 = i1 | 0;
5721 i2 = i2 | 0;
5722 if ((__THREW__ | 0) == 0) {
5723 __THREW__ = i1;
5724 threwValue = i2;
5725 }
5726}
5727function stackRestore(i1) {
5728 i1 = i1 | 0;
5729 STACKTOP = i1;
5730}
5731function setTempRet9(i1) {
5732 i1 = i1 | 0;
5733 tempRet9 = i1;
5734}
5735function setTempRet8(i1) {
5736 i1 = i1 | 0;
5737 tempRet8 = i1;
5738}
5739function setTempRet7(i1) {
5740 i1 = i1 | 0;
5741 tempRet7 = i1;
5742}
5743function setTempRet6(i1) {
5744 i1 = i1 | 0;
5745 tempRet6 = i1;
5746}
5747function setTempRet5(i1) {
5748 i1 = i1 | 0;
5749 tempRet5 = i1;
5750}
5751function setTempRet4(i1) {
5752 i1 = i1 | 0;
5753 tempRet4 = i1;
5754}
5755function setTempRet3(i1) {
5756 i1 = i1 | 0;
5757 tempRet3 = i1;
5758}
5759function setTempRet2(i1) {
5760 i1 = i1 | 0;
5761 tempRet2 = i1;
5762}
5763function setTempRet1(i1) {
5764 i1 = i1 | 0;
5765 tempRet1 = i1;
5766}
5767function setTempRet0(i1) {
5768 i1 = i1 | 0;
5769 tempRet0 = i1;
5770}
5771function stackSave() {
5772 return STACKTOP | 0;
5773}
5774
5775// EMSCRIPTEN_END_FUNCS
5776
5777
5778 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 };
5779}).toString(),
5780// EMSCRIPTEN_END_ASM
5781{ "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, "_sqrtf": _sqrtf, "__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);
5782var _strlen = Module["_strlen"] = asm["_strlen"];
5783var _memcpy = Module["_memcpy"] = asm["_memcpy"];
5784var _main = Module["_main"] = asm["_main"];
5785var _memset = Module["_memset"] = asm["_memset"];
5786var runPostSets = Module["runPostSets"] = asm["runPostSets"];
5787
5788Runtime.stackAlloc = function(size) { return asm['stackAlloc'](size) };
5789Runtime.stackSave = function() { return asm['stackSave']() };
5790Runtime.stackRestore = function(top) { asm['stackRestore'](top) };
5791
5792
5793// Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
5794var i64Math = null;
5795
5796// === Auto-generated postamble setup entry stuff ===
5797
5798if (memoryInitializer) {
5799 if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
5800 var data = Module['readBinary'](memoryInitializer);
5801 HEAPU8.set(data, STATIC_BASE);
5802 } else {
5803 addRunDependency('memory initializer');
5804 Browser.asyncLoad(memoryInitializer, function(data) {
5805 HEAPU8.set(data, STATIC_BASE);
5806 removeRunDependency('memory initializer');
5807 }, function(data) {
5808 throw 'could not load memory initializer ' + memoryInitializer;
5809 });
5810 }
5811}
5812
5813function ExitStatus(status) {
5814 this.name = "ExitStatus";
5815 this.message = "Program terminated with exit(" + status + ")";
5816 this.status = status;
5817};
5818ExitStatus.prototype = new Error();
5819ExitStatus.prototype.constructor = ExitStatus;
5820
5821var initialStackTop;
5822var preloadStartTime = null;
5823var calledMain = false;
5824
5825dependenciesFulfilled = function runCaller() {
5826 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
5827 if (!Module['calledRun'] && shouldRunNow) run([].concat(Module["arguments"]));
5828 if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
5829}
5830
5831Module['callMain'] = Module.callMain = function callMain(args) {
5832 assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on __ATMAIN__)');
5833 assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
5834
5835 args = args || [];
5836
5837 ensureInitRuntime();
5838
5839 var argc = args.length+1;
5840 function pad() {
5841 for (var i = 0; i < 4-1; i++) {
5842 argv.push(0);
5843 }
5844 }
5845 var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORMAL) ];
5846 pad();
5847 for (var i = 0; i < argc-1; i = i + 1) {
5848 argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
5849 pad();
5850 }
5851 argv.push(0);
5852 argv = allocate(argv, 'i32', ALLOC_NORMAL);
5853
5854 initialStackTop = STACKTOP;
5855
5856 try {
5857
5858 var ret = Module['_main'](argc, argv, 0);
5859
5860
5861 // if we're not running an evented main loop, it's time to exit
5862 if (!Module['noExitRuntime']) {
5863 exit(ret);
5864 }
5865 }
5866 catch(e) {
5867 if (e instanceof ExitStatus) {
5868 // exit() throws this once it's done to make sure execution
5869 // has been stopped completely
5870 return;
5871 } else if (e == 'SimulateInfiniteLoop') {
5872 // running an evented main loop, don't immediately exit
5873 Module['noExitRuntime'] = true;
5874 return;
5875 } else {
5876 if (e && typeof e === 'object' && e.stack) Module.printErr('exception thrown: ' + [e, e.stack]);
5877 throw e;
5878 }
5879 } finally {
5880 calledMain = true;
5881 }
5882}
5883
5884
5885
5886
5887function run(args) {
5888 args = args || Module['arguments'];
5889
5890 if (preloadStartTime === null) preloadStartTime = Date.now();
5891
5892 if (runDependencies > 0) {
5893 Module.printErr('run() called, but dependencies remain, so not running');
5894 return;
5895 }
5896
5897 preRun();
5898
5899 if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
5900 if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
5901
5902 function doRun() {
5903 if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
5904 Module['calledRun'] = true;
5905
5906 ensureInitRuntime();
5907
5908 preMain();
5909
5910 if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
5911 Module.printErr('pre-main prep time: ' + (Date.now() - preloadStartTime) + ' ms');
5912 }
5913
5914 if (Module['_main'] && shouldRunNow) {
5915 Module['callMain'](args);
5916 }
5917
5918 postRun();
5919 }
5920
5921 if (Module['setStatus']) {
5922 Module['setStatus']('Running...');
5923 setTimeout(function() {
5924 setTimeout(function() {
5925 Module['setStatus']('');
5926 }, 1);
5927 if (!ABORT) doRun();
5928 }, 1);
5929 } else {
5930 doRun();
5931 }
5932}
5933Module['run'] = Module.run = run;
5934
5935function exit(status) {
5936 ABORT = true;
5937 EXITSTATUS = status;
5938 STACKTOP = initialStackTop;
5939
5940 // exit the runtime
5941 exitRuntime();
5942
5943 // TODO We should handle this differently based on environment.
5944 // In the browser, the best we can do is throw an exception
5945 // to halt execution, but in node we could process.exit and
5946 // I'd imagine SM shell would have something equivalent.
5947 // This would let us set a proper exit status (which
5948 // would be great for checking test exit statuses).
5949 // https://github.com/kripken/emscripten/issues/1371
5950
5951 // throw an exception to halt the current execution
5952 throw new ExitStatus(status);
5953}
5954Module['exit'] = Module.exit = exit;
5955
5956function abort(text) {
5957 if (text) {
5958 Module.print(text);
5959 Module.printErr(text);
5960 }
5961
5962 ABORT = true;
5963 EXITSTATUS = 1;
5964
5965 var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
5966
5967 throw 'abort() at ' + stackTrace() + extra;
5968}
5969Module['abort'] = Module.abort = abort;
5970
5971// {{PRE_RUN_ADDITIONS}}
5972
5973if (Module['preInit']) {
5974 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
5975 while (Module['preInit'].length > 0) {
5976 Module['preInit'].pop()();
5977 }
5978}
5979
5980// shouldRunNow refers to calling main(), not run().
5981var shouldRunNow = true;
5982if (Module['noInitialRun']) {
5983 shouldRunNow = false;
5984}
5985
5986
5987run([].concat(Module["arguments"]));