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