Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(561)

Side by Side Diff: test/mjsunit/asm/embenchen/fannkuch.js

Issue 704653004: Add test cases based on the programs from the Embenchen benchmark suite. (Closed) Base URL: https://v8.googlecode.com/svn/branches/bleeding_edge
Patch Set: Mark certain tests as slow. Created 6 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « test/mjsunit/asm/embenchen/corrections.js ('k') | test/mjsunit/asm/embenchen/fasta.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 var EXPECTED_OUTPUT =
6 '123456789\n' +
7 '213456789\n' +
8 '231456789\n' +
9 '321456789\n' +
10 '312456789\n' +
11 '132456789\n' +
12 '234156789\n' +
13 '324156789\n' +
14 '342156789\n' +
15 '432156789\n' +
16 '423156789\n' +
17 '243156789\n' +
18 '341256789\n' +
19 '431256789\n' +
20 '413256789\n' +
21 '143256789\n' +
22 '134256789\n' +
23 '314256789\n' +
24 '412356789\n' +
25 '142356789\n' +
26 '124356789\n' +
27 '214356789\n' +
28 '241356789\n' +
29 '421356789\n' +
30 '234516789\n' +
31 '324516789\n' +
32 '342516789\n' +
33 '432516789\n' +
34 '423516789\n' +
35 '243516789\n' +
36 'Pfannkuchen(9) = 30.\n';
37 var Module = {
38 arguments: [1],
39 print: function(x) {Module.printBuffer += x + '\n';},
40 preRun: [function() {Module.printBuffer = ''}],
41 postRun: [function() {
42 assertEquals(EXPECTED_OUTPUT, Module.printBuffer);
43 }],
44 };
45 // The Module object: Our interface to the outside world. We import
46 // and export values on it, and do the work to get that through
47 // closure compiler if necessary. There are various ways Module can be used:
48 // 1. Not defined. We create it here
49 // 2. A function parameter, function(Module) { ..generated code.. }
50 // 3. pre-run appended it, var Module = {}; ..generated code..
51 // 4. External script tag defines var Module.
52 // We need to do an eval in order to handle the closure compiler
53 // case, where this code here is minified but Module was defined
54 // elsewhere (e.g. case 4 above). We also need to check if Module
55 // already exists (e.g. case 3 above).
56 // Note that if you want to run closure, and also to use Module
57 // after the generated code, you will need to define var Module = {};
58 // before the code. Then that object will be used in the code, and you
59 // can continue to use Module afterwards as well.
60 var Module;
61 if (!Module) Module = (typeof Module !== 'undefined' ? Module : null) || {};
62
63 // Sometimes an existing Module object exists with properties
64 // meant to overwrite the default module functionality. Here
65 // we collect those properties and reapply _after_ we configure
66 // the current environment's defaults to avoid having to be so
67 // defensive during initialization.
68 var moduleOverrides = {};
69 for (var key in Module) {
70 if (Module.hasOwnProperty(key)) {
71 moduleOverrides[key] = Module[key];
72 }
73 }
74
75 // The environment setup code below is customized to use Module.
76 // *** Environment setup code ***
77 var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'fun ction';
78 var ENVIRONMENT_IS_WEB = typeof window === 'object';
79 var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
80 var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIR ONMENT_IS_WORKER;
81
82 if (ENVIRONMENT_IS_NODE) {
83 // Expose functionality in the same simple way that the shells work
84 // Note that we pollute the global namespace here, otherwise we break in node
85 if (!Module['print']) Module['print'] = function print(x) {
86 process['stdout'].write(x + '\n');
87 };
88 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
89 process['stderr'].write(x + '\n');
90 };
91
92 var nodeFS = require('fs');
93 var nodePath = require('path');
94
95 Module['read'] = function read(filename, binary) {
96 filename = nodePath['normalize'](filename);
97 var ret = nodeFS['readFileSync'](filename);
98 // The path is absolute if the normalized version is the same as the resolve d.
99 if (!ret && filename != nodePath['resolve'](filename)) {
100 filename = path.join(__dirname, '..', 'src', filename);
101 ret = nodeFS['readFileSync'](filename);
102 }
103 if (ret && !binary) ret = ret.toString();
104 return ret;
105 };
106
107 Module['readBinary'] = function readBinary(filename) { return Module['read'](f ilename, true) };
108
109 Module['load'] = function load(f) {
110 globalEval(read(f));
111 };
112
113 Module['arguments'] = process['argv'].slice(2);
114
115 module['exports'] = Module;
116 }
117 else if (ENVIRONMENT_IS_SHELL) {
118 if (!Module['print']) Module['print'] = print;
119 if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not pres ent in v8 or older sm
120
121 if (typeof read != 'undefined') {
122 Module['read'] = read;
123 } else {
124 Module['read'] = function read() { throw 'no read() available (jsc?)' };
125 }
126
127 Module['readBinary'] = function readBinary(f) {
128 return read(f, 'binary');
129 };
130
131 if (typeof scriptArgs != 'undefined') {
132 Module['arguments'] = scriptArgs;
133 } else if (typeof arguments != 'undefined') {
134 Module['arguments'] = arguments;
135 }
136
137 this['Module'] = Module;
138
139 eval("if (typeof gc === 'function' && gc.toString().indexOf('[native code]') > 0) var gc = undefined"); // wipe out the SpiderMonkey shell 'gc' function, whic h can confuse closure (uses it as a minified name, and it is then initted to a n on-falsey value unexpectedly)
140 }
141 else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
142 Module['read'] = function read(url) {
143 var xhr = new XMLHttpRequest();
144 xhr.open('GET', url, false);
145 xhr.send(null);
146 return xhr.responseText;
147 };
148
149 if (typeof arguments != 'undefined') {
150 Module['arguments'] = arguments;
151 }
152
153 if (typeof console !== 'undefined') {
154 if (!Module['print']) Module['print'] = function print(x) {
155 console.log(x);
156 };
157 if (!Module['printErr']) Module['printErr'] = function printErr(x) {
158 console.log(x);
159 };
160 } else {
161 // Probably a worker, and without console.log. We can do very little here...
162 var TRY_USE_DUMP = false;
163 if (!Module['print']) Module['print'] = (TRY_USE_DUMP && (typeof(dump) !== " undefined") ? (function(x) {
164 dump(x);
165 }) : (function(x) {
166 // self.postMessage(x); // enable this if you want stdout to be sent as me ssages
167 }));
168 }
169
170 if (ENVIRONMENT_IS_WEB) {
171 window['Module'] = Module;
172 } else {
173 Module['load'] = importScripts;
174 }
175 }
176 else {
177 // Unreachable because SHELL is dependant on the others
178 throw 'Unknown runtime environment. Where are we?';
179 }
180
181 function globalEval(x) {
182 eval.call(null, x);
183 }
184 if (!Module['load'] == 'undefined' && Module['read']) {
185 Module['load'] = function load(f) {
186 globalEval(Module['read'](f));
187 };
188 }
189 if (!Module['print']) {
190 Module['print'] = function(){};
191 }
192 if (!Module['printErr']) {
193 Module['printErr'] = Module['print'];
194 }
195 if (!Module['arguments']) {
196 Module['arguments'] = [];
197 }
198 // *** Environment setup code ***
199
200 // Closure helpers
201 Module.print = Module['print'];
202 Module.printErr = Module['printErr'];
203
204 // Callbacks
205 Module['preRun'] = [];
206 Module['postRun'] = [];
207
208 // Merge back in the overrides
209 for (var key in moduleOverrides) {
210 if (moduleOverrides.hasOwnProperty(key)) {
211 Module[key] = moduleOverrides[key];
212 }
213 }
214
215
216
217 // === Auto-generated preamble library stuff ===
218
219 //========================================
220 // Runtime code shared with compiler
221 //========================================
222
223 var Runtime = {
224 stackSave: function () {
225 return STACKTOP;
226 },
227 stackRestore: function (stackTop) {
228 STACKTOP = stackTop;
229 },
230 forceAlign: function (target, quantum) {
231 quantum = quantum || 4;
232 if (quantum == 1) return target;
233 if (isNumber(target) && isNumber(quantum)) {
234 return Math.ceil(target/quantum)*quantum;
235 } else if (isNumber(quantum) && isPowerOfTwo(quantum)) {
236 return '(((' +target + ')+' + (quantum-1) + ')&' + -quantum + ')';
237 }
238 return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
239 },
240 isNumberType: function (type) {
241 return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
242 },
243 isPointerType: function isPointerType(type) {
244 return type[type.length-1] == '*';
245 },
246 isStructType: function isStructType(type) {
247 if (isPointerType(type)) return false;
248 if (isArrayType(type)) return true;
249 if (/<?\{ ?[^}]* ?\}>?/.test(type)) return true; // { i32, i8 } etc. - anonymo us struct types
250 // See comment in isStructPointerType()
251 return type[0] == '%';
252 },
253 INT_TYPES: {"i1":0,"i8":0,"i16":0,"i32":0,"i64":0},
254 FLOAT_TYPES: {"float":0,"double":0},
255 or64: function (x, y) {
256 var l = (x | 0) | (y | 0);
257 var h = (Math.round(x / 4294967296) | Math.round(y / 4294967296)) * 42949672 96;
258 return l + h;
259 },
260 and64: function (x, y) {
261 var l = (x | 0) & (y | 0);
262 var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 42949672 96;
263 return l + h;
264 },
265 xor64: function (x, y) {
266 var l = (x | 0) ^ (y | 0);
267 var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 42949672 96;
268 return l + h;
269 },
270 getNativeTypeSize: function (type) {
271 switch (type) {
272 case 'i1': case 'i8': return 1;
273 case 'i16': return 2;
274 case 'i32': return 4;
275 case 'i64': return 8;
276 case 'float': return 4;
277 case 'double': return 8;
278 default: {
279 if (type[type.length-1] === '*') {
280 return Runtime.QUANTUM_SIZE; // A pointer
281 } else if (type[0] === 'i') {
282 var bits = parseInt(type.substr(1));
283 assert(bits % 8 === 0);
284 return bits/8;
285 } else {
286 return 0;
287 }
288 }
289 }
290 },
291 getNativeFieldSize: function (type) {
292 return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
293 },
294 dedup: function dedup(items, ident) {
295 var seen = {};
296 if (ident) {
297 return items.filter(function(item) {
298 if (seen[item[ident]]) return false;
299 seen[item[ident]] = true;
300 return true;
301 });
302 } else {
303 return items.filter(function(item) {
304 if (seen[item]) return false;
305 seen[item] = true;
306 return true;
307 });
308 }
309 },
310 set: function set() {
311 var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
312 var ret = {};
313 for (var i = 0; i < args.length; i++) {
314 ret[args[i]] = 0;
315 }
316 return ret;
317 },
318 STACK_ALIGN: 8,
319 getAlignSize: function (type, size, vararg) {
320 // we align i64s and doubles on 64-bit boundaries, unlike x86
321 if (!vararg && (type == 'i64' || type == 'double')) return 8;
322 if (!type) return Math.min(size, 8); // align structures internally to 64 bi ts
323 return Math.min(size || (type ? Runtime.getNativeFieldSize(type) : 0), Runti me.QUANTUM_SIZE);
324 },
325 calculateStructAlignment: function calculateStructAlignment(type) {
326 type.flatSize = 0;
327 type.alignSize = 0;
328 var diffs = [];
329 var prev = -1;
330 var index = 0;
331 type.flatIndexes = type.fields.map(function(field) {
332 index++;
333 var size, alignSize;
334 if (Runtime.isNumberType(field) || Runtime.isPointerType(field)) {
335 size = Runtime.getNativeTypeSize(field); // pack char; char; in structs, also char[X]s.
336 alignSize = Runtime.getAlignSize(field, size);
337 } else if (Runtime.isStructType(field)) {
338 if (field[1] === '0') {
339 // this is [0 x something]. When inside another structure like here, i t must be at the end,
340 // and it adds no size
341 // XXX this happens in java-nbody for example... assert(index === type .fields.length, 'zero-length in the middle!');
342 size = 0;
343 if (Types.types[field]) {
344 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize) ;
345 } else {
346 alignSize = type.alignSize || QUANTUM_SIZE;
347 }
348 } else {
349 size = Types.types[field].flatSize;
350 alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
351 }
352 } else if (field[0] == 'b') {
353 // bN, large number field, like a [N x i8]
354 size = field.substr(1)|0;
355 alignSize = 1;
356 } else if (field[0] === '<') {
357 // vector type
358 size = alignSize = Types.types[field].flatSize; // fully aligned
359 } else if (field[0] === 'i') {
360 // illegal integer field, that could not be legalized because it is an i nternal structure field
361 // it is ok to have such fields, if we just use them as markers of field size and nothing more complex
362 size = alignSize = parseInt(field.substr(1))/8;
363 assert(size % 1 === 0, 'cannot handle non-byte-size field ' + field);
364 } else {
365 assert(false, 'invalid type for calculateStructAlignment');
366 }
367 if (type.packed) alignSize = 1;
368 type.alignSize = Math.max(type.alignSize, alignSize);
369 var curr = Runtime.alignMemory(type.flatSize, alignSize); // if necessary, place this on aligned memory
370 type.flatSize = curr + size;
371 if (prev >= 0) {
372 diffs.push(curr-prev);
373 }
374 prev = curr;
375 return curr;
376 });
377 if (type.name_ && type.name_[0] === '[') {
378 // arrays have 2 elements, so we get the proper difference. then we scale here. that way we avoid
379 // allocating a potentially huge array for [999999 x i8] etc.
380 type.flatSize = parseInt(type.name_.substr(1))*type.flatSize/2;
381 }
382 type.flatSize = Runtime.alignMemory(type.flatSize, type.alignSize);
383 if (diffs.length == 0) {
384 type.flatFactor = type.flatSize;
385 } else if (Runtime.dedup(diffs).length == 1) {
386 type.flatFactor = diffs[0];
387 }
388 type.needsFlattening = (type.flatFactor != 1);
389 return type.flatIndexes;
390 },
391 generateStructInfo: function (struct, typeName, offset) {
392 var type, alignment;
393 if (typeName) {
394 offset = offset || 0;
395 type = (typeof Types === 'undefined' ? Runtime.typeInfo : Types.types)[typ eName];
396 if (!type) return null;
397 if (type.fields.length != struct.length) {
398 printErr('Number of named fields must match the type for ' + typeName + ': possibly duplicate struct names. Cannot return structInfo');
399 return null;
400 }
401 alignment = type.flatIndexes;
402 } else {
403 var type = { fields: struct.map(function(item) { return item[0] }) };
404 alignment = Runtime.calculateStructAlignment(type);
405 }
406 var ret = {
407 __size__: type.flatSize
408 };
409 if (typeName) {
410 struct.forEach(function(item, i) {
411 if (typeof item === 'string') {
412 ret[item] = alignment[i] + offset;
413 } else {
414 // embedded struct
415 var key;
416 for (var k in item) key = k;
417 ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], align ment[i]);
418 }
419 });
420 } else {
421 struct.forEach(function(item, i) {
422 ret[item[1]] = alignment[i];
423 });
424 }
425 return ret;
426 },
427 dynCall: function (sig, ptr, args) {
428 if (args && args.length) {
429 if (!args.splice) args = Array.prototype.slice.call(args);
430 args.splice(0, 0, ptr);
431 return Module['dynCall_' + sig].apply(null, args);
432 } else {
433 return Module['dynCall_' + sig].call(null, ptr);
434 }
435 },
436 functionPointers: [],
437 addFunction: function (func) {
438 for (var i = 0; i < Runtime.functionPointers.length; i++) {
439 if (!Runtime.functionPointers[i]) {
440 Runtime.functionPointers[i] = func;
441 return 2*(1 + i);
442 }
443 }
444 throw 'Finished up all reserved function pointers. Use a higher value for RE SERVED_FUNCTION_POINTERS.';
445 },
446 removeFunction: function (index) {
447 Runtime.functionPointers[(index-2)/2] = null;
448 },
449 getAsmConst: function (code, numArgs) {
450 // code is a constant string on the heap, so we can cache these
451 if (!Runtime.asmConstCache) Runtime.asmConstCache = {};
452 var func = Runtime.asmConstCache[code];
453 if (func) return func;
454 var args = [];
455 for (var i = 0; i < numArgs; i++) {
456 args.push(String.fromCharCode(36) + i); // $0, $1 etc
457 }
458 var source = Pointer_stringify(code);
459 if (source[0] === '"') {
460 // tolerate EM_ASM("..code..") even though EM_ASM(..code..) is correct
461 if (source.indexOf('"', 1) === source.length-1) {
462 source = source.substr(1, source.length-2);
463 } else {
464 // something invalid happened, e.g. EM_ASM("..code($0)..", input)
465 abort('invalid EM_ASM input |' + source + '|. Please use EM_ASM(..code.. ) (no quotes) or EM_ASM({ ..code($0).. }, input) (to input values)');
466 }
467 }
468 try {
469 var evalled = eval('(function(' + args.join(',') + '){ ' + source + ' })') ; // new Function does not allow upvars in node
470 } catch(e) {
471 Module.printErr('error in executing inline EM_ASM code: ' + e + ' on: \n\n ' + source + '\n\nwith args |' + args + '| (make sure to use the right one out o f EM_ASM, EM_ASM_ARGS, etc.)');
472 throw e;
473 }
474 return Runtime.asmConstCache[code] = evalled;
475 },
476 warnOnce: function (text) {
477 if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
478 if (!Runtime.warnOnce.shown[text]) {
479 Runtime.warnOnce.shown[text] = 1;
480 Module.printErr(text);
481 }
482 },
483 funcWrappers: {},
484 getFuncWrapper: function (func, sig) {
485 assert(sig);
486 if (!Runtime.funcWrappers[func]) {
487 Runtime.funcWrappers[func] = function dynCall_wrapper() {
488 return Runtime.dynCall(sig, func, arguments);
489 };
490 }
491 return Runtime.funcWrappers[func];
492 },
493 UTF8Processor: function () {
494 var buffer = [];
495 var needed = 0;
496 this.processCChar = function (code) {
497 code = code & 0xFF;
498
499 if (buffer.length == 0) {
500 if ((code & 0x80) == 0x00) { // 0xxxxxxx
501 return String.fromCharCode(code);
502 }
503 buffer.push(code);
504 if ((code & 0xE0) == 0xC0) { // 110xxxxx
505 needed = 1;
506 } else if ((code & 0xF0) == 0xE0) { // 1110xxxx
507 needed = 2;
508 } else { // 11110xxx
509 needed = 3;
510 }
511 return '';
512 }
513
514 if (needed) {
515 buffer.push(code);
516 needed--;
517 if (needed > 0) return '';
518 }
519
520 var c1 = buffer[0];
521 var c2 = buffer[1];
522 var c3 = buffer[2];
523 var c4 = buffer[3];
524 var ret;
525 if (buffer.length == 2) {
526 ret = String.fromCharCode(((c1 & 0x1F) << 6) | (c2 & 0x3F));
527 } else if (buffer.length == 3) {
528 ret = String.fromCharCode(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c 3 & 0x3F));
529 } else {
530 // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
531 var codePoint = ((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) |
532 ((c3 & 0x3F) << 6) | (c4 & 0x3F);
533 ret = String.fromCharCode(
534 Math.floor((codePoint - 0x10000) / 0x400) + 0xD800,
535 (codePoint - 0x10000) % 0x400 + 0xDC00);
536 }
537 buffer.length = 0;
538 return ret;
539 }
540 this.processJSString = function processJSString(string) {
541 /* TODO: use TextEncoder when present,
542 var encoder = new TextEncoder();
543 encoder['encoding'] = "utf-8";
544 var utf8Array = encoder['encode'](aMsg.data);
545 */
546 string = unescape(encodeURIComponent(string));
547 var ret = [];
548 for (var i = 0; i < string.length; i++) {
549 ret.push(string.charCodeAt(i));
550 }
551 return ret;
552 }
553 },
554 getCompilerSetting: function (name) {
555 throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getComp ilerSetting or emscripten_get_compiler_setting to work';
556 },
557 stackAlloc: function (size) { var ret = STACKTOP;STACKTOP = (STACKTOP + size)| 0;STACKTOP = (((STACKTOP)+7)&-8); return ret; },
558 staticAlloc: function (size) { var ret = STATICTOP;STATICTOP = (STATICTOP + si ze)|0;STATICTOP = (((STATICTOP)+7)&-8); return ret; },
559 dynamicAlloc: function (size) { var ret = DYNAMICTOP;DYNAMICTOP = (DYNAMICTOP + size)|0;DYNAMICTOP = (((DYNAMICTOP)+7)&-8); if (DYNAMICTOP >= TOTAL_MEMORY) en largeMemory();; return ret; },
560 alignMemory: function (size,quantum) { var ret = size = Math.ceil((size)/(quan tum ? quantum : 8))*(quantum ? quantum : 8); return ret; },
561 makeBigInt: function (low,high,unsigned) { var ret = (unsigned ? ((+((low>>>0) ))+((+((high>>>0)))*(+4294967296))) : ((+((low>>>0)))+((+((high|0)))*(+429496729 6)))); return ret; },
562 GLOBAL_BASE: 8,
563 QUANTUM_SIZE: 4,
564 __dummy__: 0
565 }
566
567
568 Module['Runtime'] = Runtime;
569
570
571
572
573
574
575
576
577
578 //========================================
579 // Runtime essentials
580 //========================================
581
582 var __THREW__ = 0; // Used in checking for thrown exceptions.
583
584 var ABORT = false; // whether we are quitting the application. no code should ru n after this. set in exit() and abort()
585 var EXITSTATUS = 0;
586
587 var undef = 0;
588 // tempInt is used for 32-bit signed values or smaller. tempBigInt is used
589 // for 32-bit unsigned values or more than 32 bits. TODO: audit all uses of temp Int
590 var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI , tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD, tempDouble, tempFloat;
591 var tempI64, tempI64b;
592 var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRe t7, tempRet8, tempRet9;
593
594 function assert(condition, text) {
595 if (!condition) {
596 abort('Assertion failed: ' + text);
597 }
598 }
599
600 var globalScope = this;
601
602 // C calling interface. A convenient way to call C functions (in C files, or
603 // defined with extern "C").
604 //
605 // Note: LLVM optimizations can inline and remove functions, after which you wil l not be
606 // able to call them. Closure can also do so. To avoid that, add your func tion to
607 // the exports using something like
608 //
609 // -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
610 //
611 // @param ident The name of the C function (note that C++ functions will be name-mangled - use extern "C")
612 // @param returnType The return type of the function, one of the JS types 'numbe r', 'string' or 'array' (use 'number' for any C pointer, and
613 // 'array' for JavaScript arrays and typed arrays; note that a rrays are 8-bit).
614 // @param argTypes An array of the types of arguments for the function (if the re are no arguments, this can be ommitted). Types are as in returnType,
615 // except that 'array' is not possible (there is no way for us to know the length of the array)
616 // @param args An array of the arguments to the function, as native JS val ues (as in returnType)
617 // Note that string arguments will be stored on the stack (the JS string will become a C string on the stack).
618 // @return The return value, as a native JS value (as in returnType)
619 function ccall(ident, returnType, argTypes, args) {
620 return ccallFunc(getCFunc(ident), returnType, argTypes, args);
621 }
622 Module["ccall"] = ccall;
623
624 // Returns the C function with a specified identifier (for C++, you need to do m anual name mangling)
625 function getCFunc(ident) {
626 try {
627 var func = Module['_' + ident]; // closure exported function
628 if (!func) func = eval('_' + ident); // explicit lookup
629 } catch(e) {
630 }
631 assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimiz ations or closure removed it?)');
632 return func;
633 }
634
635 // Internal function that does a C call using a function, not an identifier
636 function ccallFunc(func, returnType, argTypes, args) {
637 var stack = 0;
638 function toC(value, type) {
639 if (type == 'string') {
640 if (value === null || value === undefined || value === 0) return 0; // nul l string
641 value = intArrayFromString(value);
642 type = 'array';
643 }
644 if (type == 'array') {
645 if (!stack) stack = Runtime.stackSave();
646 var ret = Runtime.stackAlloc(value.length);
647 writeArrayToMemory(value, ret);
648 return ret;
649 }
650 return value;
651 }
652 function fromC(value, type) {
653 if (type == 'string') {
654 return Pointer_stringify(value);
655 }
656 assert(type != 'array');
657 return value;
658 }
659 var i = 0;
660 var cArgs = args ? args.map(function(arg) {
661 return toC(arg, argTypes[i++]);
662 }) : [];
663 var ret = fromC(func.apply(null, cArgs), returnType);
664 if (stack) Runtime.stackRestore(stack);
665 return ret;
666 }
667
668 // Returns a native JS wrapper for a C function. This is similar to ccall, but
669 // returns a function you can call repeatedly in a normal way. For example:
670 //
671 // var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
672 // alert(my_function(5, 22));
673 // alert(my_function(99, 12));
674 //
675 function cwrap(ident, returnType, argTypes) {
676 var func = getCFunc(ident);
677 return function() {
678 return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(argu ments));
679 }
680 }
681 Module["cwrap"] = cwrap;
682
683 // Sets a value in memory in a dynamic way at run-time. Uses the
684 // type data. This is the same as makeSetValue, except that
685 // makeSetValue is done at compile-time and generates the needed
686 // code then, whereas this function picks the right code at
687 // run-time.
688 // Note that setValue and getValue only do *aligned* writes and reads!
689 // Note that ccall uses JS types as for defining types, while setValue and
690 // getValue need LLVM types ('i8', 'i32') - this is a lower-level operation
691 function setValue(ptr, value, type, noSafe) {
692 type = type || 'i8';
693 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
694 switch(type) {
695 case 'i1': HEAP8[(ptr)]=value; break;
696 case 'i8': HEAP8[(ptr)]=value; break;
697 case 'i16': HEAP16[((ptr)>>1)]=value; break;
698 case 'i32': HEAP32[((ptr)>>2)]=value; break;
699 case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble ))) >= (+1) ? (tempDouble > (+0) ? ((Math_min((+(Math_floor((tempDouble)/(+42949 67296)))), (+4294967295)))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDo uble)))>>>0))/(+4294967296))))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32 [(((ptr)+(4))>>2)]=tempI64[1]); break;
700 case 'float': HEAPF32[((ptr)>>2)]=value; break;
701 case 'double': HEAPF64[((ptr)>>3)]=value; break;
702 default: abort('invalid type for setValue: ' + type);
703 }
704 }
705 Module['setValue'] = setValue;
706
707 // Parallel to setValue.
708 function getValue(ptr, type, noSafe) {
709 type = type || 'i8';
710 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
711 switch(type) {
712 case 'i1': return HEAP8[(ptr)];
713 case 'i8': return HEAP8[(ptr)];
714 case 'i16': return HEAP16[((ptr)>>1)];
715 case 'i32': return HEAP32[((ptr)>>2)];
716 case 'i64': return HEAP32[((ptr)>>2)];
717 case 'float': return HEAPF32[((ptr)>>2)];
718 case 'double': return HEAPF64[((ptr)>>3)];
719 default: abort('invalid type for setValue: ' + type);
720 }
721 return null;
722 }
723 Module['getValue'] = getValue;
724
725 var ALLOC_NORMAL = 0; // Tries to use _malloc()
726 var ALLOC_STACK = 1; // Lives for the duration of the current function call
727 var ALLOC_STATIC = 2; // Cannot be freed
728 var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
729 var ALLOC_NONE = 4; // Do not allocate
730 Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
731 Module['ALLOC_STACK'] = ALLOC_STACK;
732 Module['ALLOC_STATIC'] = ALLOC_STATIC;
733 Module['ALLOC_DYNAMIC'] = ALLOC_DYNAMIC;
734 Module['ALLOC_NONE'] = ALLOC_NONE;
735
736 // allocate(): This is for internal use. You can use it yourself as well, but th e interface
737 // is a little tricky (see docs right below). The reason is that it is optimized
738 // for multiple syntaxes to save space in generated code. So you sho uld
739 // normally not use allocate(), and instead allocate memory using _m alloc(),
740 // initialize it with setValue(), and so forth.
741 // @slab: An array of data, or a number. If a number, then the size of the block to allocate,
742 // in *bytes* (note that this is sometimes confusing: the next parameter does not
743 // affect this!)
744 // @types: Either an array of types, one for each byte (or 0 if no type at that position),
745 // or a single type which is used for the entire block. This only matter s if there
746 // is initial data - if @slab is a number, then this does not matter at all and is
747 // ignored.
748 // @allocator: How to allocate memory, see ALLOC_*
749 function allocate(slab, types, allocator, ptr) {
750 var zeroinit, size;
751 if (typeof slab === 'number') {
752 zeroinit = true;
753 size = slab;
754 } else {
755 zeroinit = false;
756 size = slab.length;
757 }
758
759 var singleType = typeof types === 'string' ? types : null;
760
761 var ret;
762 if (allocator == ALLOC_NONE) {
763 ret = ptr;
764 } else {
765 ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAllo c][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
766 }
767
768 if (zeroinit) {
769 var ptr = ret, stop;
770 assert((ret & 3) == 0);
771 stop = ret + (size & ~3);
772 for (; ptr < stop; ptr += 4) {
773 HEAP32[((ptr)>>2)]=0;
774 }
775 stop = ret + size;
776 while (ptr < stop) {
777 HEAP8[((ptr++)|0)]=0;
778 }
779 return ret;
780 }
781
782 if (singleType === 'i8') {
783 if (slab.subarray || slab.slice) {
784 HEAPU8.set(slab, ret);
785 } else {
786 HEAPU8.set(new Uint8Array(slab), ret);
787 }
788 return ret;
789 }
790
791 var i = 0, type, typeSize, previousType;
792 while (i < size) {
793 var curr = slab[i];
794
795 if (typeof curr === 'function') {
796 curr = Runtime.getFunctionIndex(curr);
797 }
798
799 type = singleType || types[i];
800 if (type === 0) {
801 i++;
802 continue;
803 }
804
805 if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
806
807 setValue(ret+i, curr, type);
808
809 // no need to look up size unless type changes, so cache it
810 if (previousType !== type) {
811 typeSize = Runtime.getNativeTypeSize(type);
812 previousType = type;
813 }
814 i += typeSize;
815 }
816
817 return ret;
818 }
819 Module['allocate'] = allocate;
820
821 function Pointer_stringify(ptr, /* optional */ length) {
822 // TODO: use TextDecoder
823 // Find the length, and check for UTF while doing so
824 var hasUtf = false;
825 var t;
826 var i = 0;
827 while (1) {
828 t = HEAPU8[(((ptr)+(i))|0)];
829 if (t >= 128) hasUtf = true;
830 else if (t == 0 && !length) break;
831 i++;
832 if (length && i == length) break;
833 }
834 if (!length) length = i;
835
836 var ret = '';
837
838 if (!hasUtf) {
839 var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge stri ng can overflow the stack
840 var curr;
841 while (length > 0) {
842 curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.m in(length, MAX_CHUNK)));
843 ret = ret ? ret + curr : curr;
844 ptr += MAX_CHUNK;
845 length -= MAX_CHUNK;
846 }
847 return ret;
848 }
849
850 var utf8 = new Runtime.UTF8Processor();
851 for (i = 0; i < length; i++) {
852 t = HEAPU8[(((ptr)+(i))|0)];
853 ret += utf8.processCChar(t);
854 }
855 return ret;
856 }
857 Module['Pointer_stringify'] = Pointer_stringify;
858
859 // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emsc ripten HEAP, returns
860 // a copy of that string as a Javascript String object.
861 function UTF16ToString(ptr) {
862 var i = 0;
863
864 var str = '';
865 while (1) {
866 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
867 if (codeUnit == 0)
868 return str;
869 ++i;
870 // fromCharCode constructs a character from a UTF-16 code unit, so we can pa ss the UTF16 string right through.
871 str += String.fromCharCode(codeUnit);
872 }
873 }
874 Module['UTF16ToString'] = UTF16ToString;
875
876 // Copies the given Javascript String object 'str' to the emscripten HEAP at add ress 'outPtr',
877 // null-terminated and encoded in UTF16LE form. The copy will require at most (s tr.length*2+1)*2 bytes of space in the HEAP.
878 function stringToUTF16(str, outPtr) {
879 for(var i = 0; i < str.length; ++i) {
880 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly writ ten to the HEAP.
881 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
882 HEAP16[(((outPtr)+(i*2))>>1)]=codeUnit;
883 }
884 // Null-terminate the pointer to the HEAP.
885 HEAP16[(((outPtr)+(str.length*2))>>1)]=0;
886 }
887 Module['stringToUTF16'] = stringToUTF16;
888
889 // Given a pointer 'ptr' to a null-terminated UTF32LE-encoded string in the emsc ripten HEAP, returns
890 // a copy of that string as a Javascript String object.
891 function UTF32ToString(ptr) {
892 var i = 0;
893
894 var str = '';
895 while (1) {
896 var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
897 if (utf32 == 0)
898 return str;
899 ++i;
900 // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (p air), not from a Unicode code point! So encode the code point to UTF-16 for cons tructing.
901 if (utf32 >= 0x10000) {
902 var ch = utf32 - 0x10000;
903 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
904 } else {
905 str += String.fromCharCode(utf32);
906 }
907 }
908 }
909 Module['UTF32ToString'] = UTF32ToString;
910
911 // Copies the given Javascript String object 'str' to the emscripten HEAP at add ress 'outPtr',
912 // null-terminated and encoded in UTF32LE form. The copy will require at most (s tr.length+1)*4 bytes of space in the HEAP,
913 // but can use less, since str.length does not return the number of characters i n the string, but the number of UTF-16 code units in the string.
914 function stringToUTF32(str, outPtr) {
915 var iChar = 0;
916 for(var iCodeUnit = 0; iCodeUnit < str.length; ++iCodeUnit) {
917 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code un it, not a Unicode code point of the character! We must decode the string to UTF- 32 to the heap.
918 var codeUnit = str.charCodeAt(iCodeUnit); // possibly a lead surrogate
919 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
920 var trailSurrogate = str.charCodeAt(++iCodeUnit);
921 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF) ;
922 }
923 HEAP32[(((outPtr)+(iChar*4))>>2)]=codeUnit;
924 ++iChar;
925 }
926 // Null-terminate the pointer to the HEAP.
927 HEAP32[(((outPtr)+(iChar*4))>>2)]=0;
928 }
929 Module['stringToUTF32'] = stringToUTF32;
930
931 function demangle(func) {
932 var i = 3;
933 // params, etc.
934 var basicTypes = {
935 'v': 'void',
936 'b': 'bool',
937 'c': 'char',
938 's': 'short',
939 'i': 'int',
940 'l': 'long',
941 'f': 'float',
942 'd': 'double',
943 'w': 'wchar_t',
944 'a': 'signed char',
945 'h': 'unsigned char',
946 't': 'unsigned short',
947 'j': 'unsigned int',
948 'm': 'unsigned long',
949 'x': 'long long',
950 'y': 'unsigned long long',
951 'z': '...'
952 };
953 var subs = [];
954 var first = true;
955 function dump(x) {
956 //return;
957 if (x) Module.print(x);
958 Module.print(func);
959 var pre = '';
960 for (var a = 0; a < i; a++) pre += ' ';
961 Module.print (pre + '^');
962 }
963 function parseNested() {
964 i++;
965 if (func[i] === 'K') i++; // ignore const
966 var parts = [];
967 while (func[i] !== 'E') {
968 if (func[i] === 'S') { // substitution
969 i++;
970 var next = func.indexOf('_', i);
971 var num = func.substring(i, next) || 0;
972 parts.push(subs[num] || '?');
973 i = next+1;
974 continue;
975 }
976 if (func[i] === 'C') { // constructor
977 parts.push(parts[parts.length-1]);
978 i += 2;
979 continue;
980 }
981 var size = parseInt(func.substr(i));
982 var pre = size.toString().length;
983 if (!size || !pre) { i--; break; } // counter i++ below us
984 var curr = func.substr(i + pre, size);
985 parts.push(curr);
986 subs.push(curr);
987 i += pre + size;
988 }
989 i++; // skip E
990 return parts;
991 }
992 function parse(rawList, limit, allowVoid) { // main parser
993 limit = limit || Infinity;
994 var ret = '', list = [];
995 function flushList() {
996 return '(' + list.join(', ') + ')';
997 }
998 var name;
999 if (func[i] === 'N') {
1000 // namespaced N-E
1001 name = parseNested().join('::');
1002 limit--;
1003 if (limit === 0) return rawList ? [name] : name;
1004 } else {
1005 // not namespaced
1006 if (func[i] === 'K' || (first && func[i] === 'L')) i++; // ignore const an d first 'L'
1007 var size = parseInt(func.substr(i));
1008 if (size) {
1009 var pre = size.toString().length;
1010 name = func.substr(i + pre, size);
1011 i += pre + size;
1012 }
1013 }
1014 first = false;
1015 if (func[i] === 'I') {
1016 i++;
1017 var iList = parse(true);
1018 var iRet = parse(true, 1, true);
1019 ret += iRet[0] + ' ' + name + '<' + iList.join(', ') + '>';
1020 } else {
1021 ret = name;
1022 }
1023 paramLoop: while (i < func.length && limit-- > 0) {
1024 //dump('paramLoop');
1025 var c = func[i++];
1026 if (c in basicTypes) {
1027 list.push(basicTypes[c]);
1028 } else {
1029 switch (c) {
1030 case 'P': list.push(parse(true, 1, true)[0] + '*'); break; // pointer
1031 case 'R': list.push(parse(true, 1, true)[0] + '&'); break; // referenc e
1032 case 'L': { // literal
1033 i++; // skip basic type
1034 var end = func.indexOf('E', i);
1035 var size = end - i;
1036 list.push(func.substr(i, size));
1037 i += size + 2; // size + 'EE'
1038 break;
1039 }
1040 case 'A': { // array
1041 var size = parseInt(func.substr(i));
1042 i += size.toString().length;
1043 if (func[i] !== '_') throw '?';
1044 i++; // skip _
1045 list.push(parse(true, 1, true)[0] + ' [' + size + ']');
1046 break;
1047 }
1048 case 'E': break paramLoop;
1049 default: ret += '?' + c; break paramLoop;
1050 }
1051 }
1052 }
1053 if (!allowVoid && list.length === 1 && list[0] === 'void') list = []; // avo id (void)
1054 if (rawList) {
1055 if (ret) {
1056 list.push(ret + '?');
1057 }
1058 return list;
1059 } else {
1060 return ret + flushList();
1061 }
1062 }
1063 try {
1064 // Special-case the entry point, since its name differs from other name mang ling.
1065 if (func == 'Object._main' || func == '_main') {
1066 return 'main()';
1067 }
1068 if (typeof func === 'number') func = Pointer_stringify(func);
1069 if (func[0] !== '_') return func;
1070 if (func[1] !== '_') return func; // C function
1071 if (func[2] !== 'Z') return func;
1072 switch (func[3]) {
1073 case 'n': return 'operator new()';
1074 case 'd': return 'operator delete()';
1075 }
1076 return parse();
1077 } catch(e) {
1078 return func;
1079 }
1080 }
1081
1082 function demangleAll(text) {
1083 return text.replace(/__Z[\w\d_]+/g, function(x) { var y = demangle(x); return x === y ? x : (x + ' [' + y + ']') });
1084 }
1085
1086 function stackTrace() {
1087 var stack = new Error().stack;
1088 return stack ? demangleAll(stack) : '(no stack trace available)'; // Stack tra ce is not available at least on IE10 and Safari 6.
1089 }
1090
1091 // Memory management
1092
1093 var PAGE_SIZE = 4096;
1094 function alignMemoryPage(x) {
1095 return (x+4095)&-4096;
1096 }
1097
1098 var HEAP;
1099 var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
1100
1101 var STATIC_BASE = 0, STATICTOP = 0, staticSealed = false; // static area
1102 var STACK_BASE = 0, STACKTOP = 0, STACK_MAX = 0; // stack area
1103 var DYNAMIC_BASE = 0, DYNAMICTOP = 0; // dynamic area handled by sbrk
1104
1105 function enlargeMemory() {
1106 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 ALL OW_MEMORY_GROWTH which adjusts the size at runtime but prevents some optimizatio ns, or (3) set Module.TOTAL_MEMORY before the program runs.');
1107 }
1108
1109 var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
1110 var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 134217728;
1111 var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
1112
1113 var totalMemory = 4096;
1114 while (totalMemory < TOTAL_MEMORY || totalMemory < 2*TOTAL_STACK) {
1115 if (totalMemory < 16*1024*1024) {
1116 totalMemory *= 2;
1117 } else {
1118 totalMemory += 16*1024*1024
1119 }
1120 }
1121 if (totalMemory !== TOTAL_MEMORY) {
1122 Module.printErr('increasing TOTAL_MEMORY to ' + totalMemory + ' to be more rea sonable');
1123 TOTAL_MEMORY = totalMemory;
1124 }
1125
1126 // Initialize the runtime's memory
1127 // check for full engine support (use string 'subarray' to avoid closure compile r confusion)
1128 assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
1129 'JS engine does not provide full typed array support');
1130
1131 var buffer = new ArrayBuffer(TOTAL_MEMORY);
1132 HEAP8 = new Int8Array(buffer);
1133 HEAP16 = new Int16Array(buffer);
1134 HEAP32 = new Int32Array(buffer);
1135 HEAPU8 = new Uint8Array(buffer);
1136 HEAPU16 = new Uint16Array(buffer);
1137 HEAPU32 = new Uint32Array(buffer);
1138 HEAPF32 = new Float32Array(buffer);
1139 HEAPF64 = new Float64Array(buffer);
1140
1141 // Endianness check (note: assumes compiler arch was little-endian)
1142 HEAP32[0] = 255;
1143 assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a li ttle-endian system');
1144
1145 Module['HEAP'] = HEAP;
1146 Module['HEAP8'] = HEAP8;
1147 Module['HEAP16'] = HEAP16;
1148 Module['HEAP32'] = HEAP32;
1149 Module['HEAPU8'] = HEAPU8;
1150 Module['HEAPU16'] = HEAPU16;
1151 Module['HEAPU32'] = HEAPU32;
1152 Module['HEAPF32'] = HEAPF32;
1153 Module['HEAPF64'] = HEAPF64;
1154
1155 function callRuntimeCallbacks(callbacks) {
1156 while(callbacks.length > 0) {
1157 var callback = callbacks.shift();
1158 if (typeof callback == 'function') {
1159 callback();
1160 continue;
1161 }
1162 var func = callback.func;
1163 if (typeof func === 'number') {
1164 if (callback.arg === undefined) {
1165 Runtime.dynCall('v', func);
1166 } else {
1167 Runtime.dynCall('vi', func, [callback.arg]);
1168 }
1169 } else {
1170 func(callback.arg === undefined ? null : callback.arg);
1171 }
1172 }
1173 }
1174
1175 var __ATPRERUN__ = []; // functions called before the runtime is initialized
1176 var __ATINIT__ = []; // functions called during startup
1177 var __ATMAIN__ = []; // functions called when main() is to be run
1178 var __ATEXIT__ = []; // functions called during shutdown
1179 var __ATPOSTRUN__ = []; // functions called after the runtime has exited
1180
1181 var runtimeInitialized = false;
1182
1183 function preRun() {
1184 // compatibility - merge in anything from Module['preRun'] at this time
1185 if (Module['preRun']) {
1186 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRu n']];
1187 while (Module['preRun'].length) {
1188 addOnPreRun(Module['preRun'].shift());
1189 }
1190 }
1191 callRuntimeCallbacks(__ATPRERUN__);
1192 }
1193
1194 function ensureInitRuntime() {
1195 if (runtimeInitialized) return;
1196 runtimeInitialized = true;
1197 callRuntimeCallbacks(__ATINIT__);
1198 }
1199
1200 function preMain() {
1201 callRuntimeCallbacks(__ATMAIN__);
1202 }
1203
1204 function exitRuntime() {
1205 callRuntimeCallbacks(__ATEXIT__);
1206 }
1207
1208 function postRun() {
1209 // compatibility - merge in anything from Module['postRun'] at this time
1210 if (Module['postRun']) {
1211 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['pos tRun']];
1212 while (Module['postRun'].length) {
1213 addOnPostRun(Module['postRun'].shift());
1214 }
1215 }
1216 callRuntimeCallbacks(__ATPOSTRUN__);
1217 }
1218
1219 function addOnPreRun(cb) {
1220 __ATPRERUN__.unshift(cb);
1221 }
1222 Module['addOnPreRun'] = Module.addOnPreRun = addOnPreRun;
1223
1224 function addOnInit(cb) {
1225 __ATINIT__.unshift(cb);
1226 }
1227 Module['addOnInit'] = Module.addOnInit = addOnInit;
1228
1229 function addOnPreMain(cb) {
1230 __ATMAIN__.unshift(cb);
1231 }
1232 Module['addOnPreMain'] = Module.addOnPreMain = addOnPreMain;
1233
1234 function addOnExit(cb) {
1235 __ATEXIT__.unshift(cb);
1236 }
1237 Module['addOnExit'] = Module.addOnExit = addOnExit;
1238
1239 function addOnPostRun(cb) {
1240 __ATPOSTRUN__.unshift(cb);
1241 }
1242 Module['addOnPostRun'] = Module.addOnPostRun = addOnPostRun;
1243
1244 // Tools
1245
1246 // This processes a JS string into a C-line array of numbers, 0-terminated.
1247 // For LLVM-originating strings, see parser.js:parseLLVMString function
1248 function intArrayFromString(stringy, dontAddNull, length /* optional */) {
1249 var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
1250 if (length) {
1251 ret.length = length;
1252 }
1253 if (!dontAddNull) {
1254 ret.push(0);
1255 }
1256 return ret;
1257 }
1258 Module['intArrayFromString'] = intArrayFromString;
1259
1260 function intArrayToString(array) {
1261 var ret = [];
1262 for (var i = 0; i < array.length; i++) {
1263 var chr = array[i];
1264 if (chr > 0xFF) {
1265 chr &= 0xFF;
1266 }
1267 ret.push(String.fromCharCode(chr));
1268 }
1269 return ret.join('');
1270 }
1271 Module['intArrayToString'] = intArrayToString;
1272
1273 // Write a Javascript array to somewhere in the heap
1274 function writeStringToMemory(string, buffer, dontAddNull) {
1275 var array = intArrayFromString(string, dontAddNull);
1276 var i = 0;
1277 while (i < array.length) {
1278 var chr = array[i];
1279 HEAP8[(((buffer)+(i))|0)]=chr;
1280 i = i + 1;
1281 }
1282 }
1283 Module['writeStringToMemory'] = writeStringToMemory;
1284
1285 function writeArrayToMemory(array, buffer) {
1286 for (var i = 0; i < array.length; i++) {
1287 HEAP8[(((buffer)+(i))|0)]=array[i];
1288 }
1289 }
1290 Module['writeArrayToMemory'] = writeArrayToMemory;
1291
1292 function writeAsciiToMemory(str, buffer, dontAddNull) {
1293 for (var i = 0; i < str.length; i++) {
1294 HEAP8[(((buffer)+(i))|0)]=str.charCodeAt(i);
1295 }
1296 if (!dontAddNull) HEAP8[(((buffer)+(str.length))|0)]=0;
1297 }
1298 Module['writeAsciiToMemory'] = writeAsciiToMemory;
1299
1300 function unSign(value, bits, ignore) {
1301 if (value >= 0) {
1302 return value;
1303 }
1304 return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value // Need some trickery, s ince if bits == 32, we are right at the limit of the bits JS uses in bitshifts
1305 : Math.pow(2, bits) + value;
1306 }
1307 function reSign(value, bits, ignore) {
1308 if (value <= 0) {
1309 return value;
1310 }
1311 var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1312 : Math.pow(2, bits-1);
1313 if (value >= half && (bits <= 32 || value > half)) { // for huge values, we ca n hit the precision limit and always get true here. so don't do that
1314 // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1315 // TODO: In i64 mode 1, r esign the two parts separately and safely
1316 value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1317 }
1318 return value;
1319 }
1320
1321 // check for imul support, and also for correctness ( https://bugs.webkit.org/sh ow_bug.cgi?id=126345 )
1322 if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
1323 var ah = a >>> 16;
1324 var al = a & 0xffff;
1325 var bh = b >>> 16;
1326 var bl = b & 0xffff;
1327 return (al*bl + ((ah*bl + al*bh) << 16))|0;
1328 };
1329 Math.imul = Math['imul'];
1330
1331
1332 var Math_abs = Math.abs;
1333 var Math_cos = Math.cos;
1334 var Math_sin = Math.sin;
1335 var Math_tan = Math.tan;
1336 var Math_acos = Math.acos;
1337 var Math_asin = Math.asin;
1338 var Math_atan = Math.atan;
1339 var Math_atan2 = Math.atan2;
1340 var Math_exp = Math.exp;
1341 var Math_log = Math.log;
1342 var Math_sqrt = Math.sqrt;
1343 var Math_ceil = Math.ceil;
1344 var Math_floor = Math.floor;
1345 var Math_pow = Math.pow;
1346 var Math_imul = Math.imul;
1347 var Math_fround = Math.fround;
1348 var Math_min = Math.min;
1349
1350 // A counter of dependencies for calling run(). If we need to
1351 // do asynchronous work before running, increment this and
1352 // decrement it. Incrementing must happen in a place like
1353 // PRE_RUN_ADDITIONS (used by emcc to add file preloading).
1354 // Note that you can add dependencies in preRun, even though
1355 // it happens right before run - run will be postponed until
1356 // the dependencies are met.
1357 var runDependencies = 0;
1358 var runDependencyWatcher = null;
1359 var dependenciesFulfilled = null; // overridden to take different actions when a ll run dependencies are fulfilled
1360
1361 function addRunDependency(id) {
1362 runDependencies++;
1363 if (Module['monitorRunDependencies']) {
1364 Module['monitorRunDependencies'](runDependencies);
1365 }
1366 }
1367 Module['addRunDependency'] = addRunDependency;
1368 function removeRunDependency(id) {
1369 runDependencies--;
1370 if (Module['monitorRunDependencies']) {
1371 Module['monitorRunDependencies'](runDependencies);
1372 }
1373 if (runDependencies == 0) {
1374 if (runDependencyWatcher !== null) {
1375 clearInterval(runDependencyWatcher);
1376 runDependencyWatcher = null;
1377 }
1378 if (dependenciesFulfilled) {
1379 var callback = dependenciesFulfilled;
1380 dependenciesFulfilled = null;
1381 callback(); // can add another dependenciesFulfilled
1382 }
1383 }
1384 }
1385 Module['removeRunDependency'] = removeRunDependency;
1386
1387 Module["preloadedImages"] = {}; // maps url to image data
1388 Module["preloadedAudios"] = {}; // maps url to audio data
1389
1390
1391 var memoryInitializer = null;
1392
1393 // === Body ===
1394
1395
1396
1397
1398
1399 STATIC_BASE = 8;
1400
1401 STATICTOP = STATIC_BASE + Runtime.alignMemory(547);
1402 /* global initializers */ __ATINIT__.push();
1403
1404
1405 /* memory initializer */ allocate([101,114,114,111,114,58,32,37,100,10,0,0,0,0,0 ,0,80,102,97,110,110,107,117,99,104,101,110,40,37,100,41,32,61,32,37,100,46,10,0 ,0,37,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], "i8", ALLOC_NONE, Runtim e.GLOBAL_BASE);
1406
1407
1408
1409
1410 var tempDoublePtr = Runtime.alignMemory(allocate(12, "i8", ALLOC_STATIC), 8);
1411
1412 assert(tempDoublePtr % 8 == 0);
1413
1414 function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1415
1416 HEAP8[tempDoublePtr] = HEAP8[ptr];
1417
1418 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1419
1420 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1421
1422 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1423
1424 }
1425
1426 function copyTempDouble(ptr) {
1427
1428 HEAP8[tempDoublePtr] = HEAP8[ptr];
1429
1430 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1431
1432 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1433
1434 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1435
1436 HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1437
1438 HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1439
1440 HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1441
1442 HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1443
1444 }
1445
1446
1447
1448
1449
1450
1451 var ERRNO_CODES={EPERM:1,ENOENT:2,ESRCH:3,EINTR:4,EIO:5,ENXIO:6,E2BIG:7,ENOEXE C:8,EBADF:9,ECHILD:10,EAGAIN:11,EWOULDBLOCK:11,ENOMEM:12,EACCES:13,EFAULT:14,ENO TBLK:15,EBUSY:16,EEXIST:17,EXDEV:18,ENODEV:19,ENOTDIR:20,EISDIR:21,EINVAL:22,ENF ILE:23,EMFILE:24,ENOTTY:25,ETXTBSY:26,EFBIG:27,ENOSPC:28,ESPIPE:29,EROFS:30,EMLI NK: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,EBAD E:52,EBADR:53,EXFULL:54,ENOANO:55,EBADRQC:56,EBADSLT:57,EDEADLOCK:35,EBFONT:59,E NOSTR: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,E CONNRESET: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,EALRE ADY:114,EDESTADDRREQ:89,EMSGSIZE:90,EPROTONOSUPPORT:93,ESOCKTNOSUPPORT:94,EADDRN OTAVAIL:99,ENETRESET:102,EISCONN:106,ENOTCONN:107,ETOOMANYREFS:109,EUSERS:87,EDQ UOT:122,ESTALE:116,ENOTSUP:95,ENOMEDIUM:123,EILSEQ:84,EOVERFLOW:75,ECANCELED:125 ,ENOTRECOVERABLE:131,EOWNERDEAD:130,ESTRPIPE:86};
1452
1453 var ERRNO_MESSAGES={0:"Success",1:"Not super-user",2:"No such file or director y",3:"No such process",4:"Interrupted system call",5:"I/O error",6:"No such devi ce or address",7:"Arg list too long",8:"Exec format error",9:"Bad file number",1 0:"No children",11:"No more processes",12:"Not enough core",13:"Permission denie d",14:"Bad address",15:"Block device required",16:"Mount device busy",17:"File e xists",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:"N o space left on device",29:"Illegal seek",30:"Read only file system",31:"Too man y links",32:"Broken pipe",33:"Math arg out of domain of func",34:"Math result no t 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:"Identif ier 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 dr iver not attached",50:"No CSI structure available",51:"Level 2 halted",52:"Inval id 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 r esources",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:"Srmoun t error",70:"Communication error on send",71:"Protocol error",72:"Multihop attem pted",73:"Cross mount point (not really error)",74:"Trying to read unreadable me ssage",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 acc ess 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 e xec a shared library",84:"Illegal byte sequence",86:"Streams pipe error",87:"Too many users",88:"Socket operation on non-socket",89:"Destination address require d",90:"Message too long",91:"Protocol wrong type for socket",92:"Protocol not av ailable",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 int erface 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:"Connectio n timed out",111:"Connection refused",112:"Host is down",113:"Host is unreachabl e",114:"Socket already connected",115:"Connection already in progress",116:"Stal e file handle",122:"Quota exceeded",123:"No medium (in tape drive)",125:"Operati on canceled",130:"Previous owner died",131:"State not recoverable"};
1454
1455
1456 var ___errno_state=0;function ___setErrNo(value) {
1457 // For convenient setting and returning of errno.
1458 HEAP32[((___errno_state)>>2)]=value;
1459 return value;
1460 }
1461
1462 var PATH={splitPath:function (filename) {
1463 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(? :[\/]*)$/;
1464 return splitPathRe.exec(filename).slice(1);
1465 },normalizeArray:function (parts, allowAboveRoot) {
1466 // if the path tries to go above the root, `up` ends up > 0
1467 var up = 0;
1468 for (var i = parts.length - 1; i >= 0; i--) {
1469 var last = parts[i];
1470 if (last === '.') {
1471 parts.splice(i, 1);
1472 } else if (last === '..') {
1473 parts.splice(i, 1);
1474 up++;
1475 } else if (up) {
1476 parts.splice(i, 1);
1477 up--;
1478 }
1479 }
1480 // if the path is allowed to go above the root, restore leading ..s
1481 if (allowAboveRoot) {
1482 for (; up--; up) {
1483 parts.unshift('..');
1484 }
1485 }
1486 return parts;
1487 },normalize:function (path) {
1488 var isAbsolute = path.charAt(0) === '/',
1489 trailingSlash = path.substr(-1) === '/';
1490 // Normalize the path
1491 path = PATH.normalizeArray(path.split('/').filter(function(p) {
1492 return !!p;
1493 }), !isAbsolute).join('/');
1494 if (!path && !isAbsolute) {
1495 path = '.';
1496 }
1497 if (path && trailingSlash) {
1498 path += '/';
1499 }
1500 return (isAbsolute ? '/' : '') + path;
1501 },dirname:function (path) {
1502 var result = PATH.splitPath(path),
1503 root = result[0],
1504 dir = result[1];
1505 if (!root && !dir) {
1506 // No dirname whatsoever
1507 return '.';
1508 }
1509 if (dir) {
1510 // It has a dirname, strip trailing slash
1511 dir = dir.substr(0, dir.length - 1);
1512 }
1513 return root + dir;
1514 },basename:function (path) {
1515 // EMSCRIPTEN return '/'' for '/', not an empty string
1516 if (path === '/') return '/';
1517 var lastSlash = path.lastIndexOf('/');
1518 if (lastSlash === -1) return path;
1519 return path.substr(lastSlash+1);
1520 },extname:function (path) {
1521 return PATH.splitPath(path)[3];
1522 },join:function () {
1523 var paths = Array.prototype.slice.call(arguments, 0);
1524 return PATH.normalize(paths.join('/'));
1525 },join2:function (l, r) {
1526 return PATH.normalize(l + '/' + r);
1527 },resolve:function () {
1528 var resolvedPath = '',
1529 resolvedAbsolute = false;
1530 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1531 var path = (i >= 0) ? arguments[i] : FS.cwd();
1532 // Skip empty and invalid entries
1533 if (typeof path !== 'string') {
1534 throw new TypeError('Arguments to path.resolve must be strings');
1535 } else if (!path) {
1536 continue;
1537 }
1538 resolvedPath = path + '/' + resolvedPath;
1539 resolvedAbsolute = path.charAt(0) === '/';
1540 }
1541 // At this point the path should be resolved to a full absolute path, bu t
1542 // handle relative paths to be safe (might happen when process.cwd() fai ls)
1543 resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(functi on(p) {
1544 return !!p;
1545 }), !resolvedAbsolute).join('/');
1546 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
1547 },relative:function (from, to) {
1548 from = PATH.resolve(from).substr(1);
1549 to = PATH.resolve(to).substr(1);
1550 function trim(arr) {
1551 var start = 0;
1552 for (; start < arr.length; start++) {
1553 if (arr[start] !== '') break;
1554 }
1555 var end = arr.length - 1;
1556 for (; end >= 0; end--) {
1557 if (arr[end] !== '') break;
1558 }
1559 if (start > end) return [];
1560 return arr.slice(start, end - start + 1);
1561 }
1562 var fromParts = trim(from.split('/'));
1563 var toParts = trim(to.split('/'));
1564 var length = Math.min(fromParts.length, toParts.length);
1565 var samePartsLength = length;
1566 for (var i = 0; i < length; i++) {
1567 if (fromParts[i] !== toParts[i]) {
1568 samePartsLength = i;
1569 break;
1570 }
1571 }
1572 var outputParts = [];
1573 for (var i = samePartsLength; i < fromParts.length; i++) {
1574 outputParts.push('..');
1575 }
1576 outputParts = outputParts.concat(toParts.slice(samePartsLength));
1577 return outputParts.join('/');
1578 }};
1579
1580 var TTY={ttys:[],init:function () {
1581 // https://github.com/kripken/emscripten/pull/1555
1582 // if (ENVIRONMENT_IS_NODE) {
1583 // // currently, FS.init does not distinguish if process.stdin is a fi le or TTY
1584 // // device, it always assumes it's a TTY device. because of this, we 're forcing
1585 // // process.stdin to UTF8 encoding to at least make stdin reading co mpatible
1586 // // with text files until FS.init can be refactored.
1587 // process['stdin']['setEncoding']('utf8');
1588 // }
1589 },shutdown:function () {
1590 // https://github.com/kripken/emscripten/pull/1555
1591 // if (ENVIRONMENT_IS_NODE) {
1592 // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn 't exit immediately (with process.stdin being a tty)?
1593 // // isaacs: because now it's reading from the stream, you've express ed interest in it, so that read() kicks off a _read() which creates a ReadReq op eration
1594 // // inolen: I thought read() in that case was a synchronous operatio n that just grabbed some amount of buffered data if it exists?
1595 // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
1596 // // isaacs: do process.stdin.pause() and i'd think it'd probably clo se the pending call
1597 // process['stdin']['pause']();
1598 // }
1599 },register:function (dev, ops) {
1600 TTY.ttys[dev] = { input: [], output: [], ops: ops };
1601 FS.registerDevice(dev, TTY.stream_ops);
1602 },stream_ops:{open:function (stream) {
1603 var tty = TTY.ttys[stream.node.rdev];
1604 if (!tty) {
1605 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1606 }
1607 stream.tty = tty;
1608 stream.seekable = false;
1609 },close:function (stream) {
1610 // flush any pending line data
1611 if (stream.tty.output.length) {
1612 stream.tty.ops.put_char(stream.tty, 10);
1613 }
1614 },read:function (stream, buffer, offset, length, pos /* ignored */) {
1615 if (!stream.tty || !stream.tty.ops.get_char) {
1616 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1617 }
1618 var bytesRead = 0;
1619 for (var i = 0; i < length; i++) {
1620 var result;
1621 try {
1622 result = stream.tty.ops.get_char(stream.tty);
1623 } catch (e) {
1624 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1625 }
1626 if (result === undefined && bytesRead === 0) {
1627 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
1628 }
1629 if (result === null || result === undefined) break;
1630 bytesRead++;
1631 buffer[offset+i] = result;
1632 }
1633 if (bytesRead) {
1634 stream.node.timestamp = Date.now();
1635 }
1636 return bytesRead;
1637 },write:function (stream, buffer, offset, length, pos) {
1638 if (!stream.tty || !stream.tty.ops.put_char) {
1639 throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
1640 }
1641 for (var i = 0; i < length; i++) {
1642 try {
1643 stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
1644 } catch (e) {
1645 throw new FS.ErrnoError(ERRNO_CODES.EIO);
1646 }
1647 }
1648 if (length) {
1649 stream.node.timestamp = Date.now();
1650 }
1651 return i;
1652 }},default_tty_ops:{get_char:function (tty) {
1653 if (!tty.input.length) {
1654 var result = null;
1655 if (ENVIRONMENT_IS_NODE) {
1656 result = process['stdin']['read']();
1657 if (!result) {
1658 if (process['stdin']['_readableState'] && process['stdin']['_rea dableState']['ended']) {
1659 return null; // EOF
1660 }
1661 return undefined; // no data available
1662 }
1663 } else if (typeof window != 'undefined' &&
1664 typeof window.prompt == 'function') {
1665 // Browser.
1666 result = window.prompt('Input: '); // returns null on cancel
1667 if (result !== null) {
1668 result += '\n';
1669 }
1670 } else if (typeof readline == 'function') {
1671 // Command line.
1672 result = readline();
1673 if (result !== null) {
1674 result += '\n';
1675 }
1676 }
1677 if (!result) {
1678 return null;
1679 }
1680 tty.input = intArrayFromString(result, true);
1681 }
1682 return tty.input.shift();
1683 },put_char:function (tty, val) {
1684 if (val === null || val === 10) {
1685 Module['print'](tty.output.join(''));
1686 tty.output = [];
1687 } else {
1688 tty.output.push(TTY.utf8.processCChar(val));
1689 }
1690 }},default_tty1_ops:{put_char:function (tty, val) {
1691 if (val === null || val === 10) {
1692 Module['printErr'](tty.output.join(''));
1693 tty.output = [];
1694 } else {
1695 tty.output.push(TTY.utf8.processCChar(val));
1696 }
1697 }}};
1698
1699 var MEMFS={ops_table:null,CONTENT_OWNING:1,CONTENT_FLEXIBLE:2,CONTENT_FIXED:3, mount:function (mount) {
1700 return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
1701 },createNode:function (parent, name, mode, dev) {
1702 if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
1703 // no supported
1704 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
1705 }
1706 if (!MEMFS.ops_table) {
1707 MEMFS.ops_table = {
1708 dir: {
1709 node: {
1710 getattr: MEMFS.node_ops.getattr,
1711 setattr: MEMFS.node_ops.setattr,
1712 lookup: MEMFS.node_ops.lookup,
1713 mknod: MEMFS.node_ops.mknod,
1714 rename: MEMFS.node_ops.rename,
1715 unlink: MEMFS.node_ops.unlink,
1716 rmdir: MEMFS.node_ops.rmdir,
1717 readdir: MEMFS.node_ops.readdir,
1718 symlink: MEMFS.node_ops.symlink
1719 },
1720 stream: {
1721 llseek: MEMFS.stream_ops.llseek
1722 }
1723 },
1724 file: {
1725 node: {
1726 getattr: MEMFS.node_ops.getattr,
1727 setattr: MEMFS.node_ops.setattr
1728 },
1729 stream: {
1730 llseek: MEMFS.stream_ops.llseek,
1731 read: MEMFS.stream_ops.read,
1732 write: MEMFS.stream_ops.write,
1733 allocate: MEMFS.stream_ops.allocate,
1734 mmap: MEMFS.stream_ops.mmap
1735 }
1736 },
1737 link: {
1738 node: {
1739 getattr: MEMFS.node_ops.getattr,
1740 setattr: MEMFS.node_ops.setattr,
1741 readlink: MEMFS.node_ops.readlink
1742 },
1743 stream: {}
1744 },
1745 chrdev: {
1746 node: {
1747 getattr: MEMFS.node_ops.getattr,
1748 setattr: MEMFS.node_ops.setattr
1749 },
1750 stream: FS.chrdev_stream_ops
1751 },
1752 };
1753 }
1754 var node = FS.createNode(parent, name, mode, dev);
1755 if (FS.isDir(node.mode)) {
1756 node.node_ops = MEMFS.ops_table.dir.node;
1757 node.stream_ops = MEMFS.ops_table.dir.stream;
1758 node.contents = {};
1759 } else if (FS.isFile(node.mode)) {
1760 node.node_ops = MEMFS.ops_table.file.node;
1761 node.stream_ops = MEMFS.ops_table.file.stream;
1762 node.contents = [];
1763 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1764 } else if (FS.isLink(node.mode)) {
1765 node.node_ops = MEMFS.ops_table.link.node;
1766 node.stream_ops = MEMFS.ops_table.link.stream;
1767 } else if (FS.isChrdev(node.mode)) {
1768 node.node_ops = MEMFS.ops_table.chrdev.node;
1769 node.stream_ops = MEMFS.ops_table.chrdev.stream;
1770 }
1771 node.timestamp = Date.now();
1772 // add the new node to the parent
1773 if (parent) {
1774 parent.contents[name] = node;
1775 }
1776 return node;
1777 },ensureFlexible:function (node) {
1778 if (node.contentMode !== MEMFS.CONTENT_FLEXIBLE) {
1779 var contents = node.contents;
1780 node.contents = Array.prototype.slice.call(contents);
1781 node.contentMode = MEMFS.CONTENT_FLEXIBLE;
1782 }
1783 },node_ops:{getattr:function (node) {
1784 var attr = {};
1785 // device numbers reuse inode numbers.
1786 attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
1787 attr.ino = node.id;
1788 attr.mode = node.mode;
1789 attr.nlink = 1;
1790 attr.uid = 0;
1791 attr.gid = 0;
1792 attr.rdev = node.rdev;
1793 if (FS.isDir(node.mode)) {
1794 attr.size = 4096;
1795 } else if (FS.isFile(node.mode)) {
1796 attr.size = node.contents.length;
1797 } else if (FS.isLink(node.mode)) {
1798 attr.size = node.link.length;
1799 } else {
1800 attr.size = 0;
1801 }
1802 attr.atime = new Date(node.timestamp);
1803 attr.mtime = new Date(node.timestamp);
1804 attr.ctime = new Date(node.timestamp);
1805 // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksi ze),
1806 // but this is not required by the standard.
1807 attr.blksize = 4096;
1808 attr.blocks = Math.ceil(attr.size / attr.blksize);
1809 return attr;
1810 },setattr:function (node, attr) {
1811 if (attr.mode !== undefined) {
1812 node.mode = attr.mode;
1813 }
1814 if (attr.timestamp !== undefined) {
1815 node.timestamp = attr.timestamp;
1816 }
1817 if (attr.size !== undefined) {
1818 MEMFS.ensureFlexible(node);
1819 var contents = node.contents;
1820 if (attr.size < contents.length) contents.length = attr.size;
1821 else while (attr.size > contents.length) contents.push(0);
1822 }
1823 },lookup:function (parent, name) {
1824 throw FS.genericErrors[ERRNO_CODES.ENOENT];
1825 },mknod:function (parent, name, mode, dev) {
1826 return MEMFS.createNode(parent, name, mode, dev);
1827 },rename:function (old_node, new_dir, new_name) {
1828 // if we're overwriting a directory at new_name, make sure it's empty.
1829 if (FS.isDir(old_node.mode)) {
1830 var new_node;
1831 try {
1832 new_node = FS.lookupNode(new_dir, new_name);
1833 } catch (e) {
1834 }
1835 if (new_node) {
1836 for (var i in new_node.contents) {
1837 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1838 }
1839 }
1840 }
1841 // do the internal rewiring
1842 delete old_node.parent.contents[old_node.name];
1843 old_node.name = new_name;
1844 new_dir.contents[new_name] = old_node;
1845 old_node.parent = new_dir;
1846 },unlink:function (parent, name) {
1847 delete parent.contents[name];
1848 },rmdir:function (parent, name) {
1849 var node = FS.lookupNode(parent, name);
1850 for (var i in node.contents) {
1851 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
1852 }
1853 delete parent.contents[name];
1854 },readdir:function (node) {
1855 var entries = ['.', '..']
1856 for (var key in node.contents) {
1857 if (!node.contents.hasOwnProperty(key)) {
1858 continue;
1859 }
1860 entries.push(key);
1861 }
1862 return entries;
1863 },symlink:function (parent, newname, oldpath) {
1864 var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0 );
1865 node.link = oldpath;
1866 return node;
1867 },readlink:function (node) {
1868 if (!FS.isLink(node.mode)) {
1869 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1870 }
1871 return node.link;
1872 }},stream_ops:{read:function (stream, buffer, offset, length, position) {
1873 var contents = stream.node.contents;
1874 if (position >= contents.length)
1875 return 0;
1876 var size = Math.min(contents.length - position, length);
1877 assert(size >= 0);
1878 if (size > 8 && contents.subarray) { // non-trivial, and typed array
1879 buffer.set(contents.subarray(position, position + size), offset);
1880 } else
1881 {
1882 for (var i = 0; i < size; i++) {
1883 buffer[offset + i] = contents[position + i];
1884 }
1885 }
1886 return size;
1887 },write:function (stream, buffer, offset, length, position, canOwn) {
1888 var node = stream.node;
1889 node.timestamp = Date.now();
1890 var contents = node.contents;
1891 if (length && contents.length === 0 && position === 0 && buffer.subarr ay) {
1892 // just replace it with the new data
1893 if (canOwn && offset === 0) {
1894 node.contents = buffer; // this could be a subarray of Emscripten HEAP, or allocated from some other source.
1895 node.contentMode = (buffer.buffer === HEAP8.buffer) ? MEMFS.CONTEN T_OWNING : MEMFS.CONTENT_FIXED;
1896 } else {
1897 node.contents = new Uint8Array(buffer.subarray(offset, offset+leng th));
1898 node.contentMode = MEMFS.CONTENT_FIXED;
1899 }
1900 return length;
1901 }
1902 MEMFS.ensureFlexible(node);
1903 var contents = node.contents;
1904 while (contents.length < position) contents.push(0);
1905 for (var i = 0; i < length; i++) {
1906 contents[position + i] = buffer[offset + i];
1907 }
1908 return length;
1909 },llseek:function (stream, offset, whence) {
1910 var position = offset;
1911 if (whence === 1) { // SEEK_CUR.
1912 position += stream.position;
1913 } else if (whence === 2) { // SEEK_END.
1914 if (FS.isFile(stream.node.mode)) {
1915 position += stream.node.contents.length;
1916 }
1917 }
1918 if (position < 0) {
1919 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
1920 }
1921 stream.ungotten = [];
1922 stream.position = position;
1923 return position;
1924 },allocate:function (stream, offset, length) {
1925 MEMFS.ensureFlexible(stream.node);
1926 var contents = stream.node.contents;
1927 var limit = offset + length;
1928 while (limit > contents.length) contents.push(0);
1929 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
1930 if (!FS.isFile(stream.node.mode)) {
1931 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
1932 }
1933 var ptr;
1934 var allocated;
1935 var contents = stream.node.contents;
1936 // Only make a new copy when MAP_PRIVATE is specified.
1937 if ( !(flags & 2) &&
1938 (contents.buffer === buffer || contents.buffer === buffer.buffer ) ) {
1939 // We can't emulate MAP_SHARED when the file is not backed by the bu ffer
1940 // we're mapping to (e.g. the HEAP buffer).
1941 allocated = false;
1942 ptr = contents.byteOffset;
1943 } else {
1944 // Try to avoid unnecessary slices.
1945 if (position > 0 || position + length < contents.length) {
1946 if (contents.subarray) {
1947 contents = contents.subarray(position, position + length);
1948 } else {
1949 contents = Array.prototype.slice.call(contents, position, positi on + length);
1950 }
1951 }
1952 allocated = true;
1953 ptr = _malloc(length);
1954 if (!ptr) {
1955 throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
1956 }
1957 buffer.set(contents, ptr);
1958 }
1959 return { ptr: ptr, allocated: allocated };
1960 }}};
1961
1962 var IDBFS={dbs:{},indexedDB:function () {
1963 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
1964 },DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function (mount) {
1965 // reuse all of the core MEMFS functionality
1966 return MEMFS.mount.apply(null, arguments);
1967 },syncfs:function (mount, populate, callback) {
1968 IDBFS.getLocalSet(mount, function(err, local) {
1969 if (err) return callback(err);
1970
1971 IDBFS.getRemoteSet(mount, function(err, remote) {
1972 if (err) return callback(err);
1973
1974 var src = populate ? remote : local;
1975 var dst = populate ? local : remote;
1976
1977 IDBFS.reconcile(src, dst, callback);
1978 });
1979 });
1980 },getDB:function (name, callback) {
1981 // check the cache first
1982 var db = IDBFS.dbs[name];
1983 if (db) {
1984 return callback(null, db);
1985 }
1986
1987 var req;
1988 try {
1989 req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
1990 } catch (e) {
1991 return callback(e);
1992 }
1993 req.onupgradeneeded = function(e) {
1994 var db = e.target.result;
1995 var transaction = e.target.transaction;
1996
1997 var fileStore;
1998
1999 if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
2000 fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
2001 } else {
2002 fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
2003 }
2004
2005 fileStore.createIndex('timestamp', 'timestamp', { unique: false });
2006 };
2007 req.onsuccess = function() {
2008 db = req.result;
2009
2010 // add to the cache
2011 IDBFS.dbs[name] = db;
2012 callback(null, db);
2013 };
2014 req.onerror = function() {
2015 callback(this.error);
2016 };
2017 },getLocalSet:function (mount, callback) {
2018 var entries = {};
2019
2020 function isRealDir(p) {
2021 return p !== '.' && p !== '..';
2022 };
2023 function toAbsolute(root) {
2024 return function(p) {
2025 return PATH.join2(root, p);
2026 }
2027 };
2028
2029 var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolut e(mount.mountpoint));
2030
2031 while (check.length) {
2032 var path = check.pop();
2033 var stat;
2034
2035 try {
2036 stat = FS.stat(path);
2037 } catch (e) {
2038 return callback(e);
2039 }
2040
2041 if (FS.isDir(stat.mode)) {
2042 check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbs olute(path)));
2043 }
2044
2045 entries[path] = { timestamp: stat.mtime };
2046 }
2047
2048 return callback(null, { type: 'local', entries: entries });
2049 },getRemoteSet:function (mount, callback) {
2050 var entries = {};
2051
2052 IDBFS.getDB(mount.mountpoint, function(err, db) {
2053 if (err) return callback(err);
2054
2055 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
2056 transaction.onerror = function() { callback(this.error); };
2057
2058 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2059 var index = store.index('timestamp');
2060
2061 index.openKeyCursor().onsuccess = function(event) {
2062 var cursor = event.target.result;
2063
2064 if (!cursor) {
2065 return callback(null, { type: 'remote', db: db, entries: entries } );
2066 }
2067
2068 entries[cursor.primaryKey] = { timestamp: cursor.key };
2069
2070 cursor.continue();
2071 };
2072 });
2073 },loadLocalEntry:function (path, callback) {
2074 var stat, node;
2075
2076 try {
2077 var lookup = FS.lookupPath(path);
2078 node = lookup.node;
2079 stat = FS.stat(path);
2080 } catch (e) {
2081 return callback(e);
2082 }
2083
2084 if (FS.isDir(stat.mode)) {
2085 return callback(null, { timestamp: stat.mtime, mode: stat.mode });
2086 } else if (FS.isFile(stat.mode)) {
2087 return callback(null, { timestamp: stat.mtime, mode: stat.mode, conten ts: node.contents });
2088 } else {
2089 return callback(new Error('node type not supported'));
2090 }
2091 },storeLocalEntry:function (path, entry, callback) {
2092 try {
2093 if (FS.isDir(entry.mode)) {
2094 FS.mkdir(path, entry.mode);
2095 } else if (FS.isFile(entry.mode)) {
2096 FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: tru e });
2097 } else {
2098 return callback(new Error('node type not supported'));
2099 }
2100
2101 FS.utime(path, entry.timestamp, entry.timestamp);
2102 } catch (e) {
2103 return callback(e);
2104 }
2105
2106 callback(null);
2107 },removeLocalEntry:function (path, callback) {
2108 try {
2109 var lookup = FS.lookupPath(path);
2110 var stat = FS.stat(path);
2111
2112 if (FS.isDir(stat.mode)) {
2113 FS.rmdir(path);
2114 } else if (FS.isFile(stat.mode)) {
2115 FS.unlink(path);
2116 }
2117 } catch (e) {
2118 return callback(e);
2119 }
2120
2121 callback(null);
2122 },loadRemoteEntry:function (store, path, callback) {
2123 var req = store.get(path);
2124 req.onsuccess = function(event) { callback(null, event.target.result); } ;
2125 req.onerror = function() { callback(this.error); };
2126 },storeRemoteEntry:function (store, path, entry, callback) {
2127 var req = store.put(entry, path);
2128 req.onsuccess = function() { callback(null); };
2129 req.onerror = function() { callback(this.error); };
2130 },removeRemoteEntry:function (store, path, callback) {
2131 var req = store.delete(path);
2132 req.onsuccess = function() { callback(null); };
2133 req.onerror = function() { callback(this.error); };
2134 },reconcile:function (src, dst, callback) {
2135 var total = 0;
2136
2137 var create = [];
2138 Object.keys(src.entries).forEach(function (key) {
2139 var e = src.entries[key];
2140 var e2 = dst.entries[key];
2141 if (!e2 || e.timestamp > e2.timestamp) {
2142 create.push(key);
2143 total++;
2144 }
2145 });
2146
2147 var remove = [];
2148 Object.keys(dst.entries).forEach(function (key) {
2149 var e = dst.entries[key];
2150 var e2 = src.entries[key];
2151 if (!e2) {
2152 remove.push(key);
2153 total++;
2154 }
2155 });
2156
2157 if (!total) {
2158 return callback(null);
2159 }
2160
2161 var errored = false;
2162 var completed = 0;
2163 var db = src.type === 'remote' ? src.db : dst.db;
2164 var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
2165 var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
2166
2167 function done(err) {
2168 if (err) {
2169 if (!done.errored) {
2170 done.errored = true;
2171 return callback(err);
2172 }
2173 return;
2174 }
2175 if (++completed >= total) {
2176 return callback(null);
2177 }
2178 };
2179
2180 transaction.onerror = function() { done(this.error); };
2181
2182 // sort paths in ascending order so directory entries are created
2183 // before the files inside them
2184 create.sort().forEach(function (path) {
2185 if (dst.type === 'local') {
2186 IDBFS.loadRemoteEntry(store, path, function (err, entry) {
2187 if (err) return done(err);
2188 IDBFS.storeLocalEntry(path, entry, done);
2189 });
2190 } else {
2191 IDBFS.loadLocalEntry(path, function (err, entry) {
2192 if (err) return done(err);
2193 IDBFS.storeRemoteEntry(store, path, entry, done);
2194 });
2195 }
2196 });
2197
2198 // sort paths in descending order so files are deleted before their
2199 // parent directories
2200 remove.sort().reverse().forEach(function(path) {
2201 if (dst.type === 'local') {
2202 IDBFS.removeLocalEntry(path, done);
2203 } else {
2204 IDBFS.removeRemoteEntry(store, path, done);
2205 }
2206 });
2207 }};
2208
2209 var NODEFS={isWindows:false,staticInit:function () {
2210 NODEFS.isWindows = !!process.platform.match(/^win/);
2211 },mount:function (mount) {
2212 assert(ENVIRONMENT_IS_NODE);
2213 return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
2214 },createNode:function (parent, name, mode, dev) {
2215 if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
2216 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2217 }
2218 var node = FS.createNode(parent, name, mode);
2219 node.node_ops = NODEFS.node_ops;
2220 node.stream_ops = NODEFS.stream_ops;
2221 return node;
2222 },getMode:function (path) {
2223 var stat;
2224 try {
2225 stat = fs.lstatSync(path);
2226 if (NODEFS.isWindows) {
2227 // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
2228 // propagate write bits to execute bits.
2229 stat.mode = stat.mode | ((stat.mode & 146) >> 1);
2230 }
2231 } catch (e) {
2232 if (!e.code) throw e;
2233 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2234 }
2235 return stat.mode;
2236 },realPath:function (node) {
2237 var parts = [];
2238 while (node.parent !== node) {
2239 parts.push(node.name);
2240 node = node.parent;
2241 }
2242 parts.push(node.mount.opts.root);
2243 parts.reverse();
2244 return PATH.join.apply(null, parts);
2245 },flagsToPermissionStringMap:{0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",1 29:"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:"r s",4098:"rs+"},flagsToPermissionString:function (flags) {
2246 if (flags in NODEFS.flagsToPermissionStringMap) {
2247 return NODEFS.flagsToPermissionStringMap[flags];
2248 } else {
2249 return flags;
2250 }
2251 },node_ops:{getattr:function (node) {
2252 var path = NODEFS.realPath(node);
2253 var stat;
2254 try {
2255 stat = fs.lstatSync(path);
2256 } catch (e) {
2257 if (!e.code) throw e;
2258 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2259 }
2260 // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
2261 // See http://support.microsoft.com/kb/140365
2262 if (NODEFS.isWindows && !stat.blksize) {
2263 stat.blksize = 4096;
2264 }
2265 if (NODEFS.isWindows && !stat.blocks) {
2266 stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
2267 }
2268 return {
2269 dev: stat.dev,
2270 ino: stat.ino,
2271 mode: stat.mode,
2272 nlink: stat.nlink,
2273 uid: stat.uid,
2274 gid: stat.gid,
2275 rdev: stat.rdev,
2276 size: stat.size,
2277 atime: stat.atime,
2278 mtime: stat.mtime,
2279 ctime: stat.ctime,
2280 blksize: stat.blksize,
2281 blocks: stat.blocks
2282 };
2283 },setattr:function (node, attr) {
2284 var path = NODEFS.realPath(node);
2285 try {
2286 if (attr.mode !== undefined) {
2287 fs.chmodSync(path, attr.mode);
2288 // update the common node structure mode as well
2289 node.mode = attr.mode;
2290 }
2291 if (attr.timestamp !== undefined) {
2292 var date = new Date(attr.timestamp);
2293 fs.utimesSync(path, date, date);
2294 }
2295 if (attr.size !== undefined) {
2296 fs.truncateSync(path, attr.size);
2297 }
2298 } catch (e) {
2299 if (!e.code) throw e;
2300 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2301 }
2302 },lookup:function (parent, name) {
2303 var path = PATH.join2(NODEFS.realPath(parent), name);
2304 var mode = NODEFS.getMode(path);
2305 return NODEFS.createNode(parent, name, mode);
2306 },mknod:function (parent, name, mode, dev) {
2307 var node = NODEFS.createNode(parent, name, mode, dev);
2308 // create the backing node for this in the fs root as well
2309 var path = NODEFS.realPath(node);
2310 try {
2311 if (FS.isDir(node.mode)) {
2312 fs.mkdirSync(path, node.mode);
2313 } else {
2314 fs.writeFileSync(path, '', { mode: node.mode });
2315 }
2316 } catch (e) {
2317 if (!e.code) throw e;
2318 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2319 }
2320 return node;
2321 },rename:function (oldNode, newDir, newName) {
2322 var oldPath = NODEFS.realPath(oldNode);
2323 var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
2324 try {
2325 fs.renameSync(oldPath, newPath);
2326 } catch (e) {
2327 if (!e.code) throw e;
2328 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2329 }
2330 },unlink:function (parent, name) {
2331 var path = PATH.join2(NODEFS.realPath(parent), name);
2332 try {
2333 fs.unlinkSync(path);
2334 } catch (e) {
2335 if (!e.code) throw e;
2336 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2337 }
2338 },rmdir:function (parent, name) {
2339 var path = PATH.join2(NODEFS.realPath(parent), name);
2340 try {
2341 fs.rmdirSync(path);
2342 } catch (e) {
2343 if (!e.code) throw e;
2344 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2345 }
2346 },readdir:function (node) {
2347 var path = NODEFS.realPath(node);
2348 try {
2349 return fs.readdirSync(path);
2350 } catch (e) {
2351 if (!e.code) throw e;
2352 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2353 }
2354 },symlink:function (parent, newName, oldPath) {
2355 var newPath = PATH.join2(NODEFS.realPath(parent), newName);
2356 try {
2357 fs.symlinkSync(oldPath, newPath);
2358 } catch (e) {
2359 if (!e.code) throw e;
2360 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2361 }
2362 },readlink:function (node) {
2363 var path = NODEFS.realPath(node);
2364 try {
2365 return fs.readlinkSync(path);
2366 } catch (e) {
2367 if (!e.code) throw e;
2368 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2369 }
2370 }},stream_ops:{open:function (stream) {
2371 var path = NODEFS.realPath(stream.node);
2372 try {
2373 if (FS.isFile(stream.node.mode)) {
2374 stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stre am.flags));
2375 }
2376 } catch (e) {
2377 if (!e.code) throw e;
2378 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2379 }
2380 },close:function (stream) {
2381 try {
2382 if (FS.isFile(stream.node.mode) && stream.nfd) {
2383 fs.closeSync(stream.nfd);
2384 }
2385 } catch (e) {
2386 if (!e.code) throw e;
2387 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2388 }
2389 },read:function (stream, buffer, offset, length, position) {
2390 // FIXME this is terrible.
2391 var nbuffer = new Buffer(length);
2392 var res;
2393 try {
2394 res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
2395 } catch (e) {
2396 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2397 }
2398 if (res > 0) {
2399 for (var i = 0; i < res; i++) {
2400 buffer[offset + i] = nbuffer[i];
2401 }
2402 }
2403 return res;
2404 },write:function (stream, buffer, offset, length, position) {
2405 // FIXME this is terrible.
2406 var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
2407 var res;
2408 try {
2409 res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
2410 } catch (e) {
2411 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2412 }
2413 return res;
2414 },llseek:function (stream, offset, whence) {
2415 var position = offset;
2416 if (whence === 1) { // SEEK_CUR.
2417 position += stream.position;
2418 } else if (whence === 2) { // SEEK_END.
2419 if (FS.isFile(stream.node.mode)) {
2420 try {
2421 var stat = fs.fstatSync(stream.nfd);
2422 position += stat.size;
2423 } catch (e) {
2424 throw new FS.ErrnoError(ERRNO_CODES[e.code]);
2425 }
2426 }
2427 }
2428
2429 if (position < 0) {
2430 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2431 }
2432
2433 stream.position = position;
2434 return position;
2435 }}};
2436
2437 var _stdin=allocate(1, "i32*", ALLOC_STATIC);
2438
2439 var _stdout=allocate(1, "i32*", ALLOC_STATIC);
2440
2441 var _stderr=allocate(1, "i32*", ALLOC_STATIC);
2442
2443 function _fflush(stream) {
2444 // int fflush(FILE *stream);
2445 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fflush.html
2446 // we don't currently perform any user-space buffering of data
2447 }var FS={root:null,mounts:[],devices:[null],streams:[],nextInode:1,nameTable :null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,g enericErrors:{},handleFSError:function (e) {
2448 if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
2449 return ___setErrNo(e.errno);
2450 },lookupPath:function (path, opts) {
2451 path = PATH.resolve(FS.cwd(), path);
2452 opts = opts || {};
2453
2454 var defaults = {
2455 follow_mount: true,
2456 recurse_count: 0
2457 };
2458 for (var key in defaults) {
2459 if (opts[key] === undefined) {
2460 opts[key] = defaults[key];
2461 }
2462 }
2463
2464 if (opts.recurse_count > 8) { // max recursive lookup of 8
2465 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2466 }
2467
2468 // split the path
2469 var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2470 return !!p;
2471 }), false);
2472
2473 // start at the root
2474 var current = FS.root;
2475 var current_path = '/';
2476
2477 for (var i = 0; i < parts.length; i++) {
2478 var islast = (i === parts.length-1);
2479 if (islast && opts.parent) {
2480 // stop resolving
2481 break;
2482 }
2483
2484 current = FS.lookupNode(current, parts[i]);
2485 current_path = PATH.join2(current_path, parts[i]);
2486
2487 // jump to the mount's root node if this is a mountpoint
2488 if (FS.isMountpoint(current)) {
2489 if (!islast || (islast && opts.follow_mount)) {
2490 current = current.mounted.root;
2491 }
2492 }
2493
2494 // by default, lookupPath will not follow a symlink if it is the final path component.
2495 // setting opts.follow = true will override this behavior.
2496 if (!islast || opts.follow) {
2497 var count = 0;
2498 while (FS.isLink(current.mode)) {
2499 var link = FS.readlink(current_path);
2500 current_path = PATH.resolve(PATH.dirname(current_path), link);
2501
2502 var lookup = FS.lookupPath(current_path, { recurse_count: opts.rec urse_count });
2503 current = lookup.node;
2504
2505 if (count++ > 40) { // limit max consecutive symlinks to 40 (SYML OOP_MAX).
2506 throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
2507 }
2508 }
2509 }
2510 }
2511
2512 return { path: current_path, node: current };
2513 },getPath:function (node) {
2514 var path;
2515 while (true) {
2516 if (FS.isRoot(node)) {
2517 var mount = node.mount.mountpoint;
2518 if (!path) return mount;
2519 return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
2520 }
2521 path = path ? node.name + '/' + path : node.name;
2522 node = node.parent;
2523 }
2524 },hashName:function (parentid, name) {
2525 var hash = 0;
2526
2527
2528 for (var i = 0; i < name.length; i++) {
2529 hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2530 }
2531 return ((parentid + hash) >>> 0) % FS.nameTable.length;
2532 },hashAddNode:function (node) {
2533 var hash = FS.hashName(node.parent.id, node.name);
2534 node.name_next = FS.nameTable[hash];
2535 FS.nameTable[hash] = node;
2536 },hashRemoveNode:function (node) {
2537 var hash = FS.hashName(node.parent.id, node.name);
2538 if (FS.nameTable[hash] === node) {
2539 FS.nameTable[hash] = node.name_next;
2540 } else {
2541 var current = FS.nameTable[hash];
2542 while (current) {
2543 if (current.name_next === node) {
2544 current.name_next = node.name_next;
2545 break;
2546 }
2547 current = current.name_next;
2548 }
2549 }
2550 },lookupNode:function (parent, name) {
2551 var err = FS.mayLookup(parent);
2552 if (err) {
2553 throw new FS.ErrnoError(err);
2554 }
2555 var hash = FS.hashName(parent.id, name);
2556 for (var node = FS.nameTable[hash]; node; node = node.name_next) {
2557 var nodeName = node.name;
2558 if (node.parent.id === parent.id && nodeName === name) {
2559 return node;
2560 }
2561 }
2562 // if we failed to find it in the cache, call into the VFS
2563 return FS.lookup(parent, name);
2564 },createNode:function (parent, name, mode, rdev) {
2565 if (!FS.FSNode) {
2566 FS.FSNode = function(parent, name, mode, rdev) {
2567 if (!parent) {
2568 parent = this; // root node sets parent to itself
2569 }
2570 this.parent = parent;
2571 this.mount = parent.mount;
2572 this.mounted = null;
2573 this.id = FS.nextInode++;
2574 this.name = name;
2575 this.mode = mode;
2576 this.node_ops = {};
2577 this.stream_ops = {};
2578 this.rdev = rdev;
2579 };
2580
2581 FS.FSNode.prototype = {};
2582
2583 // compatibility
2584 var readMode = 292 | 73;
2585 var writeMode = 146;
2586
2587 // NOTE we must use Object.defineProperties instead of individual call s to
2588 // Object.defineProperty in order to make closure compiler happy
2589 Object.defineProperties(FS.FSNode.prototype, {
2590 read: {
2591 get: function() { return (this.mode & readMode) === readMode; },
2592 set: function(val) { val ? this.mode |= readMode : this.mode &= ~r eadMode; }
2593 },
2594 write: {
2595 get: function() { return (this.mode & writeMode) === writeMode; },
2596 set: function(val) { val ? this.mode |= writeMode : this.mode &= ~ writeMode; }
2597 },
2598 isFolder: {
2599 get: function() { return FS.isDir(this.mode); },
2600 },
2601 isDevice: {
2602 get: function() { return FS.isChrdev(this.mode); },
2603 },
2604 });
2605 }
2606
2607 var node = new FS.FSNode(parent, name, mode, rdev);
2608
2609 FS.hashAddNode(node);
2610
2611 return node;
2612 },destroyNode:function (node) {
2613 FS.hashRemoveNode(node);
2614 },isRoot:function (node) {
2615 return node === node.parent;
2616 },isMountpoint:function (node) {
2617 return !!node.mounted;
2618 },isFile:function (mode) {
2619 return (mode & 61440) === 32768;
2620 },isDir:function (mode) {
2621 return (mode & 61440) === 16384;
2622 },isLink:function (mode) {
2623 return (mode & 61440) === 40960;
2624 },isChrdev:function (mode) {
2625 return (mode & 61440) === 8192;
2626 },isBlkdev:function (mode) {
2627 return (mode & 61440) === 24576;
2628 },isFIFO:function (mode) {
2629 return (mode & 61440) === 4096;
2630 },isSocket:function (mode) {
2631 return (mode & 49152) === 49152;
2632 },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) {
2633 var flags = FS.flagModes[str];
2634 if (typeof flags === 'undefined') {
2635 throw new Error('Unknown file open mode: ' + str);
2636 }
2637 return flags;
2638 },flagsToPermissionString:function (flag) {
2639 var accmode = flag & 2097155;
2640 var perms = ['r', 'w', 'rw'][accmode];
2641 if ((flag & 512)) {
2642 perms += 'w';
2643 }
2644 return perms;
2645 },nodePermissions:function (node, perms) {
2646 if (FS.ignorePermissions) {
2647 return 0;
2648 }
2649 // return 0 if any user, group or owner bits are set.
2650 if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
2651 return ERRNO_CODES.EACCES;
2652 } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
2653 return ERRNO_CODES.EACCES;
2654 } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
2655 return ERRNO_CODES.EACCES;
2656 }
2657 return 0;
2658 },mayLookup:function (dir) {
2659 return FS.nodePermissions(dir, 'x');
2660 },mayCreate:function (dir, name) {
2661 try {
2662 var node = FS.lookupNode(dir, name);
2663 return ERRNO_CODES.EEXIST;
2664 } catch (e) {
2665 }
2666 return FS.nodePermissions(dir, 'wx');
2667 },mayDelete:function (dir, name, isdir) {
2668 var node;
2669 try {
2670 node = FS.lookupNode(dir, name);
2671 } catch (e) {
2672 return e.errno;
2673 }
2674 var err = FS.nodePermissions(dir, 'wx');
2675 if (err) {
2676 return err;
2677 }
2678 if (isdir) {
2679 if (!FS.isDir(node.mode)) {
2680 return ERRNO_CODES.ENOTDIR;
2681 }
2682 if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2683 return ERRNO_CODES.EBUSY;
2684 }
2685 } else {
2686 if (FS.isDir(node.mode)) {
2687 return ERRNO_CODES.EISDIR;
2688 }
2689 }
2690 return 0;
2691 },mayOpen:function (node, flags) {
2692 if (!node) {
2693 return ERRNO_CODES.ENOENT;
2694 }
2695 if (FS.isLink(node.mode)) {
2696 return ERRNO_CODES.ELOOP;
2697 } else if (FS.isDir(node.mode)) {
2698 if ((flags & 2097155) !== 0 || // opening for write
2699 (flags & 512)) {
2700 return ERRNO_CODES.EISDIR;
2701 }
2702 }
2703 return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
2704 },MAX_OPEN_FDS:4096,nextfd:function (fd_start, fd_end) {
2705 fd_start = fd_start || 0;
2706 fd_end = fd_end || FS.MAX_OPEN_FDS;
2707 for (var fd = fd_start; fd <= fd_end; fd++) {
2708 if (!FS.streams[fd]) {
2709 return fd;
2710 }
2711 }
2712 throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
2713 },getStream:function (fd) {
2714 return FS.streams[fd];
2715 },createStream:function (stream, fd_start, fd_end) {
2716 if (!FS.FSStream) {
2717 FS.FSStream = function(){};
2718 FS.FSStream.prototype = {};
2719 // compatibility
2720 Object.defineProperties(FS.FSStream.prototype, {
2721 object: {
2722 get: function() { return this.node; },
2723 set: function(val) { this.node = val; }
2724 },
2725 isRead: {
2726 get: function() { return (this.flags & 2097155) !== 1; }
2727 },
2728 isWrite: {
2729 get: function() { return (this.flags & 2097155) !== 0; }
2730 },
2731 isAppend: {
2732 get: function() { return (this.flags & 1024); }
2733 }
2734 });
2735 }
2736 if (0) {
2737 // reuse the object
2738 stream.__proto__ = FS.FSStream.prototype;
2739 } else {
2740 var newStream = new FS.FSStream();
2741 for (var p in stream) {
2742 newStream[p] = stream[p];
2743 }
2744 stream = newStream;
2745 }
2746 var fd = FS.nextfd(fd_start, fd_end);
2747 stream.fd = fd;
2748 FS.streams[fd] = stream;
2749 return stream;
2750 },closeStream:function (fd) {
2751 FS.streams[fd] = null;
2752 },getStreamFromPtr:function (ptr) {
2753 return FS.streams[ptr - 1];
2754 },getPtrForStream:function (stream) {
2755 return stream ? stream.fd + 1 : 0;
2756 },chrdev_stream_ops:{open:function (stream) {
2757 var device = FS.getDevice(stream.node.rdev);
2758 // override node's stream ops with the device's
2759 stream.stream_ops = device.stream_ops;
2760 // forward the open call
2761 if (stream.stream_ops.open) {
2762 stream.stream_ops.open(stream);
2763 }
2764 },llseek:function () {
2765 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
2766 }},major:function (dev) {
2767 return ((dev) >> 8);
2768 },minor:function (dev) {
2769 return ((dev) & 0xff);
2770 },makedev:function (ma, mi) {
2771 return ((ma) << 8 | (mi));
2772 },registerDevice:function (dev, ops) {
2773 FS.devices[dev] = { stream_ops: ops };
2774 },getDevice:function (dev) {
2775 return FS.devices[dev];
2776 },getMounts:function (mount) {
2777 var mounts = [];
2778 var check = [mount];
2779
2780 while (check.length) {
2781 var m = check.pop();
2782
2783 mounts.push(m);
2784
2785 check.push.apply(check, m.mounts);
2786 }
2787
2788 return mounts;
2789 },syncfs:function (populate, callback) {
2790 if (typeof(populate) === 'function') {
2791 callback = populate;
2792 populate = false;
2793 }
2794
2795 var mounts = FS.getMounts(FS.root.mount);
2796 var completed = 0;
2797
2798 function done(err) {
2799 if (err) {
2800 if (!done.errored) {
2801 done.errored = true;
2802 return callback(err);
2803 }
2804 return;
2805 }
2806 if (++completed >= mounts.length) {
2807 callback(null);
2808 }
2809 };
2810
2811 // sync all mounts
2812 mounts.forEach(function (mount) {
2813 if (!mount.type.syncfs) {
2814 return done(null);
2815 }
2816 mount.type.syncfs(mount, populate, done);
2817 });
2818 },mount:function (type, opts, mountpoint) {
2819 var root = mountpoint === '/';
2820 var pseudo = !mountpoint;
2821 var node;
2822
2823 if (root && FS.root) {
2824 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2825 } else if (!root && !pseudo) {
2826 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2827
2828 mountpoint = lookup.path; // use the absolute path
2829 node = lookup.node;
2830
2831 if (FS.isMountpoint(node)) {
2832 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2833 }
2834
2835 if (!FS.isDir(node.mode)) {
2836 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
2837 }
2838 }
2839
2840 var mount = {
2841 type: type,
2842 opts: opts,
2843 mountpoint: mountpoint,
2844 mounts: []
2845 };
2846
2847 // create a root node for the fs
2848 var mountRoot = type.mount(mount);
2849 mountRoot.mount = mount;
2850 mount.root = mountRoot;
2851
2852 if (root) {
2853 FS.root = mountRoot;
2854 } else if (node) {
2855 // set as a mountpoint
2856 node.mounted = mount;
2857
2858 // add the new mount to the current mount's children
2859 if (node.mount) {
2860 node.mount.mounts.push(mount);
2861 }
2862 }
2863
2864 return mountRoot;
2865 },unmount:function (mountpoint) {
2866 var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2867
2868 if (!FS.isMountpoint(lookup.node)) {
2869 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2870 }
2871
2872 // destroy the nodes for this mount, and all its child mounts
2873 var node = lookup.node;
2874 var mount = node.mounted;
2875 var mounts = FS.getMounts(mount);
2876
2877 Object.keys(FS.nameTable).forEach(function (hash) {
2878 var current = FS.nameTable[hash];
2879
2880 while (current) {
2881 var next = current.name_next;
2882
2883 if (mounts.indexOf(current.mount) !== -1) {
2884 FS.destroyNode(current);
2885 }
2886
2887 current = next;
2888 }
2889 });
2890
2891 // no longer a mountpoint
2892 node.mounted = null;
2893
2894 // remove this mount from the child mounts
2895 var idx = node.mount.mounts.indexOf(mount);
2896 assert(idx !== -1);
2897 node.mount.mounts.splice(idx, 1);
2898 },lookup:function (parent, name) {
2899 return parent.node_ops.lookup(parent, name);
2900 },mknod:function (path, mode, dev) {
2901 var lookup = FS.lookupPath(path, { parent: true });
2902 var parent = lookup.node;
2903 var name = PATH.basename(path);
2904 var err = FS.mayCreate(parent, name);
2905 if (err) {
2906 throw new FS.ErrnoError(err);
2907 }
2908 if (!parent.node_ops.mknod) {
2909 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2910 }
2911 return parent.node_ops.mknod(parent, name, mode, dev);
2912 },create:function (path, mode) {
2913 mode = mode !== undefined ? mode : 438 /* 0666 */;
2914 mode &= 4095;
2915 mode |= 32768;
2916 return FS.mknod(path, mode, 0);
2917 },mkdir:function (path, mode) {
2918 mode = mode !== undefined ? mode : 511 /* 0777 */;
2919 mode &= 511 | 512;
2920 mode |= 16384;
2921 return FS.mknod(path, mode, 0);
2922 },mkdev:function (path, mode, dev) {
2923 if (typeof(dev) === 'undefined') {
2924 dev = mode;
2925 mode = 438 /* 0666 */;
2926 }
2927 mode |= 8192;
2928 return FS.mknod(path, mode, dev);
2929 },symlink:function (oldpath, newpath) {
2930 var lookup = FS.lookupPath(newpath, { parent: true });
2931 var parent = lookup.node;
2932 var newname = PATH.basename(newpath);
2933 var err = FS.mayCreate(parent, newname);
2934 if (err) {
2935 throw new FS.ErrnoError(err);
2936 }
2937 if (!parent.node_ops.symlink) {
2938 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2939 }
2940 return parent.node_ops.symlink(parent, newname, oldpath);
2941 },rename:function (old_path, new_path) {
2942 var old_dirname = PATH.dirname(old_path);
2943 var new_dirname = PATH.dirname(new_path);
2944 var old_name = PATH.basename(old_path);
2945 var new_name = PATH.basename(new_path);
2946 // parents must exist
2947 var lookup, old_dir, new_dir;
2948 try {
2949 lookup = FS.lookupPath(old_path, { parent: true });
2950 old_dir = lookup.node;
2951 lookup = FS.lookupPath(new_path, { parent: true });
2952 new_dir = lookup.node;
2953 } catch (e) {
2954 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
2955 }
2956 // need to be part of the same mount
2957 if (old_dir.mount !== new_dir.mount) {
2958 throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
2959 }
2960 // source must exist
2961 var old_node = FS.lookupNode(old_dir, old_name);
2962 // old path should not be an ancestor of the new path
2963 var relative = PATH.relative(old_path, new_dirname);
2964 if (relative.charAt(0) !== '.') {
2965 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
2966 }
2967 // new path should not be an ancestor of the old path
2968 relative = PATH.relative(new_path, old_dirname);
2969 if (relative.charAt(0) !== '.') {
2970 throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
2971 }
2972 // see if the new path already exists
2973 var new_node;
2974 try {
2975 new_node = FS.lookupNode(new_dir, new_name);
2976 } catch (e) {
2977 // not fatal
2978 }
2979 // early out if nothing needs to change
2980 if (old_node === new_node) {
2981 return;
2982 }
2983 // we'll need to delete the old entry
2984 var isdir = FS.isDir(old_node.mode);
2985 var err = FS.mayDelete(old_dir, old_name, isdir);
2986 if (err) {
2987 throw new FS.ErrnoError(err);
2988 }
2989 // need delete permissions if we'll be overwriting.
2990 // need create permissions if new doesn't already exist.
2991 err = new_node ?
2992 FS.mayDelete(new_dir, new_name, isdir) :
2993 FS.mayCreate(new_dir, new_name);
2994 if (err) {
2995 throw new FS.ErrnoError(err);
2996 }
2997 if (!old_dir.node_ops.rename) {
2998 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
2999 }
3000 if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node)) ) {
3001 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3002 }
3003 // if we are going to change the parent, check write permissions
3004 if (new_dir !== old_dir) {
3005 err = FS.nodePermissions(old_dir, 'w');
3006 if (err) {
3007 throw new FS.ErrnoError(err);
3008 }
3009 }
3010 // remove the node from the lookup hash
3011 FS.hashRemoveNode(old_node);
3012 // do the underlying fs rename
3013 try {
3014 old_dir.node_ops.rename(old_node, new_dir, new_name);
3015 } catch (e) {
3016 throw e;
3017 } finally {
3018 // add the node back to the hash (in case node_ops.rename
3019 // changed its name)
3020 FS.hashAddNode(old_node);
3021 }
3022 },rmdir:function (path) {
3023 var lookup = FS.lookupPath(path, { parent: true });
3024 var parent = lookup.node;
3025 var name = PATH.basename(path);
3026 var node = FS.lookupNode(parent, name);
3027 var err = FS.mayDelete(parent, name, true);
3028 if (err) {
3029 throw new FS.ErrnoError(err);
3030 }
3031 if (!parent.node_ops.rmdir) {
3032 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3033 }
3034 if (FS.isMountpoint(node)) {
3035 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3036 }
3037 parent.node_ops.rmdir(parent, name);
3038 FS.destroyNode(node);
3039 },readdir:function (path) {
3040 var lookup = FS.lookupPath(path, { follow: true });
3041 var node = lookup.node;
3042 if (!node.node_ops.readdir) {
3043 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3044 }
3045 return node.node_ops.readdir(node);
3046 },unlink:function (path) {
3047 var lookup = FS.lookupPath(path, { parent: true });
3048 var parent = lookup.node;
3049 var name = PATH.basename(path);
3050 var node = FS.lookupNode(parent, name);
3051 var err = FS.mayDelete(parent, name, false);
3052 if (err) {
3053 // POSIX says unlink should set EPERM, not EISDIR
3054 if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
3055 throw new FS.ErrnoError(err);
3056 }
3057 if (!parent.node_ops.unlink) {
3058 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3059 }
3060 if (FS.isMountpoint(node)) {
3061 throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
3062 }
3063 parent.node_ops.unlink(parent, name);
3064 FS.destroyNode(node);
3065 },readlink:function (path) {
3066 var lookup = FS.lookupPath(path);
3067 var link = lookup.node;
3068 if (!link.node_ops.readlink) {
3069 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3070 }
3071 return link.node_ops.readlink(link);
3072 },stat:function (path, dontFollow) {
3073 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3074 var node = lookup.node;
3075 if (!node.node_ops.getattr) {
3076 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3077 }
3078 return node.node_ops.getattr(node);
3079 },lstat:function (path) {
3080 return FS.stat(path, true);
3081 },chmod:function (path, mode, dontFollow) {
3082 var node;
3083 if (typeof path === 'string') {
3084 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3085 node = lookup.node;
3086 } else {
3087 node = path;
3088 }
3089 if (!node.node_ops.setattr) {
3090 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3091 }
3092 node.node_ops.setattr(node, {
3093 mode: (mode & 4095) | (node.mode & ~4095),
3094 timestamp: Date.now()
3095 });
3096 },lchmod:function (path, mode) {
3097 FS.chmod(path, mode, true);
3098 },fchmod:function (fd, mode) {
3099 var stream = FS.getStream(fd);
3100 if (!stream) {
3101 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3102 }
3103 FS.chmod(stream.node, mode);
3104 },chown:function (path, uid, gid, dontFollow) {
3105 var node;
3106 if (typeof path === 'string') {
3107 var lookup = FS.lookupPath(path, { follow: !dontFollow });
3108 node = lookup.node;
3109 } else {
3110 node = path;
3111 }
3112 if (!node.node_ops.setattr) {
3113 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3114 }
3115 node.node_ops.setattr(node, {
3116 timestamp: Date.now()
3117 // we ignore the uid / gid for now
3118 });
3119 },lchown:function (path, uid, gid) {
3120 FS.chown(path, uid, gid, true);
3121 },fchown:function (fd, uid, gid) {
3122 var stream = FS.getStream(fd);
3123 if (!stream) {
3124 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3125 }
3126 FS.chown(stream.node, uid, gid);
3127 },truncate:function (path, len) {
3128 if (len < 0) {
3129 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3130 }
3131 var node;
3132 if (typeof path === 'string') {
3133 var lookup = FS.lookupPath(path, { follow: true });
3134 node = lookup.node;
3135 } else {
3136 node = path;
3137 }
3138 if (!node.node_ops.setattr) {
3139 throw new FS.ErrnoError(ERRNO_CODES.EPERM);
3140 }
3141 if (FS.isDir(node.mode)) {
3142 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3143 }
3144 if (!FS.isFile(node.mode)) {
3145 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3146 }
3147 var err = FS.nodePermissions(node, 'w');
3148 if (err) {
3149 throw new FS.ErrnoError(err);
3150 }
3151 node.node_ops.setattr(node, {
3152 size: len,
3153 timestamp: Date.now()
3154 });
3155 },ftruncate:function (fd, len) {
3156 var stream = FS.getStream(fd);
3157 if (!stream) {
3158 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3159 }
3160 if ((stream.flags & 2097155) === 0) {
3161 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3162 }
3163 FS.truncate(stream.node, len);
3164 },utime:function (path, atime, mtime) {
3165 var lookup = FS.lookupPath(path, { follow: true });
3166 var node = lookup.node;
3167 node.node_ops.setattr(node, {
3168 timestamp: Math.max(atime, mtime)
3169 });
3170 },open:function (path, flags, mode, fd_start, fd_end) {
3171 flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3172 mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3173 if ((flags & 64)) {
3174 mode = (mode & 4095) | 32768;
3175 } else {
3176 mode = 0;
3177 }
3178 var node;
3179 if (typeof path === 'object') {
3180 node = path;
3181 } else {
3182 path = PATH.normalize(path);
3183 try {
3184 var lookup = FS.lookupPath(path, {
3185 follow: !(flags & 131072)
3186 });
3187 node = lookup.node;
3188 } catch (e) {
3189 // ignore
3190 }
3191 }
3192 // perhaps we need to create the node
3193 if ((flags & 64)) {
3194 if (node) {
3195 // if O_CREAT and O_EXCL are set, error out if the node already exis ts
3196 if ((flags & 128)) {
3197 throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
3198 }
3199 } else {
3200 // node doesn't exist, try to create it
3201 node = FS.mknod(path, mode, 0);
3202 }
3203 }
3204 if (!node) {
3205 throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
3206 }
3207 // can't truncate a device
3208 if (FS.isChrdev(node.mode)) {
3209 flags &= ~512;
3210 }
3211 // check permissions
3212 var err = FS.mayOpen(node, flags);
3213 if (err) {
3214 throw new FS.ErrnoError(err);
3215 }
3216 // do truncation if necessary
3217 if ((flags & 512)) {
3218 FS.truncate(node, 0);
3219 }
3220 // we've already handled these, don't pass down to the underlying vfs
3221 flags &= ~(128 | 512);
3222
3223 // register the stream with the filesystem
3224 var stream = FS.createStream({
3225 node: node,
3226 path: FS.getPath(node), // we want the absolute path to the node
3227 flags: flags,
3228 seekable: true,
3229 position: 0,
3230 stream_ops: node.stream_ops,
3231 // used by the file family libc calls (fopen, fwrite, ferror, etc.)
3232 ungotten: [],
3233 error: false
3234 }, fd_start, fd_end);
3235 // call the new stream's open function
3236 if (stream.stream_ops.open) {
3237 stream.stream_ops.open(stream);
3238 }
3239 if (Module['logReadFiles'] && !(flags & 1)) {
3240 if (!FS.readFiles) FS.readFiles = {};
3241 if (!(path in FS.readFiles)) {
3242 FS.readFiles[path] = 1;
3243 Module['printErr']('read file: ' + path);
3244 }
3245 }
3246 return stream;
3247 },close:function (stream) {
3248 try {
3249 if (stream.stream_ops.close) {
3250 stream.stream_ops.close(stream);
3251 }
3252 } catch (e) {
3253 throw e;
3254 } finally {
3255 FS.closeStream(stream.fd);
3256 }
3257 },llseek:function (stream, offset, whence) {
3258 if (!stream.seekable || !stream.stream_ops.llseek) {
3259 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3260 }
3261 return stream.stream_ops.llseek(stream, offset, whence);
3262 },read:function (stream, buffer, offset, length, position) {
3263 if (length < 0 || position < 0) {
3264 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3265 }
3266 if ((stream.flags & 2097155) === 1) {
3267 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3268 }
3269 if (FS.isDir(stream.node.mode)) {
3270 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3271 }
3272 if (!stream.stream_ops.read) {
3273 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3274 }
3275 var seeking = true;
3276 if (typeof position === 'undefined') {
3277 position = stream.position;
3278 seeking = false;
3279 } else if (!stream.seekable) {
3280 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3281 }
3282 var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, p osition);
3283 if (!seeking) stream.position += bytesRead;
3284 return bytesRead;
3285 },write:function (stream, buffer, offset, length, position, canOwn) {
3286 if (length < 0 || position < 0) {
3287 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3288 }
3289 if ((stream.flags & 2097155) === 0) {
3290 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3291 }
3292 if (FS.isDir(stream.node.mode)) {
3293 throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
3294 }
3295 if (!stream.stream_ops.write) {
3296 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3297 }
3298 var seeking = true;
3299 if (typeof position === 'undefined') {
3300 position = stream.position;
3301 seeking = false;
3302 } else if (!stream.seekable) {
3303 throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
3304 }
3305 if (stream.flags & 1024) {
3306 // seek to the end before writing in append mode
3307 FS.llseek(stream, 0, 2);
3308 }
3309 var bytesWritten = stream.stream_ops.write(stream, buffer, offset, lengt h, position, canOwn);
3310 if (!seeking) stream.position += bytesWritten;
3311 return bytesWritten;
3312 },allocate:function (stream, offset, length) {
3313 if (offset < 0 || length <= 0) {
3314 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
3315 }
3316 if ((stream.flags & 2097155) === 0) {
3317 throw new FS.ErrnoError(ERRNO_CODES.EBADF);
3318 }
3319 if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
3320 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3321 }
3322 if (!stream.stream_ops.allocate) {
3323 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
3324 }
3325 stream.stream_ops.allocate(stream, offset, length);
3326 },mmap:function (stream, buffer, offset, length, position, prot, flags) {
3327 // TODO if PROT is PROT_WRITE, make sure we have write access
3328 if ((stream.flags & 2097155) === 1) {
3329 throw new FS.ErrnoError(ERRNO_CODES.EACCES);
3330 }
3331 if (!stream.stream_ops.mmap) {
3332 throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
3333 }
3334 return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
3335 },ioctl:function (stream, cmd, arg) {
3336 if (!stream.stream_ops.ioctl) {
3337 throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
3338 }
3339 return stream.stream_ops.ioctl(stream, cmd, arg);
3340 },readFile:function (path, opts) {
3341 opts = opts || {};
3342 opts.flags = opts.flags || 'r';
3343 opts.encoding = opts.encoding || 'binary';
3344 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3345 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3346 }
3347 var ret;
3348 var stream = FS.open(path, opts.flags);
3349 var stat = FS.stat(path);
3350 var length = stat.size;
3351 var buf = new Uint8Array(length);
3352 FS.read(stream, buf, 0, length, 0);
3353 if (opts.encoding === 'utf8') {
3354 ret = '';
3355 var utf8 = new Runtime.UTF8Processor();
3356 for (var i = 0; i < length; i++) {
3357 ret += utf8.processCChar(buf[i]);
3358 }
3359 } else if (opts.encoding === 'binary') {
3360 ret = buf;
3361 }
3362 FS.close(stream);
3363 return ret;
3364 },writeFile:function (path, data, opts) {
3365 opts = opts || {};
3366 opts.flags = opts.flags || 'w';
3367 opts.encoding = opts.encoding || 'utf8';
3368 if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3369 throw new Error('Invalid encoding type "' + opts.encoding + '"');
3370 }
3371 var stream = FS.open(path, opts.flags, opts.mode);
3372 if (opts.encoding === 'utf8') {
3373 var utf8 = new Runtime.UTF8Processor();
3374 var buf = new Uint8Array(utf8.processJSString(data));
3375 FS.write(stream, buf, 0, buf.length, 0, opts.canOwn);
3376 } else if (opts.encoding === 'binary') {
3377 FS.write(stream, data, 0, data.length, 0, opts.canOwn);
3378 }
3379 FS.close(stream);
3380 },cwd:function () {
3381 return FS.currentPath;
3382 },chdir:function (path) {
3383 var lookup = FS.lookupPath(path, { follow: true });
3384 if (!FS.isDir(lookup.node.mode)) {
3385 throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
3386 }
3387 var err = FS.nodePermissions(lookup.node, 'x');
3388 if (err) {
3389 throw new FS.ErrnoError(err);
3390 }
3391 FS.currentPath = lookup.path;
3392 },createDefaultDirectories:function () {
3393 FS.mkdir('/tmp');
3394 },createDefaultDevices:function () {
3395 // create /dev
3396 FS.mkdir('/dev');
3397 // setup /dev/null
3398 FS.registerDevice(FS.makedev(1, 3), {
3399 read: function() { return 0; },
3400 write: function() { return 0; }
3401 });
3402 FS.mkdev('/dev/null', FS.makedev(1, 3));
3403 // setup /dev/tty and /dev/tty1
3404 // stderr needs to print output using Module['printErr']
3405 // so we register a second tty just for it.
3406 TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
3407 TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
3408 FS.mkdev('/dev/tty', FS.makedev(5, 0));
3409 FS.mkdev('/dev/tty1', FS.makedev(6, 0));
3410 // we're not going to emulate the actual shm device,
3411 // just create the tmp dirs that reside in it commonly
3412 FS.mkdir('/dev/shm');
3413 FS.mkdir('/dev/shm/tmp');
3414 },createStandardStreams:function () {
3415 // TODO deprecate the old functionality of a single
3416 // input / output callback and that utilizes FS.createDevice
3417 // and instead require a unique set of stream ops
3418
3419 // by default, we symlink the standard streams to the
3420 // default tty devices. however, if the standard streams
3421 // have been overwritten we create a unique device for
3422 // them instead.
3423 if (Module['stdin']) {
3424 FS.createDevice('/dev', 'stdin', Module['stdin']);
3425 } else {
3426 FS.symlink('/dev/tty', '/dev/stdin');
3427 }
3428 if (Module['stdout']) {
3429 FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3430 } else {
3431 FS.symlink('/dev/tty', '/dev/stdout');
3432 }
3433 if (Module['stderr']) {
3434 FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3435 } else {
3436 FS.symlink('/dev/tty1', '/dev/stderr');
3437 }
3438
3439 // open default streams for the stdin, stdout and stderr devices
3440 var stdin = FS.open('/dev/stdin', 'r');
3441 HEAP32[((_stdin)>>2)]=FS.getPtrForStream(stdin);
3442 assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
3443
3444 var stdout = FS.open('/dev/stdout', 'w');
3445 HEAP32[((_stdout)>>2)]=FS.getPtrForStream(stdout);
3446 assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')') ;
3447
3448 var stderr = FS.open('/dev/stderr', 'w');
3449 HEAP32[((_stderr)>>2)]=FS.getPtrForStream(stderr);
3450 assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')') ;
3451 },ensureErrnoError:function () {
3452 if (FS.ErrnoError) return;
3453 FS.ErrnoError = function ErrnoError(errno) {
3454 this.errno = errno;
3455 for (var key in ERRNO_CODES) {
3456 if (ERRNO_CODES[key] === errno) {
3457 this.code = key;
3458 break;
3459 }
3460 }
3461 this.message = ERRNO_MESSAGES[errno];
3462 };
3463 FS.ErrnoError.prototype = new Error();
3464 FS.ErrnoError.prototype.constructor = FS.ErrnoError;
3465 // Some errors may happen quite a bit, to avoid overhead we reuse them ( and suffer a lack of stack info)
3466 [ERRNO_CODES.ENOENT].forEach(function(code) {
3467 FS.genericErrors[code] = new FS.ErrnoError(code);
3468 FS.genericErrors[code].stack = '<generic error, no stack>';
3469 });
3470 },staticInit:function () {
3471 FS.ensureErrnoError();
3472
3473 FS.nameTable = new Array(4096);
3474
3475 FS.mount(MEMFS, {}, '/');
3476
3477 FS.createDefaultDirectories();
3478 FS.createDefaultDevices();
3479 },init:function (input, output, error) {
3480 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)');
3481 FS.init.initialized = true;
3482
3483 FS.ensureErrnoError();
3484
3485 // Allow Module.stdin etc. to provide defaults, if none explicitly passe d to us here
3486 Module['stdin'] = input || Module['stdin'];
3487 Module['stdout'] = output || Module['stdout'];
3488 Module['stderr'] = error || Module['stderr'];
3489
3490 FS.createStandardStreams();
3491 },quit:function () {
3492 FS.init.initialized = false;
3493 for (var i = 0; i < FS.streams.length; i++) {
3494 var stream = FS.streams[i];
3495 if (!stream) {
3496 continue;
3497 }
3498 FS.close(stream);
3499 }
3500 },getMode:function (canRead, canWrite) {
3501 var mode = 0;
3502 if (canRead) mode |= 292 | 73;
3503 if (canWrite) mode |= 146;
3504 return mode;
3505 },joinPath:function (parts, forceRelative) {
3506 var path = PATH.join.apply(null, parts);
3507 if (forceRelative && path[0] == '/') path = path.substr(1);
3508 return path;
3509 },absolutePath:function (relative, base) {
3510 return PATH.resolve(base, relative);
3511 },standardizePath:function (path) {
3512 return PATH.normalize(path);
3513 },findObject:function (path, dontResolveLastLink) {
3514 var ret = FS.analyzePath(path, dontResolveLastLink);
3515 if (ret.exists) {
3516 return ret.object;
3517 } else {
3518 ___setErrNo(ret.error);
3519 return null;
3520 }
3521 },analyzePath:function (path, dontResolveLastLink) {
3522 // operate from within the context of the symlink's target
3523 try {
3524 var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3525 path = lookup.path;
3526 } catch (e) {
3527 }
3528 var ret = {
3529 isRoot: false, exists: false, error: 0, name: null, path: null, object : null,
3530 parentExists: false, parentPath: null, parentObject: null
3531 };
3532 try {
3533 var lookup = FS.lookupPath(path, { parent: true });
3534 ret.parentExists = true;
3535 ret.parentPath = lookup.path;
3536 ret.parentObject = lookup.node;
3537 ret.name = PATH.basename(path);
3538 lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3539 ret.exists = true;
3540 ret.path = lookup.path;
3541 ret.object = lookup.node;
3542 ret.name = lookup.node.name;
3543 ret.isRoot = lookup.path === '/';
3544 } catch (e) {
3545 ret.error = e.errno;
3546 };
3547 return ret;
3548 },createFolder:function (parent, name, canRead, canWrite) {
3549 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(p arent), name);
3550 var mode = FS.getMode(canRead, canWrite);
3551 return FS.mkdir(path, mode);
3552 },createPath:function (parent, path, canRead, canWrite) {
3553 parent = typeof parent === 'string' ? parent : FS.getPath(parent);
3554 var parts = path.split('/').reverse();
3555 while (parts.length) {
3556 var part = parts.pop();
3557 if (!part) continue;
3558 var current = PATH.join2(parent, part);
3559 try {
3560 FS.mkdir(current);
3561 } catch (e) {
3562 // ignore EEXIST
3563 }
3564 parent = current;
3565 }
3566 return current;
3567 },createFile:function (parent, name, properties, canRead, canWrite) {
3568 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(p arent), name);
3569 var mode = FS.getMode(canRead, canWrite);
3570 return FS.create(path, mode);
3571 },createDataFile:function (parent, name, data, canRead, canWrite, canOwn) {
3572 var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.ge tPath(parent), name) : parent;
3573 var mode = FS.getMode(canRead, canWrite);
3574 var node = FS.create(path, mode);
3575 if (data) {
3576 if (typeof data === 'string') {
3577 var arr = new Array(data.length);
3578 for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charC odeAt(i);
3579 data = arr;
3580 }
3581 // make sure we can write to the file
3582 FS.chmod(node, mode | 146);
3583 var stream = FS.open(node, 'w');
3584 FS.write(stream, data, 0, data.length, 0, canOwn);
3585 FS.close(stream);
3586 FS.chmod(node, mode);
3587 }
3588 return node;
3589 },createDevice:function (parent, name, input, output) {
3590 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(p arent), name);
3591 var mode = FS.getMode(!!input, !!output);
3592 if (!FS.createDevice.major) FS.createDevice.major = 64;
3593 var dev = FS.makedev(FS.createDevice.major++, 0);
3594 // Create a fake device that a set of stream ops to emulate
3595 // the old behavior.
3596 FS.registerDevice(dev, {
3597 open: function(stream) {
3598 stream.seekable = false;
3599 },
3600 close: function(stream) {
3601 // flush any pending line data
3602 if (output && output.buffer && output.buffer.length) {
3603 output(10);
3604 }
3605 },
3606 read: function(stream, buffer, offset, length, pos /* ignored */) {
3607 var bytesRead = 0;
3608 for (var i = 0; i < length; i++) {
3609 var result;
3610 try {
3611 result = input();
3612 } catch (e) {
3613 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3614 }
3615 if (result === undefined && bytesRead === 0) {
3616 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
3617 }
3618 if (result === null || result === undefined) break;
3619 bytesRead++;
3620 buffer[offset+i] = result;
3621 }
3622 if (bytesRead) {
3623 stream.node.timestamp = Date.now();
3624 }
3625 return bytesRead;
3626 },
3627 write: function(stream, buffer, offset, length, pos) {
3628 for (var i = 0; i < length; i++) {
3629 try {
3630 output(buffer[offset+i]);
3631 } catch (e) {
3632 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3633 }
3634 }
3635 if (length) {
3636 stream.node.timestamp = Date.now();
3637 }
3638 return i;
3639 }
3640 });
3641 return FS.mkdev(path, mode, dev);
3642 },createLink:function (parent, name, target, canRead, canWrite) {
3643 var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(p arent), name);
3644 return FS.symlink(target, path);
3645 },forceLoadFile:function (obj) {
3646 if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return tru e;
3647 var success = true;
3648 if (typeof XMLHttpRequest !== 'undefined') {
3649 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.");
3650 } else if (Module['read']) {
3651 // Command-line.
3652 try {
3653 // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
3654 // read() will try to parse UTF8.
3655 obj.contents = intArrayFromString(Module['read'](obj.url), true);
3656 } catch (e) {
3657 success = false;
3658 }
3659 } else {
3660 throw new Error('Cannot load without read() or XMLHttpRequest.');
3661 }
3662 if (!success) ___setErrNo(ERRNO_CODES.EIO);
3663 return success;
3664 },createLazyFile:function (parent, name, url, canRead, canWrite) {
3665 // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
3666 function LazyUint8Array() {
3667 this.lengthKnown = false;
3668 this.chunks = []; // Loaded chunks. Index is the chunk number
3669 }
3670 LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
3671 if (idx > this.length-1 || idx < 0) {
3672 return undefined;
3673 }
3674 var chunkOffset = idx % this.chunkSize;
3675 var chunkNum = Math.floor(idx / this.chunkSize);
3676 return this.getter(chunkNum)[chunkOffset];
3677 }
3678 LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setData Getter(getter) {
3679 this.getter = getter;
3680 }
3681 LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLeng th() {
3682 // Find length
3683 var xhr = new XMLHttpRequest();
3684 xhr.open('HEAD', url, false);
3685 xhr.send(null);
3686 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3687 var datalength = Number(xhr.getResponseHeader("Content-length"));
3688 var header;
3689 var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges" )) && header === "bytes";
3690 var chunkSize = 1024*1024; // Chunk size in bytes
3691
3692 if (!hasByteServing) chunkSize = datalength;
3693
3694 // Function to get a range from the remote URL.
3695 var doXHR = (function(from, to) {
3696 if (from > to) throw new Error("invalid range (" + from + ", " + t o + ") or no bytes requested!");
3697 if (to > datalength-1) throw new Error("only " + datalength + " by tes available! programmer error!");
3698
3699 // TODO: Use mozResponseArrayBuffer, responseStream, etc. if avail able.
3700 var xhr = new XMLHttpRequest();
3701 xhr.open('GET', url, false);
3702 if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes =" + from + "-" + to);
3703
3704 // Some hints to the browser that we want binary data.
3705 if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuf fer';
3706 if (xhr.overrideMimeType) {
3707 xhr.overrideMimeType('text/plain; charset=x-user-defined');
3708 }
3709
3710 xhr.send(null);
3711 if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3712 if (xhr.response !== undefined) {
3713 return new Uint8Array(xhr.response || []);
3714 } else {
3715 return intArrayFromString(xhr.responseText || '', true);
3716 }
3717 });
3718 var lazyArray = this;
3719 lazyArray.setDataGetter(function(chunkNum) {
3720 var start = chunkNum * chunkSize;
3721 var end = (chunkNum+1) * chunkSize - 1; // including this byte
3722 end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
3723 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
3724 lazyArray.chunks[chunkNum] = doXHR(start, end);
3725 }
3726 if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3727 return lazyArray.chunks[chunkNum];
3728 });
3729
3730 this._length = datalength;
3731 this._chunkSize = chunkSize;
3732 this.lengthKnown = true;
3733 }
3734 if (typeof XMLHttpRequest !== 'undefined') {
3735 if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs o utside webworkers in modern browsers. Use --embed-file or --preload-file in emcc ';
3736 var lazyArray = new LazyUint8Array();
3737 Object.defineProperty(lazyArray, "length", {
3738 get: function() {
3739 if(!this.lengthKnown) {
3740 this.cacheLength();
3741 }
3742 return this._length;
3743 }
3744 });
3745 Object.defineProperty(lazyArray, "chunkSize", {
3746 get: function() {
3747 if(!this.lengthKnown) {
3748 this.cacheLength();
3749 }
3750 return this._chunkSize;
3751 }
3752 });
3753
3754 var properties = { isDevice: false, contents: lazyArray };
3755 } else {
3756 var properties = { isDevice: false, url: url };
3757 }
3758
3759 var node = FS.createFile(parent, name, properties, canRead, canWrite);
3760 // This is a total hack, but I want to get this lazy file code out of th e
3761 // core of MEMFS. If we want to keep this lazy file concept I feel it sh ould
3762 // be its own thin LAZYFS proxying calls to MEMFS.
3763 if (properties.contents) {
3764 node.contents = properties.contents;
3765 } else if (properties.url) {
3766 node.contents = null;
3767 node.url = properties.url;
3768 }
3769 // override each stream op with one that tries to force load the lazy fi le first
3770 var stream_ops = {};
3771 var keys = Object.keys(node.stream_ops);
3772 keys.forEach(function(key) {
3773 var fn = node.stream_ops[key];
3774 stream_ops[key] = function forceLoadLazyFile() {
3775 if (!FS.forceLoadFile(node)) {
3776 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3777 }
3778 return fn.apply(null, arguments);
3779 };
3780 });
3781 // use a custom read function
3782 stream_ops.read = function stream_ops_read(stream, buffer, offset, lengt h, position) {
3783 if (!FS.forceLoadFile(node)) {
3784 throw new FS.ErrnoError(ERRNO_CODES.EIO);
3785 }
3786 var contents = stream.node.contents;
3787 if (position >= contents.length)
3788 return 0;
3789 var size = Math.min(contents.length - position, length);
3790 assert(size >= 0);
3791 if (contents.slice) { // normal array
3792 for (var i = 0; i < size; i++) {
3793 buffer[offset + i] = contents[position + i];
3794 }
3795 } else {
3796 for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
3797 buffer[offset + i] = contents.get(position + i);
3798 }
3799 }
3800 return size;
3801 };
3802 node.stream_ops = stream_ops;
3803 return node;
3804 },createPreloadedFile:function (parent, name, url, canRead, canWrite, onlo ad, onerror, dontCreateFile, canOwn) {
3805 Browser.init();
3806 // TODO we should allow people to just pass in a complete filename inste ad
3807 // of parent and name being that we just join them anyways
3808 var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
3809 function processData(byteArray) {
3810 function finish(byteArray) {
3811 if (!dontCreateFile) {
3812 FS.createDataFile(parent, name, byteArray, canRead, canWrite, canO wn);
3813 }
3814 if (onload) onload();
3815 removeRunDependency('cp ' + fullname);
3816 }
3817 var handled = false;
3818 Module['preloadPlugins'].forEach(function(plugin) {
3819 if (handled) return;
3820 if (plugin['canHandle'](fullname)) {
3821 plugin['handle'](byteArray, fullname, finish, function() {
3822 if (onerror) onerror();
3823 removeRunDependency('cp ' + fullname);
3824 });
3825 handled = true;
3826 }
3827 });
3828 if (!handled) finish(byteArray);
3829 }
3830 addRunDependency('cp ' + fullname);
3831 if (typeof url == 'string') {
3832 Browser.asyncLoad(url, function(byteArray) {
3833 processData(byteArray);
3834 }, onerror);
3835 } else {
3836 processData(url);
3837 }
3838 },indexedDB:function () {
3839 return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
3840 },DB_NAME:function () {
3841 return 'EM_FS_' + window.location.pathname;
3842 },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function (paths, o nload, onerror) {
3843 onload = onload || function(){};
3844 onerror = onerror || function(){};
3845 var indexedDB = FS.indexedDB();
3846 try {
3847 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3848 } catch (e) {
3849 return onerror(e);
3850 }
3851 openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
3852 console.log('creating db');
3853 var db = openRequest.result;
3854 db.createObjectStore(FS.DB_STORE_NAME);
3855 };
3856 openRequest.onsuccess = function openRequest_onsuccess() {
3857 var db = openRequest.result;
3858 var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
3859 var files = transaction.objectStore(FS.DB_STORE_NAME);
3860 var ok = 0, fail = 0, total = paths.length;
3861 function finish() {
3862 if (fail == 0) onload(); else onerror();
3863 }
3864 paths.forEach(function(path) {
3865 var putRequest = files.put(FS.analyzePath(path).object.contents, pat h);
3866 putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (o k + fail == total) finish() };
3867 putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
3868 });
3869 transaction.onerror = onerror;
3870 };
3871 openRequest.onerror = onerror;
3872 },loadFilesFromDB:function (paths, onload, onerror) {
3873 onload = onload || function(){};
3874 onerror = onerror || function(){};
3875 var indexedDB = FS.indexedDB();
3876 try {
3877 var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
3878 } catch (e) {
3879 return onerror(e);
3880 }
3881 openRequest.onupgradeneeded = onerror; // no database to load from
3882 openRequest.onsuccess = function openRequest_onsuccess() {
3883 var db = openRequest.result;
3884 try {
3885 var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
3886 } catch(e) {
3887 onerror(e);
3888 return;
3889 }
3890 var files = transaction.objectStore(FS.DB_STORE_NAME);
3891 var ok = 0, fail = 0, total = paths.length;
3892 function finish() {
3893 if (fail == 0) onload(); else onerror();
3894 }
3895 paths.forEach(function(path) {
3896 var getRequest = files.get(path);
3897 getRequest.onsuccess = function getRequest_onsuccess() {
3898 if (FS.analyzePath(path).exists) {
3899 FS.unlink(path);
3900 }
3901 FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequ est.result, true, true, true);
3902 ok++;
3903 if (ok + fail == total) finish();
3904 };
3905 getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
3906 });
3907 transaction.onerror = onerror;
3908 };
3909 openRequest.onerror = onerror;
3910 }};
3911
3912
3913
3914
3915 function _mkport() { throw 'TODO' }var SOCKFS={mount:function (mount) {
3916 return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
3917 },createSocket:function (family, type, protocol) {
3918 var streaming = type == 1;
3919 if (protocol) {
3920 assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
3921 }
3922
3923 // create our internal socket structure
3924 var sock = {
3925 family: family,
3926 type: type,
3927 protocol: protocol,
3928 server: null,
3929 peers: {},
3930 pending: [],
3931 recv_queue: [],
3932 sock_ops: SOCKFS.websocket_sock_ops
3933 };
3934
3935 // create the filesystem node to store the socket structure
3936 var name = SOCKFS.nextname();
3937 var node = FS.createNode(SOCKFS.root, name, 49152, 0);
3938 node.sock = sock;
3939
3940 // and the wrapping stream that enables library functions such
3941 // as read and write to indirectly interact with the socket
3942 var stream = FS.createStream({
3943 path: name,
3944 node: node,
3945 flags: FS.modeStringToFlags('r+'),
3946 seekable: false,
3947 stream_ops: SOCKFS.stream_ops
3948 });
3949
3950 // map the new stream to the socket structure (sockets have a 1:1
3951 // relationship with a stream)
3952 sock.stream = stream;
3953
3954 return sock;
3955 },getSocket:function (fd) {
3956 var stream = FS.getStream(fd);
3957 if (!stream || !FS.isSocket(stream.node.mode)) {
3958 return null;
3959 }
3960 return stream.node.sock;
3961 },stream_ops:{poll:function (stream) {
3962 var sock = stream.node.sock;
3963 return sock.sock_ops.poll(sock);
3964 },ioctl:function (stream, request, varargs) {
3965 var sock = stream.node.sock;
3966 return sock.sock_ops.ioctl(sock, request, varargs);
3967 },read:function (stream, buffer, offset, length, position /* ignored */) {
3968 var sock = stream.node.sock;
3969 var msg = sock.sock_ops.recvmsg(sock, length);
3970 if (!msg) {
3971 // socket is closed
3972 return 0;
3973 }
3974 buffer.set(msg.buffer, offset);
3975 return msg.buffer.length;
3976 },write:function (stream, buffer, offset, length, position /* ignored */ ) {
3977 var sock = stream.node.sock;
3978 return sock.sock_ops.sendmsg(sock, buffer, offset, length);
3979 },close:function (stream) {
3980 var sock = stream.node.sock;
3981 sock.sock_ops.close(sock);
3982 }},nextname:function () {
3983 if (!SOCKFS.nextname.current) {
3984 SOCKFS.nextname.current = 0;
3985 }
3986 return 'socket[' + (SOCKFS.nextname.current++) + ']';
3987 },websocket_sock_ops:{createPeer:function (sock, addr, port) {
3988 var ws;
3989
3990 if (typeof addr === 'object') {
3991 ws = addr;
3992 addr = null;
3993 port = null;
3994 }
3995
3996 if (ws) {
3997 // for sockets that've already connected (e.g. we're the server)
3998 // we can inspect the _socket property for the address
3999 if (ws._socket) {
4000 addr = ws._socket.remoteAddress;
4001 port = ws._socket.remotePort;
4002 }
4003 // if we're just now initializing a connection to the remote,
4004 // inspect the url property
4005 else {
4006 var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
4007 if (!result) {
4008 throw new Error('WebSocket URL must be in the format ws(s)://add ress:port');
4009 }
4010 addr = result[1];
4011 port = parseInt(result[2], 10);
4012 }
4013 } else {
4014 // create the actual websocket object and connect
4015 try {
4016 // runtimeConfig gets set to true if WebSocket runtime configurati on is available.
4017 var runtimeConfig = (Module['websocket'] && ('object' === typeof M odule['websocket']));
4018
4019 // The default value is 'ws://' the replace is needed because the compiler replaces "//" comments with '#'
4020 // comments without checking context, so we'd end up with ws:#, th e replace swaps the "#" for "//" again.
4021 var url = 'ws:#'.replace('#', '//');
4022
4023 if (runtimeConfig) {
4024 if ('string' === typeof Module['websocket']['url']) {
4025 url = Module['websocket']['url']; // Fetch runtime WebSocket U RL config.
4026 }
4027 }
4028
4029 if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
4030 url = url + addr + ':' + port;
4031 }
4032
4033 // Make the WebSocket subprotocol (Sec-WebSocket-Protocol) default to binary if no configuration is set.
4034 var subProtocols = 'binary'; // The default value is 'binary'
4035
4036 if (runtimeConfig) {
4037 if ('string' === typeof Module['websocket']['subprotocol']) {
4038 subProtocols = Module['websocket']['subprotocol']; // Fetch ru ntime WebSocket subprotocol config.
4039 }
4040 }
4041
4042 // The regex trims the string (removes spaces at the beginning and end, then splits the string by
4043 // <any space>,<any space> into an Array. Whitespace removal is im portant for Websockify and ws.
4044 subProtocols = subProtocols.replace(/^ +| +$/g,"").split(/ *, */);
4045
4046 // The node ws library API for specifying optional subprotocol is slightly different than the browser's.
4047 var opts = ENVIRONMENT_IS_NODE ? {'protocol': subProtocols.toStrin g()} : subProtocols;
4048
4049 // If node we use the ws library.
4050 var WebSocket = ENVIRONMENT_IS_NODE ? require('ws') : window['WebS ocket'];
4051 ws = new WebSocket(url, opts);
4052 ws.binaryType = 'arraybuffer';
4053 } catch (e) {
4054 throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
4055 }
4056 }
4057
4058
4059 var peer = {
4060 addr: addr,
4061 port: port,
4062 socket: ws,
4063 dgram_send_queue: []
4064 };
4065
4066 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4067 SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
4068
4069 // if this is a bound dgram socket, send the port number first to allo w
4070 // us to override the ephemeral port reported to us by remotePort on t he
4071 // remote end.
4072 if (sock.type === 2 && typeof sock.sport !== 'undefined') {
4073 peer.dgram_send_queue.push(new Uint8Array([
4074 255, 255, 255, 255,
4075 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.cha rCodeAt(0),
4076 ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
4077 ]));
4078 }
4079
4080 return peer;
4081 },getPeer:function (sock, addr, port) {
4082 return sock.peers[addr + ':' + port];
4083 },addPeer:function (sock, peer) {
4084 sock.peers[peer.addr + ':' + peer.port] = peer;
4085 },removePeer:function (sock, peer) {
4086 delete sock.peers[peer.addr + ':' + peer.port];
4087 },handlePeerEvents:function (sock, peer) {
4088 var first = true;
4089
4090 var handleOpen = function () {
4091 try {
4092 var queued = peer.dgram_send_queue.shift();
4093 while (queued) {
4094 peer.socket.send(queued);
4095 queued = peer.dgram_send_queue.shift();
4096 }
4097 } catch (e) {
4098 // not much we can do here in the way of proper error handling as we've already
4099 // lied and said this data was sent. shut it down.
4100 peer.socket.close();
4101 }
4102 };
4103
4104 function handleMessage(data) {
4105 assert(typeof data !== 'string' && data.byteLength !== undefined); // must receive an ArrayBuffer
4106 data = new Uint8Array(data); // make a typed array view on the arra y buffer
4107
4108
4109 // if this is the port message, override the peer's port with it
4110 var wasfirst = first;
4111 first = false;
4112 if (wasfirst &&
4113 data.length === 10 &&
4114 data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
4115 data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) & & data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
4116 // update the peer's port and it's key in the peer map
4117 var newport = ((data[8] << 8) | data[9]);
4118 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4119 peer.port = newport;
4120 SOCKFS.websocket_sock_ops.addPeer(sock, peer);
4121 return;
4122 }
4123
4124 sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
4125 };
4126
4127 if (ENVIRONMENT_IS_NODE) {
4128 peer.socket.on('open', handleOpen);
4129 peer.socket.on('message', function(data, flags) {
4130 if (!flags.binary) {
4131 return;
4132 }
4133 handleMessage((new Uint8Array(data)).buffer); // copy from node B uffer -> ArrayBuffer
4134 });
4135 peer.socket.on('error', function() {
4136 // don't throw
4137 });
4138 } else {
4139 peer.socket.onopen = handleOpen;
4140 peer.socket.onmessage = function peer_socket_onmessage(event) {
4141 handleMessage(event.data);
4142 };
4143 }
4144 },poll:function (sock) {
4145 if (sock.type === 1 && sock.server) {
4146 // listen sockets should only say they're available for reading
4147 // if there are pending clients.
4148 return sock.pending.length ? (64 | 1) : 0;
4149 }
4150
4151 var mask = 0;
4152 var dest = sock.type === 1 ? // we only care about the socket state f or connection-based sockets
4153 SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
4154 null;
4155
4156 if (sock.recv_queue.length ||
4157 !dest || // connection-less sockets are always ready to read
4158 (dest && dest.socket.readyState === dest.socket.CLOSING) ||
4159 (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
4160 mask |= (64 | 1);
4161 }
4162
4163 if (!dest || // connection-less sockets are always ready to write
4164 (dest && dest.socket.readyState === dest.socket.OPEN)) {
4165 mask |= 4;
4166 }
4167
4168 if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
4169 (dest && dest.socket.readyState === dest.socket.CLOSED)) {
4170 mask |= 16;
4171 }
4172
4173 return mask;
4174 },ioctl:function (sock, request, arg) {
4175 switch (request) {
4176 case 21531:
4177 var bytes = 0;
4178 if (sock.recv_queue.length) {
4179 bytes = sock.recv_queue[0].data.length;
4180 }
4181 HEAP32[((arg)>>2)]=bytes;
4182 return 0;
4183 default:
4184 return ERRNO_CODES.EINVAL;
4185 }
4186 },close:function (sock) {
4187 // if we've spawned a listen server, close it
4188 if (sock.server) {
4189 try {
4190 sock.server.close();
4191 } catch (e) {
4192 }
4193 sock.server = null;
4194 }
4195 // close any peer connections
4196 var peers = Object.keys(sock.peers);
4197 for (var i = 0; i < peers.length; i++) {
4198 var peer = sock.peers[peers[i]];
4199 try {
4200 peer.socket.close();
4201 } catch (e) {
4202 }
4203 SOCKFS.websocket_sock_ops.removePeer(sock, peer);
4204 }
4205 return 0;
4206 },bind:function (sock, addr, port) {
4207 if (typeof sock.saddr !== 'undefined' || typeof sock.sport !== 'undefi ned') {
4208 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already bound
4209 }
4210 sock.saddr = addr;
4211 sock.sport = port || _mkport();
4212 // in order to emulate dgram sockets, we need to launch a listen serve r when
4213 // binding on a connection-less socket
4214 // note: this is only required on the server side
4215 if (sock.type === 2) {
4216 // close the existing server if it exists
4217 if (sock.server) {
4218 sock.server.close();
4219 sock.server = null;
4220 }
4221 // swallow error operation not supported error that occurs when bind ing in the
4222 // browser where this isn't supported
4223 try {
4224 sock.sock_ops.listen(sock, 0);
4225 } catch (e) {
4226 if (!(e instanceof FS.ErrnoError)) throw e;
4227 if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
4228 }
4229 }
4230 },connect:function (sock, addr, port) {
4231 if (sock.server) {
4232 throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
4233 }
4234
4235 // TODO autobind
4236 // if (!sock.addr && sock.type == 2) {
4237 // }
4238
4239 // early out if we're already connected / in the middle of connecting
4240 if (typeof sock.daddr !== 'undefined' && typeof sock.dport !== 'undefi ned') {
4241 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock. dport);
4242 if (dest) {
4243 if (dest.socket.readyState === dest.socket.CONNECTING) {
4244 throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
4245 } else {
4246 throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
4247 }
4248 }
4249 }
4250
4251 // add the socket to our peer list and set our
4252 // destination address / port to match
4253 var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4254 sock.daddr = peer.addr;
4255 sock.dport = peer.port;
4256
4257 // always "fail" in non-blocking mode
4258 throw new FS.ErrnoError(ERRNO_CODES.EINPROGRESS);
4259 },listen:function (sock, backlog) {
4260 if (!ENVIRONMENT_IS_NODE) {
4261 throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
4262 }
4263 if (sock.server) {
4264 throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already listening
4265 }
4266 var WebSocketServer = require('ws').Server;
4267 var host = sock.saddr;
4268 sock.server = new WebSocketServer({
4269 host: host,
4270 port: sock.sport
4271 // TODO support backlog
4272 });
4273
4274 sock.server.on('connection', function(ws) {
4275 if (sock.type === 1) {
4276 var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.pro tocol);
4277
4278 // create a peer on the new socket
4279 var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
4280 newsock.daddr = peer.addr;
4281 newsock.dport = peer.port;
4282
4283 // push to queue for accept to pick up
4284 sock.pending.push(newsock);
4285 } else {
4286 // create a peer on the listen socket so calling sendto
4287 // with the listen socket and an address will resolve
4288 // to the correct client
4289 SOCKFS.websocket_sock_ops.createPeer(sock, ws);
4290 }
4291 });
4292 sock.server.on('closed', function() {
4293 sock.server = null;
4294 });
4295 sock.server.on('error', function() {
4296 // don't throw
4297 });
4298 },accept:function (listensock) {
4299 if (!listensock.server) {
4300 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4301 }
4302 var newsock = listensock.pending.shift();
4303 newsock.stream.flags = listensock.stream.flags;
4304 return newsock;
4305 },getname:function (sock, peer) {
4306 var addr, port;
4307 if (peer) {
4308 if (sock.daddr === undefined || sock.dport === undefined) {
4309 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4310 }
4311 addr = sock.daddr;
4312 port = sock.dport;
4313 } else {
4314 // TODO saddr and sport will be set for bind()'d UDP sockets, but wh at
4315 // should we be returning for TCP sockets that've been connect()'d?
4316 addr = sock.saddr || 0;
4317 port = sock.sport || 0;
4318 }
4319 return { addr: addr, port: port };
4320 },sendmsg:function (sock, buffer, offset, length, addr, port) {
4321 if (sock.type === 2) {
4322 // connection-less sockets will honor the message address,
4323 // and otherwise fall back to the bound destination address
4324 if (addr === undefined || port === undefined) {
4325 addr = sock.daddr;
4326 port = sock.dport;
4327 }
4328 // if there was no address to fall back to, error out
4329 if (addr === undefined || port === undefined) {
4330 throw new FS.ErrnoError(ERRNO_CODES.EDESTADDRREQ);
4331 }
4332 } else {
4333 // connection-based sockets will only use the bound
4334 addr = sock.daddr;
4335 port = sock.dport;
4336 }
4337
4338 // find the peer for the destination address
4339 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
4340
4341 // early out if not connected with a connection-based socket
4342 if (sock.type === 1) {
4343 if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest. socket.readyState === dest.socket.CLOSED) {
4344 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4345 } else if (dest.socket.readyState === dest.socket.CONNECTING) {
4346 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4347 }
4348 }
4349
4350 // create a copy of the incoming data to send, as the WebSocket API
4351 // doesn't work entirely with an ArrayBufferView, it'll just send
4352 // the entire underlying buffer
4353 var data;
4354 if (buffer instanceof Array || buffer instanceof ArrayBuffer) {
4355 data = buffer.slice(offset, offset + length);
4356 } else { // ArrayBufferView
4357 data = buffer.buffer.slice(buffer.byteOffset + offset, buffer.byteOf fset + offset + length);
4358 }
4359
4360 // if we're emulating a connection-less dgram socket and don't have
4361 // a cached connection, queue the buffer to send upon connect and
4362 // lie, saying the data was sent now.
4363 if (sock.type === 2) {
4364 if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
4365 // if we're not connected, open a new connection
4366 if (!dest || dest.socket.readyState === dest.socket.CLOSING || des t.socket.readyState === dest.socket.CLOSED) {
4367 dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
4368 }
4369 dest.dgram_send_queue.push(data);
4370 return length;
4371 }
4372 }
4373
4374 try {
4375 // send the actual data
4376 dest.socket.send(data);
4377 return length;
4378 } catch (e) {
4379 throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
4380 }
4381 },recvmsg:function (sock, length) {
4382 // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
4383 if (sock.type === 1 && sock.server) {
4384 // tcp servers should not be recv()'ing on the listen socket
4385 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4386 }
4387
4388 var queued = sock.recv_queue.shift();
4389 if (!queued) {
4390 if (sock.type === 1) {
4391 var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, soc k.dport);
4392
4393 if (!dest) {
4394 // if we have a destination address but are not connected, error out
4395 throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
4396 }
4397 else if (dest.socket.readyState === dest.socket.CLOSING || dest.so cket.readyState === dest.socket.CLOSED) {
4398 // return null if the socket has closed
4399 return null;
4400 }
4401 else {
4402 // else, our socket is in a valid state but truly has nothing av ailable
4403 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4404 }
4405 } else {
4406 throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
4407 }
4408 }
4409
4410 // queued.data will be an ArrayBuffer if it's unadulterated, but if it 's
4411 // requeued TCP data it'll be an ArrayBufferView
4412 var queuedLength = queued.data.byteLength || queued.data.length;
4413 var queuedOffset = queued.data.byteOffset || 0;
4414 var queuedBuffer = queued.data.buffer || queued.data;
4415 var bytesRead = Math.min(length, queuedLength);
4416 var res = {
4417 buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
4418 addr: queued.addr,
4419 port: queued.port
4420 };
4421
4422
4423 // push back any unread data for TCP connections
4424 if (sock.type === 1 && bytesRead < queuedLength) {
4425 var bytesRemaining = queuedLength - bytesRead;
4426 queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
4427 sock.recv_queue.unshift(queued);
4428 }
4429
4430 return res;
4431 }}};function _send(fd, buf, len, flags) {
4432 var sock = SOCKFS.getSocket(fd);
4433 if (!sock) {
4434 ___setErrNo(ERRNO_CODES.EBADF);
4435 return -1;
4436 }
4437 // TODO honor flags
4438 return _write(fd, buf, len);
4439 }
4440
4441 function _pwrite(fildes, buf, nbyte, offset) {
4442 // ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset) ;
4443 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4444 var stream = FS.getStream(fildes);
4445 if (!stream) {
4446 ___setErrNo(ERRNO_CODES.EBADF);
4447 return -1;
4448 }
4449 try {
4450 var slab = HEAP8;
4451 return FS.write(stream, slab, buf, nbyte, offset);
4452 } catch (e) {
4453 FS.handleFSError(e);
4454 return -1;
4455 }
4456 }function _write(fildes, buf, nbyte) {
4457 // ssize_t write(int fildes, const void *buf, size_t nbyte);
4458 // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
4459 var stream = FS.getStream(fildes);
4460 if (!stream) {
4461 ___setErrNo(ERRNO_CODES.EBADF);
4462 return -1;
4463 }
4464
4465
4466 try {
4467 var slab = HEAP8;
4468 return FS.write(stream, slab, buf, nbyte);
4469 } catch (e) {
4470 FS.handleFSError(e);
4471 return -1;
4472 }
4473 }
4474
4475 function _fileno(stream) {
4476 // int fileno(FILE *stream);
4477 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fileno.html
4478 stream = FS.getStreamFromPtr(stream);
4479 if (!stream) return -1;
4480 return stream.fd;
4481 }function _fwrite(ptr, size, nitems, stream) {
4482 // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, FIL E *restrict stream);
4483 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fwrite.html
4484 var bytesToWrite = nitems * size;
4485 if (bytesToWrite == 0) return 0;
4486 var fd = _fileno(stream);
4487 var bytesWritten = _write(fd, ptr, bytesToWrite);
4488 if (bytesWritten == -1) {
4489 var streamObj = FS.getStreamFromPtr(stream);
4490 if (streamObj) streamObj.error = true;
4491 return 0;
4492 } else {
4493 return Math.floor(bytesWritten / size);
4494 }
4495 }
4496
4497
4498
4499 Module["_strlen"] = _strlen;
4500
4501 function __reallyNegative(x) {
4502 return x < 0 || (x === 0 && (1/x) === -Infinity);
4503 }function __formatString(format, varargs) {
4504 var textIndex = format;
4505 var argIndex = 0;
4506 function getNextArg(type) {
4507 // NOTE: Explicitly ignoring type safety. Otherwise this fails:
4508 // int x = 4; printf("%c\n", (char)x);
4509 var ret;
4510 if (type === 'double') {
4511 ret = HEAPF64[(((varargs)+(argIndex))>>3)];
4512 } else if (type == 'i64') {
4513 ret = [HEAP32[(((varargs)+(argIndex))>>2)],
4514 HEAP32[(((varargs)+(argIndex+4))>>2)]];
4515
4516 } else {
4517 type = 'i32'; // varargs are always i32, i64, or double
4518 ret = HEAP32[(((varargs)+(argIndex))>>2)];
4519 }
4520 argIndex += Runtime.getNativeFieldSize(type);
4521 return ret;
4522 }
4523
4524 var ret = [];
4525 var curr, next, currArg;
4526 while(1) {
4527 var startTextIndex = textIndex;
4528 curr = HEAP8[(textIndex)];
4529 if (curr === 0) break;
4530 next = HEAP8[((textIndex+1)|0)];
4531 if (curr == 37) {
4532 // Handle flags.
4533 var flagAlwaysSigned = false;
4534 var flagLeftAlign = false;
4535 var flagAlternative = false;
4536 var flagZeroPad = false;
4537 var flagPadSign = false;
4538 flagsLoop: while (1) {
4539 switch (next) {
4540 case 43:
4541 flagAlwaysSigned = true;
4542 break;
4543 case 45:
4544 flagLeftAlign = true;
4545 break;
4546 case 35:
4547 flagAlternative = true;
4548 break;
4549 case 48:
4550 if (flagZeroPad) {
4551 break flagsLoop;
4552 } else {
4553 flagZeroPad = true;
4554 break;
4555 }
4556 case 32:
4557 flagPadSign = true;
4558 break;
4559 default:
4560 break flagsLoop;
4561 }
4562 textIndex++;
4563 next = HEAP8[((textIndex+1)|0)];
4564 }
4565
4566 // Handle width.
4567 var width = 0;
4568 if (next == 42) {
4569 width = getNextArg('i32');
4570 textIndex++;
4571 next = HEAP8[((textIndex+1)|0)];
4572 } else {
4573 while (next >= 48 && next <= 57) {
4574 width = width * 10 + (next - 48);
4575 textIndex++;
4576 next = HEAP8[((textIndex+1)|0)];
4577 }
4578 }
4579
4580 // Handle precision.
4581 var precisionSet = false, precision = -1;
4582 if (next == 46) {
4583 precision = 0;
4584 precisionSet = true;
4585 textIndex++;
4586 next = HEAP8[((textIndex+1)|0)];
4587 if (next == 42) {
4588 precision = getNextArg('i32');
4589 textIndex++;
4590 } else {
4591 while(1) {
4592 var precisionChr = HEAP8[((textIndex+1)|0)];
4593 if (precisionChr < 48 ||
4594 precisionChr > 57) break;
4595 precision = precision * 10 + (precisionChr - 48);
4596 textIndex++;
4597 }
4598 }
4599 next = HEAP8[((textIndex+1)|0)];
4600 }
4601 if (precision < 0) {
4602 precision = 6; // Standard default.
4603 precisionSet = false;
4604 }
4605
4606 // Handle integer sizes. WARNING: These assume a 32-bit architecture!
4607 var argSize;
4608 switch (String.fromCharCode(next)) {
4609 case 'h':
4610 var nextNext = HEAP8[((textIndex+2)|0)];
4611 if (nextNext == 104) {
4612 textIndex++;
4613 argSize = 1; // char (actually i32 in varargs)
4614 } else {
4615 argSize = 2; // short (actually i32 in varargs)
4616 }
4617 break;
4618 case 'l':
4619 var nextNext = HEAP8[((textIndex+2)|0)];
4620 if (nextNext == 108) {
4621 textIndex++;
4622 argSize = 8; // long long
4623 } else {
4624 argSize = 4; // long
4625 }
4626 break;
4627 case 'L': // long long
4628 case 'q': // int64_t
4629 case 'j': // intmax_t
4630 argSize = 8;
4631 break;
4632 case 'z': // size_t
4633 case 't': // ptrdiff_t
4634 case 'I': // signed ptrdiff_t or unsigned size_t
4635 argSize = 4;
4636 break;
4637 default:
4638 argSize = null;
4639 }
4640 if (argSize) textIndex++;
4641 next = HEAP8[((textIndex+1)|0)];
4642
4643 // Handle type specifier.
4644 switch (String.fromCharCode(next)) {
4645 case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p' : {
4646 // Integer.
4647 var signed = next == 100 || next == 105;
4648 argSize = argSize || 4;
4649 var currArg = getNextArg('i' + (argSize * 8));
4650 var argText;
4651 // Flatten i64-1 [low, high] into a (slightly rounded) double
4652 if (argSize == 8) {
4653 currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117 );
4654 }
4655 // Truncate to requested size.
4656 if (argSize <= 4) {
4657 var limit = Math.pow(256, argSize) - 1;
4658 currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
4659 }
4660 // Format the number.
4661 var currAbsArg = Math.abs(currArg);
4662 var prefix = '';
4663 if (next == 100 || next == 105) {
4664 argText = reSign(currArg, 8 * argSize, 1).toString(10);
4665 } else if (next == 117) {
4666 argText = unSign(currArg, 8 * argSize, 1).toString(10);
4667 currArg = Math.abs(currArg);
4668 } else if (next == 111) {
4669 argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
4670 } else if (next == 120 || next == 88) {
4671 prefix = (flagAlternative && currArg != 0) ? '0x' : '';
4672 if (currArg < 0) {
4673 // Represent negative numbers in hex as 2's complement.
4674 currArg = -currArg;
4675 argText = (currAbsArg - 1).toString(16);
4676 var buffer = [];
4677 for (var i = 0; i < argText.length; i++) {
4678 buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
4679 }
4680 argText = buffer.join('');
4681 while (argText.length < argSize * 2) argText = 'f' + argText;
4682 } else {
4683 argText = currAbsArg.toString(16);
4684 }
4685 if (next == 88) {
4686 prefix = prefix.toUpperCase();
4687 argText = argText.toUpperCase();
4688 }
4689 } else if (next == 112) {
4690 if (currAbsArg === 0) {
4691 argText = '(nil)';
4692 } else {
4693 prefix = '0x';
4694 argText = currAbsArg.toString(16);
4695 }
4696 }
4697 if (precisionSet) {
4698 while (argText.length < precision) {
4699 argText = '0' + argText;
4700 }
4701 }
4702
4703 // Add sign if needed
4704 if (currArg >= 0) {
4705 if (flagAlwaysSigned) {
4706 prefix = '+' + prefix;
4707 } else if (flagPadSign) {
4708 prefix = ' ' + prefix;
4709 }
4710 }
4711
4712 // Move sign to prefix so we zero-pad after the sign
4713 if (argText.charAt(0) == '-') {
4714 prefix = '-' + prefix;
4715 argText = argText.substr(1);
4716 }
4717
4718 // Add padding.
4719 while (prefix.length + argText.length < width) {
4720 if (flagLeftAlign) {
4721 argText += ' ';
4722 } else {
4723 if (flagZeroPad) {
4724 argText = '0' + argText;
4725 } else {
4726 prefix = ' ' + prefix;
4727 }
4728 }
4729 }
4730
4731 // Insert the result into the buffer.
4732 argText = prefix + argText;
4733 argText.split('').forEach(function(chr) {
4734 ret.push(chr.charCodeAt(0));
4735 });
4736 break;
4737 }
4738 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': {
4739 // Float.
4740 var currArg = getNextArg('double');
4741 var argText;
4742 if (isNaN(currArg)) {
4743 argText = 'nan';
4744 flagZeroPad = false;
4745 } else if (!isFinite(currArg)) {
4746 argText = (currArg < 0 ? '-' : '') + 'inf';
4747 flagZeroPad = false;
4748 } else {
4749 var isGeneral = false;
4750 var effectivePrecision = Math.min(precision, 20);
4751
4752 // Convert g/G to f/F or e/E, as per:
4753 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/pri ntf.html
4754 if (next == 103 || next == 71) {
4755 isGeneral = true;
4756 precision = precision || 1;
4757 var exponent = parseInt(currArg.toExponential(effectivePrecisi on).split('e')[1], 10);
4758 if (precision > exponent && exponent >= -4) {
4759 next = ((next == 103) ? 'f' : 'F').charCodeAt(0);
4760 precision -= exponent + 1;
4761 } else {
4762 next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
4763 precision--;
4764 }
4765 effectivePrecision = Math.min(precision, 20);
4766 }
4767
4768 if (next == 101 || next == 69) {
4769 argText = currArg.toExponential(effectivePrecision);
4770 // Make sure the exponent has at least 2 digits.
4771 if (/[eE][-+]\d$/.test(argText)) {
4772 argText = argText.slice(0, -1) + '0' + argText.slice(-1);
4773 }
4774 } else if (next == 102 || next == 70) {
4775 argText = currArg.toFixed(effectivePrecision);
4776 if (currArg === 0 && __reallyNegative(currArg)) {
4777 argText = '-' + argText;
4778 }
4779 }
4780
4781 var parts = argText.split('e');
4782 if (isGeneral && !flagAlternative) {
4783 // Discard trailing zeros and periods.
4784 while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
4785 (parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.' )) {
4786 parts[0] = parts[0].slice(0, -1);
4787 }
4788 } else {
4789 // Make sure we have a period in alternative mode.
4790 if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
4791 // Zero pad until required precision.
4792 while (precision > effectivePrecision++) parts[0] += '0';
4793 }
4794 argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
4795
4796 // Capitalize 'E' if needed.
4797 if (next == 69) argText = argText.toUpperCase();
4798
4799 // Add sign.
4800 if (currArg >= 0) {
4801 if (flagAlwaysSigned) {
4802 argText = '+' + argText;
4803 } else if (flagPadSign) {
4804 argText = ' ' + argText;
4805 }
4806 }
4807 }
4808
4809 // Add padding.
4810 while (argText.length < width) {
4811 if (flagLeftAlign) {
4812 argText += ' ';
4813 } else {
4814 if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
4815 argText = argText[0] + '0' + argText.slice(1);
4816 } else {
4817 argText = (flagZeroPad ? '0' : ' ') + argText;
4818 }
4819 }
4820 }
4821
4822 // Adjust case.
4823 if (next < 97) argText = argText.toUpperCase();
4824
4825 // Insert the result into the buffer.
4826 argText.split('').forEach(function(chr) {
4827 ret.push(chr.charCodeAt(0));
4828 });
4829 break;
4830 }
4831 case 's': {
4832 // String.
4833 var arg = getNextArg('i8*');
4834 var argLength = arg ? _strlen(arg) : '(null)'.length;
4835 if (precisionSet) argLength = Math.min(argLength, precision);
4836 if (!flagLeftAlign) {
4837 while (argLength < width--) {
4838 ret.push(32);
4839 }
4840 }
4841 if (arg) {
4842 for (var i = 0; i < argLength; i++) {
4843 ret.push(HEAPU8[((arg++)|0)]);
4844 }
4845 } else {
4846 ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength ), true));
4847 }
4848 if (flagLeftAlign) {
4849 while (argLength < width--) {
4850 ret.push(32);
4851 }
4852 }
4853 break;
4854 }
4855 case 'c': {
4856 // Character.
4857 if (flagLeftAlign) ret.push(getNextArg('i8'));
4858 while (--width > 0) {
4859 ret.push(32);
4860 }
4861 if (!flagLeftAlign) ret.push(getNextArg('i8'));
4862 break;
4863 }
4864 case 'n': {
4865 // Write the length written so far to the next parameter.
4866 var ptr = getNextArg('i32*');
4867 HEAP32[((ptr)>>2)]=ret.length;
4868 break;
4869 }
4870 case '%': {
4871 // Literal percent sign.
4872 ret.push(curr);
4873 break;
4874 }
4875 default: {
4876 // Unknown specifiers remain untouched.
4877 for (var i = startTextIndex; i < textIndex + 2; i++) {
4878 ret.push(HEAP8[(i)]);
4879 }
4880 }
4881 }
4882 textIndex += 2;
4883 // TODO: Support a/A (hex float) and m (last error) specifiers.
4884 // TODO: Support %1${specifier} for arg selection.
4885 } else {
4886 ret.push(curr);
4887 textIndex += 1;
4888 }
4889 }
4890 return ret;
4891 }function _fprintf(stream, format, varargs) {
4892 // int fprintf(FILE *restrict stream, const char *restrict format, ...);
4893 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
4894 var result = __formatString(format, varargs);
4895 var stack = Runtime.stackSave();
4896 var ret = _fwrite(allocate(result, 'i8', ALLOC_STACK), 1, result.length, s tream);
4897 Runtime.stackRestore(stack);
4898 return ret;
4899 }function _printf(format, varargs) {
4900 // int printf(const char *restrict format, ...);
4901 // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
4902 var stdout = HEAP32[((_stdout)>>2)];
4903 return _fprintf(stdout, format, varargs);
4904 }
4905
4906
4907 function _fputc(c, stream) {
4908 // int fputc(int c, FILE *stream);
4909 // http://pubs.opengroup.org/onlinepubs/000095399/functions/fputc.html
4910 var chr = unSign(c & 0xFF);
4911 HEAP8[((_fputc.ret)|0)]=chr;
4912 var fd = _fileno(stream);
4913 var ret = _write(fd, _fputc.ret, 1);
4914 if (ret == -1) {
4915 var streamObj = FS.getStreamFromPtr(stream);
4916 if (streamObj) streamObj.error = true;
4917 return -1;
4918 } else {
4919 return chr;
4920 }
4921 }function _putchar(c) {
4922 // int putchar(int c);
4923 // http://pubs.opengroup.org/onlinepubs/000095399/functions/putchar.html
4924 return _fputc(c, HEAP32[((_stdout)>>2)]);
4925 }
4926
4927 function _sbrk(bytes) {
4928 // Implement a Linux-like 'memory area' for our 'process'.
4929 // Changes the size of the memory area by |bytes|; returns the
4930 // address of the previous top ('break') of the memory area
4931 // We control the "dynamic" memory - DYNAMIC_BASE to DYNAMICTOP
4932 var self = _sbrk;
4933 if (!self.called) {
4934 DYNAMICTOP = alignMemoryPage(DYNAMICTOP); // make sure we start out alig ned
4935 self.called = true;
4936 assert(Runtime.dynamicAlloc);
4937 self.alloc = Runtime.dynamicAlloc;
4938 Runtime.dynamicAlloc = function() { abort('cannot dynamically allocate, sbrk now has control') };
4939 }
4940 var ret = DYNAMICTOP;
4941 if (bytes != 0) self.alloc(bytes);
4942 return ret; // Previous break location.
4943 }
4944
4945 function _sysconf(name) {
4946 // long sysconf(int name);
4947 // http://pubs.opengroup.org/onlinepubs/009695399/functions/sysconf.html
4948 switch(name) {
4949 case 30: return PAGE_SIZE;
4950 case 132:
4951 case 133:
4952 case 12:
4953 case 137:
4954 case 138:
4955 case 15:
4956 case 235:
4957 case 16:
4958 case 17:
4959 case 18:
4960 case 19:
4961 case 20:
4962 case 149:
4963 case 13:
4964 case 10:
4965 case 236:
4966 case 153:
4967 case 9:
4968 case 21:
4969 case 22:
4970 case 159:
4971 case 154:
4972 case 14:
4973 case 77:
4974 case 78:
4975 case 139:
4976 case 80:
4977 case 81:
4978 case 79:
4979 case 82:
4980 case 68:
4981 case 67:
4982 case 164:
4983 case 11:
4984 case 29:
4985 case 47:
4986 case 48:
4987 case 95:
4988 case 52:
4989 case 51:
4990 case 46:
4991 return 200809;
4992 case 27:
4993 case 246:
4994 case 127:
4995 case 128:
4996 case 23:
4997 case 24:
4998 case 160:
4999 case 161:
5000 case 181:
5001 case 182:
5002 case 242:
5003 case 183:
5004 case 184:
5005 case 243:
5006 case 244:
5007 case 245:
5008 case 165:
5009 case 178:
5010 case 179:
5011 case 49:
5012 case 50:
5013 case 168:
5014 case 169:
5015 case 175:
5016 case 170:
5017 case 171:
5018 case 172:
5019 case 97:
5020 case 76:
5021 case 32:
5022 case 173:
5023 case 35:
5024 return -1;
5025 case 176:
5026 case 177:
5027 case 7:
5028 case 155:
5029 case 8:
5030 case 157:
5031 case 125:
5032 case 126:
5033 case 92:
5034 case 93:
5035 case 129:
5036 case 130:
5037 case 131:
5038 case 94:
5039 case 91:
5040 return 1;
5041 case 74:
5042 case 60:
5043 case 69:
5044 case 70:
5045 case 4:
5046 return 1024;
5047 case 31:
5048 case 42:
5049 case 72:
5050 return 32;
5051 case 87:
5052 case 26:
5053 case 33:
5054 return 2147483647;
5055 case 34:
5056 case 1:
5057 return 47839;
5058 case 38:
5059 case 36:
5060 return 99;
5061 case 43:
5062 case 37:
5063 return 2048;
5064 case 0: return 2097152;
5065 case 3: return 65536;
5066 case 28: return 32768;
5067 case 44: return 32767;
5068 case 75: return 16384;
5069 case 39: return 1000;
5070 case 89: return 700;
5071 case 71: return 256;
5072 case 40: return 255;
5073 case 2: return 100;
5074 case 180: return 64;
5075 case 25: return 20;
5076 case 5: return 16;
5077 case 6: return 6;
5078 case 73: return 4;
5079 case 84: return 1;
5080 }
5081 ___setErrNo(ERRNO_CODES.EINVAL);
5082 return -1;
5083 }
5084
5085
5086 Module["_memset"] = _memset;
5087
5088 function ___errno_location() {
5089 return ___errno_state;
5090 }
5091
5092 function _abort() {
5093 Module['abort']();
5094 }
5095
5096 var Browser={mainLoop:{scheduler:null,method:"",shouldPause:false,paused:false ,queue:[],pause:function () {
5097 Browser.mainLoop.shouldPause = true;
5098 },resume:function () {
5099 if (Browser.mainLoop.paused) {
5100 Browser.mainLoop.paused = false;
5101 Browser.mainLoop.scheduler();
5102 }
5103 Browser.mainLoop.shouldPause = false;
5104 },updateStatus:function () {
5105 if (Module['setStatus']) {
5106 var message = Module['statusMessage'] || 'Please wait...';
5107 var remaining = Browser.mainLoop.remainingBlockers;
5108 var expected = Browser.mainLoop.expectedBlockers;
5109 if (remaining) {
5110 if (remaining < expected) {
5111 Module['setStatus'](message + ' (' + (expected - remaining) + '/ ' + expected + ')');
5112 } else {
5113 Module['setStatus'](message);
5114 }
5115 } else {
5116 Module['setStatus']('');
5117 }
5118 }
5119 }},isFullScreen:false,pointerLock:false,moduleContextCreatedCallbacks:[] ,workers:[],init:function () {
5120 if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs t o exist even in workers
5121
5122 if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
5123 Browser.initted = true;
5124
5125 try {
5126 new Blob();
5127 Browser.hasBlobConstructor = true;
5128 } catch(e) {
5129 Browser.hasBlobConstructor = false;
5130 console.log("warning: no blob constructor, cannot create blobs with mi metypes");
5131 }
5132 Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuil der : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.h asBlobConstructor ? console.log("warning: no BlobBuilder") : null));
5133 Browser.URLObject = typeof window != "undefined" ? (window.URL ? window. URL : window.webkitURL) : undefined;
5134 if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
5135 console.log("warning: Browser does not support creating object URLs. B uilt-in browser image decoding will not be available.");
5136 Module.noImageDecoding = true;
5137 }
5138
5139 // Support for plugins that can process preloaded files. You can add mor e of these to
5140 // your app by creating and appending to Module.preloadPlugins.
5141 //
5142 // Each plugin is asked if it can handle a file based on the file's name . If it can,
5143 // it is given the file's raw data. When it is done, it calls a callback with the file's
5144 // (possibly modified) data. For example, a plugin might decompress a fi le, or it
5145 // might create some side data structure for use later (like an Image el ement, etc.).
5146
5147 var imagePlugin = {};
5148 imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
5149 return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
5150 };
5151 imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onl oad, onerror) {
5152 var b = null;
5153 if (Browser.hasBlobConstructor) {
5154 try {
5155 b = new Blob([byteArray], { type: Browser.getMimetype(name) });
5156 if (b.size !== byteArray.length) { // Safari bug #118630
5157 // Safari's Blob can only take an ArrayBuffer
5158 b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Brows er.getMimetype(name) });
5159 }
5160 } catch(e) {
5161 Runtime.warnOnce('Blob constructor present but fails: ' + e + '; f alling back to blob builder');
5162 }
5163 }
5164 if (!b) {
5165 var bb = new Browser.BlobBuilder();
5166 bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
5167 b = bb.getBlob();
5168 }
5169 var url = Browser.URLObject.createObjectURL(b);
5170 var img = new Image();
5171 img.onload = function img_onload() {
5172 assert(img.complete, 'Image ' + name + ' could not be decoded');
5173 var canvas = document.createElement('canvas');
5174 canvas.width = img.width;
5175 canvas.height = img.height;
5176 var ctx = canvas.getContext('2d');
5177 ctx.drawImage(img, 0, 0);
5178 Module["preloadedImages"][name] = canvas;
5179 Browser.URLObject.revokeObjectURL(url);
5180 if (onload) onload(byteArray);
5181 };
5182 img.onerror = function img_onerror(event) {
5183 console.log('Image ' + url + ' could not be decoded');
5184 if (onerror) onerror();
5185 };
5186 img.src = url;
5187 };
5188 Module['preloadPlugins'].push(imagePlugin);
5189
5190 var audioPlugin = {};
5191 audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
5192 return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wa v': 1, '.mp3': 1 };
5193 };
5194 audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onl oad, onerror) {
5195 var done = false;
5196 function finish(audio) {
5197 if (done) return;
5198 done = true;
5199 Module["preloadedAudios"][name] = audio;
5200 if (onload) onload(byteArray);
5201 }
5202 function fail() {
5203 if (done) return;
5204 done = true;
5205 Module["preloadedAudios"][name] = new Audio(); // empty shim
5206 if (onerror) onerror();
5207 }
5208 if (Browser.hasBlobConstructor) {
5209 try {
5210 var b = new Blob([byteArray], { type: Browser.getMimetype(name) }) ;
5211 } catch(e) {
5212 return fail();
5213 }
5214 var url = Browser.URLObject.createObjectURL(b); // XXX we never revo ke this!
5215 var audio = new Audio();
5216 audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
5217 audio.onerror = function audio_onerror(event) {
5218 if (done) return;
5219 console.log('warning: browser could not fully decode audio ' + nam e + ', trying slower base64 approach');
5220 function encode64(data) {
5221 var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789+/';
5222 var PAD = '=';
5223 var ret = '';
5224 var leftchar = 0;
5225 var leftbits = 0;
5226 for (var i = 0; i < data.length; i++) {
5227 leftchar = (leftchar << 8) | data[i];
5228 leftbits += 8;
5229 while (leftbits >= 6) {
5230 var curr = (leftchar >> (leftbits-6)) & 0x3f;
5231 leftbits -= 6;
5232 ret += BASE[curr];
5233 }
5234 }
5235 if (leftbits == 2) {
5236 ret += BASE[(leftchar&3) << 4];
5237 ret += PAD + PAD;
5238 } else if (leftbits == 4) {
5239 ret += BASE[(leftchar&0xf) << 2];
5240 ret += PAD;
5241 }
5242 return ret;
5243 }
5244 audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encod e64(byteArray);
5245 finish(audio); // we don't wait for confirmation this worked - but it's worth trying
5246 };
5247 audio.src = url;
5248 // workaround for chrome bug 124926 - we do not always get oncanplay through or onerror
5249 Browser.safeSetTimeout(function() {
5250 finish(audio); // try to use it even though it is not necessarily ready to play
5251 }, 10000);
5252 } else {
5253 return fail();
5254 }
5255 };
5256 Module['preloadPlugins'].push(audioPlugin);
5257
5258 // Canvas event setup
5259
5260 var canvas = Module['canvas'];
5261
5262 // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
5263 // Module['forcedAspectRatio'] = 4 / 3;
5264
5265 canvas.requestPointerLock = canvas['requestPointerLock'] ||
5266 canvas['mozRequestPointerLock'] ||
5267 canvas['webkitRequestPointerLock'] ||
5268 canvas['msRequestPointerLock'] ||
5269 function(){};
5270 canvas.exitPointerLock = document['exitPointerLock'] ||
5271 document['mozExitPointerLock'] ||
5272 document['webkitExitPointerLock'] ||
5273 document['msExitPointerLock'] ||
5274 function(){}; // no-op if function does not exi st
5275 canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
5276
5277 function pointerLockChange() {
5278 Browser.pointerLock = document['pointerLockElement'] === canvas ||
5279 document['mozPointerLockElement'] === canvas ||
5280 document['webkitPointerLockElement'] === canvas ||
5281 document['msPointerLockElement'] === canvas;
5282 }
5283
5284 document.addEventListener('pointerlockchange', pointerLockChange, false) ;
5285 document.addEventListener('mozpointerlockchange', pointerLockChange, fal se);
5286 document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
5287 document.addEventListener('mspointerlockchange', pointerLockChange, fals e);
5288
5289 if (Module['elementPointerLock']) {
5290 canvas.addEventListener("click", function(ev) {
5291 if (!Browser.pointerLock && canvas.requestPointerLock) {
5292 canvas.requestPointerLock();
5293 ev.preventDefault();
5294 }
5295 }, false);
5296 }
5297 },createContext:function (canvas, useWebGL, setInModule, webGLContextAttri butes) {
5298 var ctx;
5299 var errorInfo = '?';
5300 function onContextCreationError(event) {
5301 errorInfo = event.statusMessage || errorInfo;
5302 }
5303 try {
5304 if (useWebGL) {
5305 var contextAttributes = {
5306 antialias: false,
5307 alpha: false
5308 };
5309
5310 if (webGLContextAttributes) {
5311 for (var attribute in webGLContextAttributes) {
5312 contextAttributes[attribute] = webGLContextAttributes[attribute] ;
5313 }
5314 }
5315
5316
5317 canvas.addEventListener('webglcontextcreationerror', onContextCreati onError, false);
5318 try {
5319 ['experimental-webgl', 'webgl'].some(function(webglId) {
5320 return ctx = canvas.getContext(webglId, contextAttributes);
5321 });
5322 } finally {
5323 canvas.removeEventListener('webglcontextcreationerror', onContextC reationError, false);
5324 }
5325 } else {
5326 ctx = canvas.getContext('2d');
5327 }
5328 if (!ctx) throw ':(';
5329 } catch (e) {
5330 Module.print('Could not create canvas: ' + [errorInfo, e]);
5331 return null;
5332 }
5333 if (useWebGL) {
5334 // Set the background of the WebGL canvas to black
5335 canvas.style.backgroundColor = "black";
5336
5337 // Warn on context loss
5338 canvas.addEventListener('webglcontextlost', function(event) {
5339 alert('WebGL context lost. You will need to reload the page.');
5340 }, false);
5341 }
5342 if (setInModule) {
5343 GLctx = Module.ctx = ctx;
5344 Module.useWebGL = useWebGL;
5345 Browser.moduleContextCreatedCallbacks.forEach(function(callback) { cal lback() });
5346 Browser.init();
5347 }
5348 return ctx;
5349 },destroyContext:function (canvas, useWebGL, setInModule) {},fullScreenHan dlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullScr een:function (lockPointer, resizeCanvas) {
5350 Browser.lockPointer = lockPointer;
5351 Browser.resizeCanvas = resizeCanvas;
5352 if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = tr ue;
5353 if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
5354
5355 var canvas = Module['canvas'];
5356 function fullScreenChange() {
5357 Browser.isFullScreen = false;
5358 var canvasContainer = canvas.parentNode;
5359 if ((document['webkitFullScreenElement'] || document['webkitFullscreen Element'] ||
5360 document['mozFullScreenElement'] || document['mozFullscreenElemen t'] ||
5361 document['fullScreenElement'] || document['fullscreenElement'] ||
5362 document['msFullScreenElement'] || document['msFullscreenElement' ] ||
5363 document['webkitCurrentFullScreenElement']) === canvasContainer) {
5364 canvas.cancelFullScreen = document['cancelFullScreen'] ||
5365 document['mozCancelFullScreen'] ||
5366 document['webkitCancelFullScreen'] ||
5367 document['msExitFullscreen'] ||
5368 document['exitFullscreen'] ||
5369 function() {};
5370 canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
5371 if (Browser.lockPointer) canvas.requestPointerLock();
5372 Browser.isFullScreen = true;
5373 if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
5374 } else {
5375
5376 // remove the full screen specific parent of the canvas again to res tore the HTML structure from before going full screen
5377 canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
5378 canvasContainer.parentNode.removeChild(canvasContainer);
5379
5380 if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
5381 }
5382 if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScree n);
5383 Browser.updateCanvasDimensions(canvas);
5384 }
5385
5386 if (!Browser.fullScreenHandlersInstalled) {
5387 Browser.fullScreenHandlersInstalled = true;
5388 document.addEventListener('fullscreenchange', fullScreenChange, false) ;
5389 document.addEventListener('mozfullscreenchange', fullScreenChange, fal se);
5390 document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
5391 document.addEventListener('MSFullscreenChange', fullScreenChange, fals e);
5392 }
5393
5394 // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root
5395 var canvasContainer = document.createElement("div");
5396 canvas.parentNode.insertBefore(canvasContainer, canvas);
5397 canvasContainer.appendChild(canvas);
5398
5399 // use parent of canvas as full screen root to allow aspect ratio correc tion (Firefox stretches the root to screen size)
5400 canvasContainer.requestFullScreen = canvasContainer['requestFullScreen'] ||
5401 canvasContainer['mozRequestFullScree n'] ||
5402 canvasContainer['msRequestFullscreen '] ||
5403 (canvasContainer['webkitRequestFullSc reen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_ KEYBOARD_INPUT']) } : null);
5404 canvasContainer.requestFullScreen();
5405 },requestAnimationFrame:function requestAnimationFrame(func) {
5406 if (typeof window === 'undefined') { // Provide fallback to setTimeout i f window is undefined (e.g. in Node.js)
5407 setTimeout(func, 1000/60);
5408 } else {
5409 if (!window.requestAnimationFrame) {
5410 window.requestAnimationFrame = window['requestAnimationFrame'] ||
5411 window['mozRequestAnimationFrame'] ||
5412 window['webkitRequestAnimationFrame'] ||
5413 window['msRequestAnimationFrame'] ||
5414 window['oRequestAnimationFrame'] ||
5415 window['setTimeout'];
5416 }
5417 window.requestAnimationFrame(func);
5418 }
5419 },safeCallback:function (func) {
5420 return function() {
5421 if (!ABORT) return func.apply(null, arguments);
5422 };
5423 },safeRequestAnimationFrame:function (func) {
5424 return Browser.requestAnimationFrame(function() {
5425 if (!ABORT) func();
5426 });
5427 },safeSetTimeout:function (func, timeout) {
5428 return setTimeout(function() {
5429 if (!ABORT) func();
5430 }, timeout);
5431 },safeSetInterval:function (func, timeout) {
5432 return setInterval(function() {
5433 if (!ABORT) func();
5434 }, timeout);
5435 },getMimetype:function (name) {
5436 return {
5437 'jpg': 'image/jpeg',
5438 'jpeg': 'image/jpeg',
5439 'png': 'image/png',
5440 'bmp': 'image/bmp',
5441 'ogg': 'audio/ogg',
5442 'wav': 'audio/wav',
5443 'mp3': 'audio/mpeg'
5444 }[name.substr(name.lastIndexOf('.')+1)];
5445 },getUserMedia:function (func) {
5446 if(!window.getUserMedia) {
5447 window.getUserMedia = navigator['getUserMedia'] ||
5448 navigator['mozGetUserMedia'];
5449 }
5450 window.getUserMedia(func);
5451 },getMovementX:function (event) {
5452 return event['movementX'] ||
5453 event['mozMovementX'] ||
5454 event['webkitMovementX'] ||
5455 0;
5456 },getMovementY:function (event) {
5457 return event['movementY'] ||
5458 event['mozMovementY'] ||
5459 event['webkitMovementY'] ||
5460 0;
5461 },getMouseWheelDelta:function (event) {
5462 return Math.max(-1, Math.min(1, event.type === 'DOMMouseScroll' ? event. detail : -event.wheelDelta));
5463 },mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,calculateMouseEvent: function (event) { // event should be mousemove, mousedown or mouseup
5464 if (Browser.pointerLock) {
5465 // When the pointer is locked, calculate the coordinates
5466 // based on the movement of the mouse.
5467 // Workaround for Firefox bug 764498
5468 if (event.type != 'mousemove' &&
5469 ('mozMovementX' in event)) {
5470 Browser.mouseMovementX = Browser.mouseMovementY = 0;
5471 } else {
5472 Browser.mouseMovementX = Browser.getMovementX(event);
5473 Browser.mouseMovementY = Browser.getMovementY(event);
5474 }
5475
5476 // check if SDL is available
5477 if (typeof SDL != "undefined") {
5478 Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
5479 Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
5480 } else {
5481 // just add the mouse delta to the current absolut mouse position
5482 // FIXME: ideally this should be clamped against the canvas size and zero
5483 Browser.mouseX += Browser.mouseMovementX;
5484 Browser.mouseY += Browser.mouseMovementY;
5485 }
5486 } else {
5487 // Otherwise, calculate the movement based on the changes
5488 // in the coordinates.
5489 var rect = Module["canvas"].getBoundingClientRect();
5490 var x, y;
5491
5492 // Neither .scrollX or .pageXOffset are defined in a spec, but
5493 // we prefer .scrollX because it is currently in a spec draft.
5494 // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
5495 var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scroll X : window.pageXOffset);
5496 var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scroll Y : window.pageYOffset);
5497 if (event.type == 'touchstart' ||
5498 event.type == 'touchend' ||
5499 event.type == 'touchmove') {
5500 var t = event.touches.item(0);
5501 if (t) {
5502 x = t.pageX - (scrollX + rect.left);
5503 y = t.pageY - (scrollY + rect.top);
5504 } else {
5505 return;
5506 }
5507 } else {
5508 x = event.pageX - (scrollX + rect.left);
5509 y = event.pageY - (scrollY + rect.top);
5510 }
5511
5512 // the canvas might be CSS-scaled compared to its backbuffer;
5513 // SDL-using content will want mouse coordinates in terms
5514 // of backbuffer units.
5515 var cw = Module["canvas"].width;
5516 var ch = Module["canvas"].height;
5517 x = x * (cw / rect.width);
5518 y = y * (ch / rect.height);
5519
5520 Browser.mouseMovementX = x - Browser.mouseX;
5521 Browser.mouseMovementY = y - Browser.mouseY;
5522 Browser.mouseX = x;
5523 Browser.mouseY = y;
5524 }
5525 },xhrLoad:function (url, onload, onerror) {
5526 var xhr = new XMLHttpRequest();
5527 xhr.open('GET', url, true);
5528 xhr.responseType = 'arraybuffer';
5529 xhr.onload = function xhr_onload() {
5530 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
5531 onload(xhr.response);
5532 } else {
5533 onerror();
5534 }
5535 };
5536 xhr.onerror = onerror;
5537 xhr.send(null);
5538 },asyncLoad:function (url, onload, onerror, noRunDep) {
5539 Browser.xhrLoad(url, function(arrayBuffer) {
5540 assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayB uffer).');
5541 onload(new Uint8Array(arrayBuffer));
5542 if (!noRunDep) removeRunDependency('al ' + url);
5543 }, function(event) {
5544 if (onerror) {
5545 onerror();
5546 } else {
5547 throw 'Loading data file "' + url + '" failed.';
5548 }
5549 });
5550 if (!noRunDep) addRunDependency('al ' + url);
5551 },resizeListeners:[],updateResizeListeners:function () {
5552 var canvas = Module['canvas'];
5553 Browser.resizeListeners.forEach(function(listener) {
5554 listener(canvas.width, canvas.height);
5555 });
5556 },setCanvasSize:function (width, height, noUpdates) {
5557 var canvas = Module['canvas'];
5558 Browser.updateCanvasDimensions(canvas, width, height);
5559 if (!noUpdates) Browser.updateResizeListeners();
5560 },windowedWidth:0,windowedHeight:0,setFullScreenCanvasSize:function () {
5561 // check if SDL is available
5562 if (typeof SDL != "undefined") {
5563 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
5564 flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
5565 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
5566 }
5567 Browser.updateResizeListeners();
5568 },setWindowedCanvasSize:function () {
5569 // check if SDL is available
5570 if (typeof SDL != "undefined") {
5571 var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
5572 flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
5573 HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
5574 }
5575 Browser.updateResizeListeners();
5576 },updateCanvasDimensions:function (canvas, wNative, hNative) {
5577 if (wNative && hNative) {
5578 canvas.widthNative = wNative;
5579 canvas.heightNative = hNative;
5580 } else {
5581 wNative = canvas.widthNative;
5582 hNative = canvas.heightNative;
5583 }
5584 var w = wNative;
5585 var h = hNative;
5586 if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
5587 if (w/h < Module['forcedAspectRatio']) {
5588 w = Math.round(h * Module['forcedAspectRatio']);
5589 } else {
5590 h = Math.round(w / Module['forcedAspectRatio']);
5591 }
5592 }
5593 if (((document['webkitFullScreenElement'] || document['webkitFullscreenE lement'] ||
5594 document['mozFullScreenElement'] || document['mozFullscreenElement' ] ||
5595 document['fullScreenElement'] || document['fullscreenElement'] ||
5596 document['msFullScreenElement'] || document['msFullscreenElement'] ||
5597 document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
5598 var factor = Math.min(screen.width / w, screen.height / h);
5599 w = Math.round(w * factor);
5600 h = Math.round(h * factor);
5601 }
5602 if (Browser.resizeCanvas) {
5603 if (canvas.width != w) canvas.width = w;
5604 if (canvas.height != h) canvas.height = h;
5605 if (typeof canvas.style != 'undefined') {
5606 canvas.style.removeProperty( "width");
5607 canvas.style.removeProperty("height");
5608 }
5609 } else {
5610 if (canvas.width != wNative) canvas.width = wNative;
5611 if (canvas.height != hNative) canvas.height = hNative;
5612 if (typeof canvas.style != 'undefined') {
5613 if (w != wNative || h != hNative) {
5614 canvas.style.setProperty( "width", w + "px", "important");
5615 canvas.style.setProperty("height", h + "px", "important");
5616 } else {
5617 canvas.style.removeProperty( "width");
5618 canvas.style.removeProperty("height");
5619 }
5620 }
5621 }
5622 }};
5623
5624 function _time(ptr) {
5625 var ret = Math.floor(Date.now()/1000);
5626 if (ptr) {
5627 HEAP32[((ptr)>>2)]=ret;
5628 }
5629 return ret;
5630 }
5631
5632
5633
5634 function _emscripten_memcpy_big(dest, src, num) {
5635 HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
5636 return dest;
5637 }
5638 Module["_memcpy"] = _memcpy;
5639 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.crea tePath;Module["FS_createDataFile"] = FS.createDataFile;Module["FS_createPreloade dFile"] = FS.createPreloadedFile;Module["FS_createLazyFile"] = FS.createLazyFile ;Module["FS_createLink"] = FS.createLink;Module["FS_createDevice"] = FS.createDe vice;
5640 ___errno_state = Runtime.staticAlloc(4); HEAP32[((___errno_state)>>2)]=0;
5641 __ATINIT__.unshift({ func: function() { TTY.init() } });__ATEXIT__.push({ func: function() { TTY.shutdown() } });TTY.utf8 = new Runtime.UTF8Processor();
5642 if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); NODEFS.staticInit(); }
5643 __ATINIT__.push({ func: function() { SOCKFS.root = FS.mount(SOCKFS, {}, null); } });
5644 _fputc.ret = allocate([0], "i8", ALLOC_STATIC);
5645 Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, res izeCanvas) { Browser.requestFullScreen(lockPointer, resizeCanvas) };
5646 Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
5647 Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdat es) { Browser.setCanvasSize(width, height, noUpdates) };
5648 Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.p ause() };
5649 Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop .resume() };
5650 Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia () }
5651 STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
5652
5653 staticSealed = true; // seal the static portion of memory
5654
5655 STACK_MAX = STACK_BASE + 5242880;
5656
5657 DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
5658
5659 assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
5660
5661
5662 var Math_min = Math.min;
5663 function asmPrintInt(x, y) {
5664 Module.print('int ' + x + ',' + y);// + ' ' + new Error().stack);
5665 }
5666 function asmPrintFloat(x, y) {
5667 Module.print('float ' + x + ',' + y);// + ' ' + new Error().stack);
5668 }
5669 // EMSCRIPTEN_START_ASM
5670 var asm = (function(global, env, buffer) {
5671 'use asm';
5672 var HEAP8 = new global.Int8Array(buffer);
5673 var HEAP16 = new global.Int16Array(buffer);
5674 var HEAP32 = new global.Int32Array(buffer);
5675 var HEAPU8 = new global.Uint8Array(buffer);
5676 var HEAPU16 = new global.Uint16Array(buffer);
5677 var HEAPU32 = new global.Uint32Array(buffer);
5678 var HEAPF32 = new global.Float32Array(buffer);
5679 var HEAPF64 = new global.Float64Array(buffer);
5680
5681 var STACKTOP=env.STACKTOP|0;
5682 var STACK_MAX=env.STACK_MAX|0;
5683 var tempDoublePtr=env.tempDoublePtr|0;
5684 var ABORT=env.ABORT|0;
5685
5686 var __THREW__ = 0;
5687 var threwValue = 0;
5688 var setjmpId = 0;
5689 var undef = 0;
5690 var nan = +env.NaN, inf = +env.Infinity;
5691 var tempInt = 0, tempBigInt = 0, tempBigIntP = 0, tempBigIntS = 0, tempBigIntR = 0.0, tempBigIntI = 0, tempBigIntD = 0, tempValue = 0, tempDouble = 0.0;
5692
5693 var tempRet0 = 0;
5694 var tempRet1 = 0;
5695 var tempRet2 = 0;
5696 var tempRet3 = 0;
5697 var tempRet4 = 0;
5698 var tempRet5 = 0;
5699 var tempRet6 = 0;
5700 var tempRet7 = 0;
5701 var tempRet8 = 0;
5702 var tempRet9 = 0;
5703 var Math_floor=global.Math.floor;
5704 var Math_abs=global.Math.abs;
5705 var Math_sqrt=global.Math.sqrt;
5706 var Math_pow=global.Math.pow;
5707 var Math_cos=global.Math.cos;
5708 var Math_sin=global.Math.sin;
5709 var Math_tan=global.Math.tan;
5710 var Math_acos=global.Math.acos;
5711 var Math_asin=global.Math.asin;
5712 var Math_atan=global.Math.atan;
5713 var Math_atan2=global.Math.atan2;
5714 var Math_exp=global.Math.exp;
5715 var Math_log=global.Math.log;
5716 var Math_ceil=global.Math.ceil;
5717 var Math_imul=global.Math.imul;
5718 var abort=env.abort;
5719 var assert=env.assert;
5720 var asmPrintInt=env.asmPrintInt;
5721 var asmPrintFloat=env.asmPrintFloat;
5722 var Math_min=env.min;
5723 var _fflush=env._fflush;
5724 var _emscripten_memcpy_big=env._emscripten_memcpy_big;
5725 var _putchar=env._putchar;
5726 var _fputc=env._fputc;
5727 var _send=env._send;
5728 var _pwrite=env._pwrite;
5729 var _abort=env._abort;
5730 var __reallyNegative=env.__reallyNegative;
5731 var _fwrite=env._fwrite;
5732 var _sbrk=env._sbrk;
5733 var _mkport=env._mkport;
5734 var _fprintf=env._fprintf;
5735 var ___setErrNo=env.___setErrNo;
5736 var __formatString=env.__formatString;
5737 var _fileno=env._fileno;
5738 var _printf=env._printf;
5739 var _time=env._time;
5740 var _sysconf=env._sysconf;
5741 var _write=env._write;
5742 var ___errno_location=env.___errno_location;
5743 var tempFloat = 0.0;
5744
5745 // EMSCRIPTEN_START_FUNCS
5746 function _malloc(i12) {
5747 i12 = i12 | 0;
5748 var i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0, i10 = 0, i11 = 0, i13 = 0, i14 = 0, i15 = 0, i16 = 0, i17 = 0, i18 = 0, i19 = 0, i2 0 = 0, i21 = 0, i22 = 0, i23 = 0, i24 = 0, i25 = 0, i26 = 0, i27 = 0, i28 = 0, i 29 = 0, i30 = 0, i31 = 0, i32 = 0;
5749 i1 = STACKTOP;
5750 do {
5751 if (i12 >>> 0 < 245) {
5752 if (i12 >>> 0 < 11) {
5753 i12 = 16;
5754 } else {
5755 i12 = i12 + 11 & -8;
5756 }
5757 i20 = i12 >>> 3;
5758 i18 = HEAP32[14] | 0;
5759 i21 = i18 >>> i20;
5760 if ((i21 & 3 | 0) != 0) {
5761 i6 = (i21 & 1 ^ 1) + i20 | 0;
5762 i5 = i6 << 1;
5763 i3 = 96 + (i5 << 2) | 0;
5764 i5 = 96 + (i5 + 2 << 2) | 0;
5765 i7 = HEAP32[i5 >> 2] | 0;
5766 i2 = i7 + 8 | 0;
5767 i4 = HEAP32[i2 >> 2] | 0;
5768 do {
5769 if ((i3 | 0) != (i4 | 0)) {
5770 if (i4 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5771 _abort();
5772 }
5773 i8 = i4 + 12 | 0;
5774 if ((HEAP32[i8 >> 2] | 0) == (i7 | 0)) {
5775 HEAP32[i8 >> 2] = i3;
5776 HEAP32[i5 >> 2] = i4;
5777 break;
5778 } else {
5779 _abort();
5780 }
5781 } else {
5782 HEAP32[14] = i18 & ~(1 << i6);
5783 }
5784 } while (0);
5785 i32 = i6 << 3;
5786 HEAP32[i7 + 4 >> 2] = i32 | 3;
5787 i32 = i7 + (i32 | 4) | 0;
5788 HEAP32[i32 >> 2] = HEAP32[i32 >> 2] | 1;
5789 i32 = i2;
5790 STACKTOP = i1;
5791 return i32 | 0;
5792 }
5793 if (i12 >>> 0 > (HEAP32[64 >> 2] | 0) >>> 0) {
5794 if ((i21 | 0) != 0) {
5795 i7 = 2 << i20;
5796 i7 = i21 << i20 & (i7 | 0 - i7);
5797 i7 = (i7 & 0 - i7) + -1 | 0;
5798 i2 = i7 >>> 12 & 16;
5799 i7 = i7 >>> i2;
5800 i6 = i7 >>> 5 & 8;
5801 i7 = i7 >>> i6;
5802 i5 = i7 >>> 2 & 4;
5803 i7 = i7 >>> i5;
5804 i4 = i7 >>> 1 & 2;
5805 i7 = i7 >>> i4;
5806 i3 = i7 >>> 1 & 1;
5807 i3 = (i6 | i2 | i5 | i4 | i3) + (i7 >>> i3) | 0;
5808 i7 = i3 << 1;
5809 i4 = 96 + (i7 << 2) | 0;
5810 i7 = 96 + (i7 + 2 << 2) | 0;
5811 i5 = HEAP32[i7 >> 2] | 0;
5812 i2 = i5 + 8 | 0;
5813 i6 = HEAP32[i2 >> 2] | 0;
5814 do {
5815 if ((i4 | 0) != (i6 | 0)) {
5816 if (i6 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5817 _abort();
5818 }
5819 i8 = i6 + 12 | 0;
5820 if ((HEAP32[i8 >> 2] | 0) == (i5 | 0)) {
5821 HEAP32[i8 >> 2] = i4;
5822 HEAP32[i7 >> 2] = i6;
5823 break;
5824 } else {
5825 _abort();
5826 }
5827 } else {
5828 HEAP32[14] = i18 & ~(1 << i3);
5829 }
5830 } while (0);
5831 i6 = i3 << 3;
5832 i4 = i6 - i12 | 0;
5833 HEAP32[i5 + 4 >> 2] = i12 | 3;
5834 i3 = i5 + i12 | 0;
5835 HEAP32[i5 + (i12 | 4) >> 2] = i4 | 1;
5836 HEAP32[i5 + i6 >> 2] = i4;
5837 i6 = HEAP32[64 >> 2] | 0;
5838 if ((i6 | 0) != 0) {
5839 i5 = HEAP32[76 >> 2] | 0;
5840 i8 = i6 >>> 3;
5841 i9 = i8 << 1;
5842 i6 = 96 + (i9 << 2) | 0;
5843 i7 = HEAP32[14] | 0;
5844 i8 = 1 << i8;
5845 if ((i7 & i8 | 0) != 0) {
5846 i7 = 96 + (i9 + 2 << 2) | 0;
5847 i8 = HEAP32[i7 >> 2] | 0;
5848 if (i8 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5849 _abort();
5850 } else {
5851 i28 = i7;
5852 i27 = i8;
5853 }
5854 } else {
5855 HEAP32[14] = i7 | i8;
5856 i28 = 96 + (i9 + 2 << 2) | 0;
5857 i27 = i6;
5858 }
5859 HEAP32[i28 >> 2] = i5;
5860 HEAP32[i27 + 12 >> 2] = i5;
5861 HEAP32[i5 + 8 >> 2] = i27;
5862 HEAP32[i5 + 12 >> 2] = i6;
5863 }
5864 HEAP32[64 >> 2] = i4;
5865 HEAP32[76 >> 2] = i3;
5866 i32 = i2;
5867 STACKTOP = i1;
5868 return i32 | 0;
5869 }
5870 i18 = HEAP32[60 >> 2] | 0;
5871 if ((i18 | 0) != 0) {
5872 i2 = (i18 & 0 - i18) + -1 | 0;
5873 i31 = i2 >>> 12 & 16;
5874 i2 = i2 >>> i31;
5875 i30 = i2 >>> 5 & 8;
5876 i2 = i2 >>> i30;
5877 i32 = i2 >>> 2 & 4;
5878 i2 = i2 >>> i32;
5879 i6 = i2 >>> 1 & 2;
5880 i2 = i2 >>> i6;
5881 i3 = i2 >>> 1 & 1;
5882 i3 = HEAP32[360 + ((i30 | i31 | i32 | i6 | i3) + (i2 >>> i3) << 2) >> 2] | 0;
5883 i2 = (HEAP32[i3 + 4 >> 2] & -8) - i12 | 0;
5884 i6 = i3;
5885 while (1) {
5886 i5 = HEAP32[i6 + 16 >> 2] | 0;
5887 if ((i5 | 0) == 0) {
5888 i5 = HEAP32[i6 + 20 >> 2] | 0;
5889 if ((i5 | 0) == 0) {
5890 break;
5891 }
5892 }
5893 i6 = (HEAP32[i5 + 4 >> 2] & -8) - i12 | 0;
5894 i4 = i6 >>> 0 < i2 >>> 0;
5895 i2 = i4 ? i6 : i2;
5896 i6 = i5;
5897 i3 = i4 ? i5 : i3;
5898 }
5899 i6 = HEAP32[72 >> 2] | 0;
5900 if (i3 >>> 0 < i6 >>> 0) {
5901 _abort();
5902 }
5903 i4 = i3 + i12 | 0;
5904 if (!(i3 >>> 0 < i4 >>> 0)) {
5905 _abort();
5906 }
5907 i5 = HEAP32[i3 + 24 >> 2] | 0;
5908 i7 = HEAP32[i3 + 12 >> 2] | 0;
5909 do {
5910 if ((i7 | 0) == (i3 | 0)) {
5911 i8 = i3 + 20 | 0;
5912 i7 = HEAP32[i8 >> 2] | 0;
5913 if ((i7 | 0) == 0) {
5914 i8 = i3 + 16 | 0;
5915 i7 = HEAP32[i8 >> 2] | 0;
5916 if ((i7 | 0) == 0) {
5917 i26 = 0;
5918 break;
5919 }
5920 }
5921 while (1) {
5922 i10 = i7 + 20 | 0;
5923 i9 = HEAP32[i10 >> 2] | 0;
5924 if ((i9 | 0) != 0) {
5925 i7 = i9;
5926 i8 = i10;
5927 continue;
5928 }
5929 i10 = i7 + 16 | 0;
5930 i9 = HEAP32[i10 >> 2] | 0;
5931 if ((i9 | 0) == 0) {
5932 break;
5933 } else {
5934 i7 = i9;
5935 i8 = i10;
5936 }
5937 }
5938 if (i8 >>> 0 < i6 >>> 0) {
5939 _abort();
5940 } else {
5941 HEAP32[i8 >> 2] = 0;
5942 i26 = i7;
5943 break;
5944 }
5945 } else {
5946 i8 = HEAP32[i3 + 8 >> 2] | 0;
5947 if (i8 >>> 0 < i6 >>> 0) {
5948 _abort();
5949 }
5950 i6 = i8 + 12 | 0;
5951 if ((HEAP32[i6 >> 2] | 0) != (i3 | 0)) {
5952 _abort();
5953 }
5954 i9 = i7 + 8 | 0;
5955 if ((HEAP32[i9 >> 2] | 0) == (i3 | 0)) {
5956 HEAP32[i6 >> 2] = i7;
5957 HEAP32[i9 >> 2] = i8;
5958 i26 = i7;
5959 break;
5960 } else {
5961 _abort();
5962 }
5963 }
5964 } while (0);
5965 do {
5966 if ((i5 | 0) != 0) {
5967 i7 = HEAP32[i3 + 28 >> 2] | 0;
5968 i6 = 360 + (i7 << 2) | 0;
5969 if ((i3 | 0) == (HEAP32[i6 >> 2] | 0)) {
5970 HEAP32[i6 >> 2] = i26;
5971 if ((i26 | 0) == 0) {
5972 HEAP32[60 >> 2] = HEAP32[60 >> 2] & ~(1 << i7);
5973 break;
5974 }
5975 } else {
5976 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5977 _abort();
5978 }
5979 i6 = i5 + 16 | 0;
5980 if ((HEAP32[i6 >> 2] | 0) == (i3 | 0)) {
5981 HEAP32[i6 >> 2] = i26;
5982 } else {
5983 HEAP32[i5 + 20 >> 2] = i26;
5984 }
5985 if ((i26 | 0) == 0) {
5986 break;
5987 }
5988 }
5989 if (i26 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5990 _abort();
5991 }
5992 HEAP32[i26 + 24 >> 2] = i5;
5993 i5 = HEAP32[i3 + 16 >> 2] | 0;
5994 do {
5995 if ((i5 | 0) != 0) {
5996 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
5997 _abort();
5998 } else {
5999 HEAP32[i26 + 16 >> 2] = i5;
6000 HEAP32[i5 + 24 >> 2] = i26;
6001 break;
6002 }
6003 }
6004 } while (0);
6005 i5 = HEAP32[i3 + 20 >> 2] | 0;
6006 if ((i5 | 0) != 0) {
6007 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6008 _abort();
6009 } else {
6010 HEAP32[i26 + 20 >> 2] = i5;
6011 HEAP32[i5 + 24 >> 2] = i26;
6012 break;
6013 }
6014 }
6015 }
6016 } while (0);
6017 if (i2 >>> 0 < 16) {
6018 i32 = i2 + i12 | 0;
6019 HEAP32[i3 + 4 >> 2] = i32 | 3;
6020 i32 = i3 + (i32 + 4) | 0;
6021 HEAP32[i32 >> 2] = HEAP32[i32 >> 2] | 1;
6022 } else {
6023 HEAP32[i3 + 4 >> 2] = i12 | 3;
6024 HEAP32[i3 + (i12 | 4) >> 2] = i2 | 1;
6025 HEAP32[i3 + (i2 + i12) >> 2] = i2;
6026 i6 = HEAP32[64 >> 2] | 0;
6027 if ((i6 | 0) != 0) {
6028 i5 = HEAP32[76 >> 2] | 0;
6029 i8 = i6 >>> 3;
6030 i9 = i8 << 1;
6031 i6 = 96 + (i9 << 2) | 0;
6032 i7 = HEAP32[14] | 0;
6033 i8 = 1 << i8;
6034 if ((i7 & i8 | 0) != 0) {
6035 i7 = 96 + (i9 + 2 << 2) | 0;
6036 i8 = HEAP32[i7 >> 2] | 0;
6037 if (i8 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6038 _abort();
6039 } else {
6040 i25 = i7;
6041 i24 = i8;
6042 }
6043 } else {
6044 HEAP32[14] = i7 | i8;
6045 i25 = 96 + (i9 + 2 << 2) | 0;
6046 i24 = i6;
6047 }
6048 HEAP32[i25 >> 2] = i5;
6049 HEAP32[i24 + 12 >> 2] = i5;
6050 HEAP32[i5 + 8 >> 2] = i24;
6051 HEAP32[i5 + 12 >> 2] = i6;
6052 }
6053 HEAP32[64 >> 2] = i2;
6054 HEAP32[76 >> 2] = i4;
6055 }
6056 i32 = i3 + 8 | 0;
6057 STACKTOP = i1;
6058 return i32 | 0;
6059 }
6060 }
6061 } else {
6062 if (!(i12 >>> 0 > 4294967231)) {
6063 i24 = i12 + 11 | 0;
6064 i12 = i24 & -8;
6065 i26 = HEAP32[60 >> 2] | 0;
6066 if ((i26 | 0) != 0) {
6067 i25 = 0 - i12 | 0;
6068 i24 = i24 >>> 8;
6069 if ((i24 | 0) != 0) {
6070 if (i12 >>> 0 > 16777215) {
6071 i27 = 31;
6072 } else {
6073 i31 = (i24 + 1048320 | 0) >>> 16 & 8;
6074 i32 = i24 << i31;
6075 i30 = (i32 + 520192 | 0) >>> 16 & 4;
6076 i32 = i32 << i30;
6077 i27 = (i32 + 245760 | 0) >>> 16 & 2;
6078 i27 = 14 - (i30 | i31 | i27) + (i32 << i27 >>> 15) | 0;
6079 i27 = i12 >>> (i27 + 7 | 0) & 1 | i27 << 1;
6080 }
6081 } else {
6082 i27 = 0;
6083 }
6084 i30 = HEAP32[360 + (i27 << 2) >> 2] | 0;
6085 L126 : do {
6086 if ((i30 | 0) == 0) {
6087 i29 = 0;
6088 i24 = 0;
6089 } else {
6090 if ((i27 | 0) == 31) {
6091 i24 = 0;
6092 } else {
6093 i24 = 25 - (i27 >>> 1) | 0;
6094 }
6095 i29 = 0;
6096 i28 = i12 << i24;
6097 i24 = 0;
6098 while (1) {
6099 i32 = HEAP32[i30 + 4 >> 2] & -8;
6100 i31 = i32 - i12 | 0;
6101 if (i31 >>> 0 < i25 >>> 0) {
6102 if ((i32 | 0) == (i12 | 0)) {
6103 i25 = i31;
6104 i29 = i30;
6105 i24 = i30;
6106 break L126;
6107 } else {
6108 i25 = i31;
6109 i24 = i30;
6110 }
6111 }
6112 i31 = HEAP32[i30 + 20 >> 2] | 0;
6113 i30 = HEAP32[i30 + (i28 >>> 31 << 2) + 16 >> 2] | 0;
6114 i29 = (i31 | 0) == 0 | (i31 | 0) == (i30 | 0) ? i29 : i31;
6115 if ((i30 | 0) == 0) {
6116 break;
6117 } else {
6118 i28 = i28 << 1;
6119 }
6120 }
6121 }
6122 } while (0);
6123 if ((i29 | 0) == 0 & (i24 | 0) == 0) {
6124 i32 = 2 << i27;
6125 i26 = i26 & (i32 | 0 - i32);
6126 if ((i26 | 0) == 0) {
6127 break;
6128 }
6129 i32 = (i26 & 0 - i26) + -1 | 0;
6130 i28 = i32 >>> 12 & 16;
6131 i32 = i32 >>> i28;
6132 i27 = i32 >>> 5 & 8;
6133 i32 = i32 >>> i27;
6134 i30 = i32 >>> 2 & 4;
6135 i32 = i32 >>> i30;
6136 i31 = i32 >>> 1 & 2;
6137 i32 = i32 >>> i31;
6138 i29 = i32 >>> 1 & 1;
6139 i29 = HEAP32[360 + ((i27 | i28 | i30 | i31 | i29) + (i32 >>> i29) << 2) >> 2] | 0;
6140 }
6141 if ((i29 | 0) != 0) {
6142 while (1) {
6143 i27 = (HEAP32[i29 + 4 >> 2] & -8) - i12 | 0;
6144 i26 = i27 >>> 0 < i25 >>> 0;
6145 i25 = i26 ? i27 : i25;
6146 i24 = i26 ? i29 : i24;
6147 i26 = HEAP32[i29 + 16 >> 2] | 0;
6148 if ((i26 | 0) != 0) {
6149 i29 = i26;
6150 continue;
6151 }
6152 i29 = HEAP32[i29 + 20 >> 2] | 0;
6153 if ((i29 | 0) == 0) {
6154 break;
6155 }
6156 }
6157 }
6158 if ((i24 | 0) != 0 ? i25 >>> 0 < ((HEAP32[64 >> 2] | 0) - i12 | 0) >>> 0 : 0) {
6159 i4 = HEAP32[72 >> 2] | 0;
6160 if (i24 >>> 0 < i4 >>> 0) {
6161 _abort();
6162 }
6163 i2 = i24 + i12 | 0;
6164 if (!(i24 >>> 0 < i2 >>> 0)) {
6165 _abort();
6166 }
6167 i3 = HEAP32[i24 + 24 >> 2] | 0;
6168 i6 = HEAP32[i24 + 12 >> 2] | 0;
6169 do {
6170 if ((i6 | 0) == (i24 | 0)) {
6171 i6 = i24 + 20 | 0;
6172 i5 = HEAP32[i6 >> 2] | 0;
6173 if ((i5 | 0) == 0) {
6174 i6 = i24 + 16 | 0;
6175 i5 = HEAP32[i6 >> 2] | 0;
6176 if ((i5 | 0) == 0) {
6177 i22 = 0;
6178 break;
6179 }
6180 }
6181 while (1) {
6182 i8 = i5 + 20 | 0;
6183 i7 = HEAP32[i8 >> 2] | 0;
6184 if ((i7 | 0) != 0) {
6185 i5 = i7;
6186 i6 = i8;
6187 continue;
6188 }
6189 i7 = i5 + 16 | 0;
6190 i8 = HEAP32[i7 >> 2] | 0;
6191 if ((i8 | 0) == 0) {
6192 break;
6193 } else {
6194 i5 = i8;
6195 i6 = i7;
6196 }
6197 }
6198 if (i6 >>> 0 < i4 >>> 0) {
6199 _abort();
6200 } else {
6201 HEAP32[i6 >> 2] = 0;
6202 i22 = i5;
6203 break;
6204 }
6205 } else {
6206 i5 = HEAP32[i24 + 8 >> 2] | 0;
6207 if (i5 >>> 0 < i4 >>> 0) {
6208 _abort();
6209 }
6210 i7 = i5 + 12 | 0;
6211 if ((HEAP32[i7 >> 2] | 0) != (i24 | 0)) {
6212 _abort();
6213 }
6214 i4 = i6 + 8 | 0;
6215 if ((HEAP32[i4 >> 2] | 0) == (i24 | 0)) {
6216 HEAP32[i7 >> 2] = i6;
6217 HEAP32[i4 >> 2] = i5;
6218 i22 = i6;
6219 break;
6220 } else {
6221 _abort();
6222 }
6223 }
6224 } while (0);
6225 do {
6226 if ((i3 | 0) != 0) {
6227 i4 = HEAP32[i24 + 28 >> 2] | 0;
6228 i5 = 360 + (i4 << 2) | 0;
6229 if ((i24 | 0) == (HEAP32[i5 >> 2] | 0)) {
6230 HEAP32[i5 >> 2] = i22;
6231 if ((i22 | 0) == 0) {
6232 HEAP32[60 >> 2] = HEAP32[60 >> 2] & ~(1 << i4);
6233 break;
6234 }
6235 } else {
6236 if (i3 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6237 _abort();
6238 }
6239 i4 = i3 + 16 | 0;
6240 if ((HEAP32[i4 >> 2] | 0) == (i24 | 0)) {
6241 HEAP32[i4 >> 2] = i22;
6242 } else {
6243 HEAP32[i3 + 20 >> 2] = i22;
6244 }
6245 if ((i22 | 0) == 0) {
6246 break;
6247 }
6248 }
6249 if (i22 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6250 _abort();
6251 }
6252 HEAP32[i22 + 24 >> 2] = i3;
6253 i3 = HEAP32[i24 + 16 >> 2] | 0;
6254 do {
6255 if ((i3 | 0) != 0) {
6256 if (i3 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6257 _abort();
6258 } else {
6259 HEAP32[i22 + 16 >> 2] = i3;
6260 HEAP32[i3 + 24 >> 2] = i22;
6261 break;
6262 }
6263 }
6264 } while (0);
6265 i3 = HEAP32[i24 + 20 >> 2] | 0;
6266 if ((i3 | 0) != 0) {
6267 if (i3 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6268 _abort();
6269 } else {
6270 HEAP32[i22 + 20 >> 2] = i3;
6271 HEAP32[i3 + 24 >> 2] = i22;
6272 break;
6273 }
6274 }
6275 }
6276 } while (0);
6277 L204 : do {
6278 if (!(i25 >>> 0 < 16)) {
6279 HEAP32[i24 + 4 >> 2] = i12 | 3;
6280 HEAP32[i24 + (i12 | 4) >> 2] = i25 | 1;
6281 HEAP32[i24 + (i25 + i12) >> 2] = i25;
6282 i4 = i25 >>> 3;
6283 if (i25 >>> 0 < 256) {
6284 i6 = i4 << 1;
6285 i3 = 96 + (i6 << 2) | 0;
6286 i5 = HEAP32[14] | 0;
6287 i4 = 1 << i4;
6288 if ((i5 & i4 | 0) != 0) {
6289 i5 = 96 + (i6 + 2 << 2) | 0;
6290 i4 = HEAP32[i5 >> 2] | 0;
6291 if (i4 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6292 _abort();
6293 } else {
6294 i21 = i5;
6295 i20 = i4;
6296 }
6297 } else {
6298 HEAP32[14] = i5 | i4;
6299 i21 = 96 + (i6 + 2 << 2) | 0;
6300 i20 = i3;
6301 }
6302 HEAP32[i21 >> 2] = i2;
6303 HEAP32[i20 + 12 >> 2] = i2;
6304 HEAP32[i24 + (i12 + 8) >> 2] = i20;
6305 HEAP32[i24 + (i12 + 12) >> 2] = i3;
6306 break;
6307 }
6308 i3 = i25 >>> 8;
6309 if ((i3 | 0) != 0) {
6310 if (i25 >>> 0 > 16777215) {
6311 i3 = 31;
6312 } else {
6313 i31 = (i3 + 1048320 | 0) >>> 16 & 8;
6314 i32 = i3 << i31;
6315 i30 = (i32 + 520192 | 0) >>> 16 & 4;
6316 i32 = i32 << i30;
6317 i3 = (i32 + 245760 | 0) >>> 16 & 2;
6318 i3 = 14 - (i30 | i31 | i3) + (i32 << i3 >>> 15) | 0;
6319 i3 = i25 >>> (i3 + 7 | 0) & 1 | i3 << 1;
6320 }
6321 } else {
6322 i3 = 0;
6323 }
6324 i6 = 360 + (i3 << 2) | 0;
6325 HEAP32[i24 + (i12 + 28) >> 2] = i3;
6326 HEAP32[i24 + (i12 + 20) >> 2] = 0;
6327 HEAP32[i24 + (i12 + 16) >> 2] = 0;
6328 i4 = HEAP32[60 >> 2] | 0;
6329 i5 = 1 << i3;
6330 if ((i4 & i5 | 0) == 0) {
6331 HEAP32[60 >> 2] = i4 | i5;
6332 HEAP32[i6 >> 2] = i2;
6333 HEAP32[i24 + (i12 + 24) >> 2] = i6;
6334 HEAP32[i24 + (i12 + 12) >> 2] = i2;
6335 HEAP32[i24 + (i12 + 8) >> 2] = i2;
6336 break;
6337 }
6338 i4 = HEAP32[i6 >> 2] | 0;
6339 if ((i3 | 0) == 31) {
6340 i3 = 0;
6341 } else {
6342 i3 = 25 - (i3 >>> 1) | 0;
6343 }
6344 L225 : do {
6345 if ((HEAP32[i4 + 4 >> 2] & -8 | 0) != (i25 | 0)) {
6346 i3 = i25 << i3;
6347 while (1) {
6348 i6 = i4 + (i3 >>> 31 << 2) + 16 | 0;
6349 i5 = HEAP32[i6 >> 2] | 0;
6350 if ((i5 | 0) == 0) {
6351 break;
6352 }
6353 if ((HEAP32[i5 + 4 >> 2] & -8 | 0) == (i25 | 0)) {
6354 i18 = i5;
6355 break L225;
6356 } else {
6357 i3 = i3 << 1;
6358 i4 = i5;
6359 }
6360 }
6361 if (i6 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6362 _abort();
6363 } else {
6364 HEAP32[i6 >> 2] = i2;
6365 HEAP32[i24 + (i12 + 24) >> 2] = i4;
6366 HEAP32[i24 + (i12 + 12) >> 2] = i2;
6367 HEAP32[i24 + (i12 + 8) >> 2] = i2;
6368 break L204;
6369 }
6370 } else {
6371 i18 = i4;
6372 }
6373 } while (0);
6374 i4 = i18 + 8 | 0;
6375 i3 = HEAP32[i4 >> 2] | 0;
6376 i5 = HEAP32[72 >> 2] | 0;
6377 if (i18 >>> 0 < i5 >>> 0) {
6378 _abort();
6379 }
6380 if (i3 >>> 0 < i5 >>> 0) {
6381 _abort();
6382 } else {
6383 HEAP32[i3 + 12 >> 2] = i2;
6384 HEAP32[i4 >> 2] = i2;
6385 HEAP32[i24 + (i12 + 8) >> 2] = i3;
6386 HEAP32[i24 + (i12 + 12) >> 2] = i18;
6387 HEAP32[i24 + (i12 + 24) >> 2] = 0;
6388 break;
6389 }
6390 } else {
6391 i32 = i25 + i12 | 0;
6392 HEAP32[i24 + 4 >> 2] = i32 | 3;
6393 i32 = i24 + (i32 + 4) | 0;
6394 HEAP32[i32 >> 2] = HEAP32[i32 >> 2] | 1;
6395 }
6396 } while (0);
6397 i32 = i24 + 8 | 0;
6398 STACKTOP = i1;
6399 return i32 | 0;
6400 }
6401 }
6402 } else {
6403 i12 = -1;
6404 }
6405 }
6406 } while (0);
6407 i18 = HEAP32[64 >> 2] | 0;
6408 if (!(i12 >>> 0 > i18 >>> 0)) {
6409 i3 = i18 - i12 | 0;
6410 i2 = HEAP32[76 >> 2] | 0;
6411 if (i3 >>> 0 > 15) {
6412 HEAP32[76 >> 2] = i2 + i12;
6413 HEAP32[64 >> 2] = i3;
6414 HEAP32[i2 + (i12 + 4) >> 2] = i3 | 1;
6415 HEAP32[i2 + i18 >> 2] = i3;
6416 HEAP32[i2 + 4 >> 2] = i12 | 3;
6417 } else {
6418 HEAP32[64 >> 2] = 0;
6419 HEAP32[76 >> 2] = 0;
6420 HEAP32[i2 + 4 >> 2] = i18 | 3;
6421 i32 = i2 + (i18 + 4) | 0;
6422 HEAP32[i32 >> 2] = HEAP32[i32 >> 2] | 1;
6423 }
6424 i32 = i2 + 8 | 0;
6425 STACKTOP = i1;
6426 return i32 | 0;
6427 }
6428 i18 = HEAP32[68 >> 2] | 0;
6429 if (i12 >>> 0 < i18 >>> 0) {
6430 i31 = i18 - i12 | 0;
6431 HEAP32[68 >> 2] = i31;
6432 i32 = HEAP32[80 >> 2] | 0;
6433 HEAP32[80 >> 2] = i32 + i12;
6434 HEAP32[i32 + (i12 + 4) >> 2] = i31 | 1;
6435 HEAP32[i32 + 4 >> 2] = i12 | 3;
6436 i32 = i32 + 8 | 0;
6437 STACKTOP = i1;
6438 return i32 | 0;
6439 }
6440 do {
6441 if ((HEAP32[132] | 0) == 0) {
6442 i18 = _sysconf(30) | 0;
6443 if ((i18 + -1 & i18 | 0) == 0) {
6444 HEAP32[536 >> 2] = i18;
6445 HEAP32[532 >> 2] = i18;
6446 HEAP32[540 >> 2] = -1;
6447 HEAP32[544 >> 2] = -1;
6448 HEAP32[548 >> 2] = 0;
6449 HEAP32[500 >> 2] = 0;
6450 HEAP32[132] = (_time(0) | 0) & -16 ^ 1431655768;
6451 break;
6452 } else {
6453 _abort();
6454 }
6455 }
6456 } while (0);
6457 i20 = i12 + 48 | 0;
6458 i25 = HEAP32[536 >> 2] | 0;
6459 i21 = i12 + 47 | 0;
6460 i22 = i25 + i21 | 0;
6461 i25 = 0 - i25 | 0;
6462 i18 = i22 & i25;
6463 if (!(i18 >>> 0 > i12 >>> 0)) {
6464 i32 = 0;
6465 STACKTOP = i1;
6466 return i32 | 0;
6467 }
6468 i24 = HEAP32[496 >> 2] | 0;
6469 if ((i24 | 0) != 0 ? (i31 = HEAP32[488 >> 2] | 0, i32 = i31 + i18 | 0, i32 >>> 0 <= i31 >>> 0 | i32 >>> 0 > i24 >>> 0) : 0) {
6470 i32 = 0;
6471 STACKTOP = i1;
6472 return i32 | 0;
6473 }
6474 L269 : do {
6475 if ((HEAP32[500 >> 2] & 4 | 0) == 0) {
6476 i26 = HEAP32[80 >> 2] | 0;
6477 L271 : do {
6478 if ((i26 | 0) != 0) {
6479 i24 = 504 | 0;
6480 while (1) {
6481 i27 = HEAP32[i24 >> 2] | 0;
6482 if (!(i27 >>> 0 > i26 >>> 0) ? (i23 = i24 + 4 | 0, (i27 + (HEAP32[i23 >> 2 ] | 0) | 0) >>> 0 > i26 >>> 0) : 0) {
6483 break;
6484 }
6485 i24 = HEAP32[i24 + 8 >> 2] | 0;
6486 if ((i24 | 0) == 0) {
6487 i13 = 182;
6488 break L271;
6489 }
6490 }
6491 if ((i24 | 0) != 0) {
6492 i25 = i22 - (HEAP32[68 >> 2] | 0) & i25;
6493 if (i25 >>> 0 < 2147483647) {
6494 i13 = _sbrk(i25 | 0) | 0;
6495 i26 = (i13 | 0) == ((HEAP32[i24 >> 2] | 0) + (HEAP32[i23 >> 2] | 0) | 0);
6496 i22 = i13;
6497 i24 = i25;
6498 i23 = i26 ? i13 : -1;
6499 i25 = i26 ? i25 : 0;
6500 i13 = 191;
6501 } else {
6502 i25 = 0;
6503 }
6504 } else {
6505 i13 = 182;
6506 }
6507 } else {
6508 i13 = 182;
6509 }
6510 } while (0);
6511 do {
6512 if ((i13 | 0) == 182) {
6513 i23 = _sbrk(0) | 0;
6514 if ((i23 | 0) != (-1 | 0)) {
6515 i24 = i23;
6516 i22 = HEAP32[532 >> 2] | 0;
6517 i25 = i22 + -1 | 0;
6518 if ((i25 & i24 | 0) == 0) {
6519 i25 = i18;
6520 } else {
6521 i25 = i18 - i24 + (i25 + i24 & 0 - i22) | 0;
6522 }
6523 i24 = HEAP32[488 >> 2] | 0;
6524 i26 = i24 + i25 | 0;
6525 if (i25 >>> 0 > i12 >>> 0 & i25 >>> 0 < 2147483647) {
6526 i22 = HEAP32[496 >> 2] | 0;
6527 if ((i22 | 0) != 0 ? i26 >>> 0 <= i24 >>> 0 | i26 >>> 0 > i22 >>> 0 : 0) {
6528 i25 = 0;
6529 break;
6530 }
6531 i22 = _sbrk(i25 | 0) | 0;
6532 i13 = (i22 | 0) == (i23 | 0);
6533 i24 = i25;
6534 i23 = i13 ? i23 : -1;
6535 i25 = i13 ? i25 : 0;
6536 i13 = 191;
6537 } else {
6538 i25 = 0;
6539 }
6540 } else {
6541 i25 = 0;
6542 }
6543 }
6544 } while (0);
6545 L291 : do {
6546 if ((i13 | 0) == 191) {
6547 i13 = 0 - i24 | 0;
6548 if ((i23 | 0) != (-1 | 0)) {
6549 i17 = i23;
6550 i14 = i25;
6551 i13 = 202;
6552 break L269;
6553 }
6554 do {
6555 if ((i22 | 0) != (-1 | 0) & i24 >>> 0 < 2147483647 & i24 >>> 0 < i20 >>> 0 ? (i19 = HEAP32[536 >> 2] | 0, i19 = i21 - i24 + i19 & 0 - i19, i19 >>> 0 < 214 7483647) : 0) {
6556 if ((_sbrk(i19 | 0) | 0) == (-1 | 0)) {
6557 _sbrk(i13 | 0) | 0;
6558 break L291;
6559 } else {
6560 i24 = i19 + i24 | 0;
6561 break;
6562 }
6563 }
6564 } while (0);
6565 if ((i22 | 0) != (-1 | 0)) {
6566 i17 = i22;
6567 i14 = i24;
6568 i13 = 202;
6569 break L269;
6570 }
6571 }
6572 } while (0);
6573 HEAP32[500 >> 2] = HEAP32[500 >> 2] | 4;
6574 i13 = 199;
6575 } else {
6576 i25 = 0;
6577 i13 = 199;
6578 }
6579 } while (0);
6580 if ((((i13 | 0) == 199 ? i18 >>> 0 < 2147483647 : 0) ? (i17 = _sbrk(i18 | 0) | 0, i16 = _sbrk(0) | 0, (i16 | 0) != (-1 | 0) & (i17 | 0) != (-1 | 0) & i17 >>> 0 < i16 >>> 0) : 0) ? (i15 = i16 - i17 | 0, i14 = i15 >>> 0 > (i12 + 40 | 0) >>> 0, i14) : 0) {
6581 i14 = i14 ? i15 : i25;
6582 i13 = 202;
6583 }
6584 if ((i13 | 0) == 202) {
6585 i15 = (HEAP32[488 >> 2] | 0) + i14 | 0;
6586 HEAP32[488 >> 2] = i15;
6587 if (i15 >>> 0 > (HEAP32[492 >> 2] | 0) >>> 0) {
6588 HEAP32[492 >> 2] = i15;
6589 }
6590 i15 = HEAP32[80 >> 2] | 0;
6591 L311 : do {
6592 if ((i15 | 0) != 0) {
6593 i21 = 504 | 0;
6594 while (1) {
6595 i16 = HEAP32[i21 >> 2] | 0;
6596 i19 = i21 + 4 | 0;
6597 i20 = HEAP32[i19 >> 2] | 0;
6598 if ((i17 | 0) == (i16 + i20 | 0)) {
6599 i13 = 214;
6600 break;
6601 }
6602 i18 = HEAP32[i21 + 8 >> 2] | 0;
6603 if ((i18 | 0) == 0) {
6604 break;
6605 } else {
6606 i21 = i18;
6607 }
6608 }
6609 if (((i13 | 0) == 214 ? (HEAP32[i21 + 12 >> 2] & 8 | 0) == 0 : 0) ? i15 >>> 0 >= i16 >>> 0 & i15 >>> 0 < i17 >>> 0 : 0) {
6610 HEAP32[i19 >> 2] = i20 + i14;
6611 i2 = (HEAP32[68 >> 2] | 0) + i14 | 0;
6612 i3 = i15 + 8 | 0;
6613 if ((i3 & 7 | 0) == 0) {
6614 i3 = 0;
6615 } else {
6616 i3 = 0 - i3 & 7;
6617 }
6618 i32 = i2 - i3 | 0;
6619 HEAP32[80 >> 2] = i15 + i3;
6620 HEAP32[68 >> 2] = i32;
6621 HEAP32[i15 + (i3 + 4) >> 2] = i32 | 1;
6622 HEAP32[i15 + (i2 + 4) >> 2] = 40;
6623 HEAP32[84 >> 2] = HEAP32[544 >> 2];
6624 break;
6625 }
6626 if (i17 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6627 HEAP32[72 >> 2] = i17;
6628 }
6629 i19 = i17 + i14 | 0;
6630 i16 = 504 | 0;
6631 while (1) {
6632 if ((HEAP32[i16 >> 2] | 0) == (i19 | 0)) {
6633 i13 = 224;
6634 break;
6635 }
6636 i18 = HEAP32[i16 + 8 >> 2] | 0;
6637 if ((i18 | 0) == 0) {
6638 break;
6639 } else {
6640 i16 = i18;
6641 }
6642 }
6643 if ((i13 | 0) == 224 ? (HEAP32[i16 + 12 >> 2] & 8 | 0) == 0 : 0) {
6644 HEAP32[i16 >> 2] = i17;
6645 i6 = i16 + 4 | 0;
6646 HEAP32[i6 >> 2] = (HEAP32[i6 >> 2] | 0) + i14;
6647 i6 = i17 + 8 | 0;
6648 if ((i6 & 7 | 0) == 0) {
6649 i6 = 0;
6650 } else {
6651 i6 = 0 - i6 & 7;
6652 }
6653 i7 = i17 + (i14 + 8) | 0;
6654 if ((i7 & 7 | 0) == 0) {
6655 i13 = 0;
6656 } else {
6657 i13 = 0 - i7 & 7;
6658 }
6659 i15 = i17 + (i13 + i14) | 0;
6660 i8 = i6 + i12 | 0;
6661 i7 = i17 + i8 | 0;
6662 i10 = i15 - (i17 + i6) - i12 | 0;
6663 HEAP32[i17 + (i6 + 4) >> 2] = i12 | 3;
6664 L348 : do {
6665 if ((i15 | 0) != (HEAP32[80 >> 2] | 0)) {
6666 if ((i15 | 0) == (HEAP32[76 >> 2] | 0)) {
6667 i32 = (HEAP32[64 >> 2] | 0) + i10 | 0;
6668 HEAP32[64 >> 2] = i32;
6669 HEAP32[76 >> 2] = i7;
6670 HEAP32[i17 + (i8 + 4) >> 2] = i32 | 1;
6671 HEAP32[i17 + (i32 + i8) >> 2] = i32;
6672 break;
6673 }
6674 i12 = i14 + 4 | 0;
6675 i18 = HEAP32[i17 + (i12 + i13) >> 2] | 0;
6676 if ((i18 & 3 | 0) == 1) {
6677 i11 = i18 & -8;
6678 i16 = i18 >>> 3;
6679 do {
6680 if (!(i18 >>> 0 < 256)) {
6681 i9 = HEAP32[i17 + ((i13 | 24) + i14) >> 2] | 0;
6682 i19 = HEAP32[i17 + (i14 + 12 + i13) >> 2] | 0;
6683 do {
6684 if ((i19 | 0) == (i15 | 0)) {
6685 i19 = i13 | 16;
6686 i18 = i17 + (i12 + i19) | 0;
6687 i16 = HEAP32[i18 >> 2] | 0;
6688 if ((i16 | 0) == 0) {
6689 i18 = i17 + (i19 + i14) | 0;
6690 i16 = HEAP32[i18 >> 2] | 0;
6691 if ((i16 | 0) == 0) {
6692 i5 = 0;
6693 break;
6694 }
6695 }
6696 while (1) {
6697 i20 = i16 + 20 | 0;
6698 i19 = HEAP32[i20 >> 2] | 0;
6699 if ((i19 | 0) != 0) {
6700 i16 = i19;
6701 i18 = i20;
6702 continue;
6703 }
6704 i19 = i16 + 16 | 0;
6705 i20 = HEAP32[i19 >> 2] | 0;
6706 if ((i20 | 0) == 0) {
6707 break;
6708 } else {
6709 i16 = i20;
6710 i18 = i19;
6711 }
6712 }
6713 if (i18 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6714 _abort();
6715 } else {
6716 HEAP32[i18 >> 2] = 0;
6717 i5 = i16;
6718 break;
6719 }
6720 } else {
6721 i18 = HEAP32[i17 + ((i13 | 8) + i14) >> 2] | 0;
6722 if (i18 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6723 _abort();
6724 }
6725 i16 = i18 + 12 | 0;
6726 if ((HEAP32[i16 >> 2] | 0) != (i15 | 0)) {
6727 _abort();
6728 }
6729 i20 = i19 + 8 | 0;
6730 if ((HEAP32[i20 >> 2] | 0) == (i15 | 0)) {
6731 HEAP32[i16 >> 2] = i19;
6732 HEAP32[i20 >> 2] = i18;
6733 i5 = i19;
6734 break;
6735 } else {
6736 _abort();
6737 }
6738 }
6739 } while (0);
6740 if ((i9 | 0) != 0) {
6741 i16 = HEAP32[i17 + (i14 + 28 + i13) >> 2] | 0;
6742 i18 = 360 + (i16 << 2) | 0;
6743 if ((i15 | 0) == (HEAP32[i18 >> 2] | 0)) {
6744 HEAP32[i18 >> 2] = i5;
6745 if ((i5 | 0) == 0) {
6746 HEAP32[60 >> 2] = HEAP32[60 >> 2] & ~(1 << i16);
6747 break;
6748 }
6749 } else {
6750 if (i9 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6751 _abort();
6752 }
6753 i16 = i9 + 16 | 0;
6754 if ((HEAP32[i16 >> 2] | 0) == (i15 | 0)) {
6755 HEAP32[i16 >> 2] = i5;
6756 } else {
6757 HEAP32[i9 + 20 >> 2] = i5;
6758 }
6759 if ((i5 | 0) == 0) {
6760 break;
6761 }
6762 }
6763 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6764 _abort();
6765 }
6766 HEAP32[i5 + 24 >> 2] = i9;
6767 i15 = i13 | 16;
6768 i9 = HEAP32[i17 + (i15 + i14) >> 2] | 0;
6769 do {
6770 if ((i9 | 0) != 0) {
6771 if (i9 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6772 _abort();
6773 } else {
6774 HEAP32[i5 + 16 >> 2] = i9;
6775 HEAP32[i9 + 24 >> 2] = i5;
6776 break;
6777 }
6778 }
6779 } while (0);
6780 i9 = HEAP32[i17 + (i12 + i15) >> 2] | 0;
6781 if ((i9 | 0) != 0) {
6782 if (i9 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6783 _abort();
6784 } else {
6785 HEAP32[i5 + 20 >> 2] = i9;
6786 HEAP32[i9 + 24 >> 2] = i5;
6787 break;
6788 }
6789 }
6790 }
6791 } else {
6792 i5 = HEAP32[i17 + ((i13 | 8) + i14) >> 2] | 0;
6793 i12 = HEAP32[i17 + (i14 + 12 + i13) >> 2] | 0;
6794 i18 = 96 + (i16 << 1 << 2) | 0;
6795 if ((i5 | 0) != (i18 | 0)) {
6796 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6797 _abort();
6798 }
6799 if ((HEAP32[i5 + 12 >> 2] | 0) != (i15 | 0)) {
6800 _abort();
6801 }
6802 }
6803 if ((i12 | 0) == (i5 | 0)) {
6804 HEAP32[14] = HEAP32[14] & ~(1 << i16);
6805 break;
6806 }
6807 if ((i12 | 0) != (i18 | 0)) {
6808 if (i12 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6809 _abort();
6810 }
6811 i16 = i12 + 8 | 0;
6812 if ((HEAP32[i16 >> 2] | 0) == (i15 | 0)) {
6813 i9 = i16;
6814 } else {
6815 _abort();
6816 }
6817 } else {
6818 i9 = i12 + 8 | 0;
6819 }
6820 HEAP32[i5 + 12 >> 2] = i12;
6821 HEAP32[i9 >> 2] = i5;
6822 }
6823 } while (0);
6824 i15 = i17 + ((i11 | i13) + i14) | 0;
6825 i10 = i11 + i10 | 0;
6826 }
6827 i5 = i15 + 4 | 0;
6828 HEAP32[i5 >> 2] = HEAP32[i5 >> 2] & -2;
6829 HEAP32[i17 + (i8 + 4) >> 2] = i10 | 1;
6830 HEAP32[i17 + (i10 + i8) >> 2] = i10;
6831 i5 = i10 >>> 3;
6832 if (i10 >>> 0 < 256) {
6833 i10 = i5 << 1;
6834 i2 = 96 + (i10 << 2) | 0;
6835 i9 = HEAP32[14] | 0;
6836 i5 = 1 << i5;
6837 if ((i9 & i5 | 0) != 0) {
6838 i9 = 96 + (i10 + 2 << 2) | 0;
6839 i5 = HEAP32[i9 >> 2] | 0;
6840 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6841 _abort();
6842 } else {
6843 i3 = i9;
6844 i4 = i5;
6845 }
6846 } else {
6847 HEAP32[14] = i9 | i5;
6848 i3 = 96 + (i10 + 2 << 2) | 0;
6849 i4 = i2;
6850 }
6851 HEAP32[i3 >> 2] = i7;
6852 HEAP32[i4 + 12 >> 2] = i7;
6853 HEAP32[i17 + (i8 + 8) >> 2] = i4;
6854 HEAP32[i17 + (i8 + 12) >> 2] = i2;
6855 break;
6856 }
6857 i3 = i10 >>> 8;
6858 if ((i3 | 0) != 0) {
6859 if (i10 >>> 0 > 16777215) {
6860 i3 = 31;
6861 } else {
6862 i31 = (i3 + 1048320 | 0) >>> 16 & 8;
6863 i32 = i3 << i31;
6864 i30 = (i32 + 520192 | 0) >>> 16 & 4;
6865 i32 = i32 << i30;
6866 i3 = (i32 + 245760 | 0) >>> 16 & 2;
6867 i3 = 14 - (i30 | i31 | i3) + (i32 << i3 >>> 15) | 0;
6868 i3 = i10 >>> (i3 + 7 | 0) & 1 | i3 << 1;
6869 }
6870 } else {
6871 i3 = 0;
6872 }
6873 i4 = 360 + (i3 << 2) | 0;
6874 HEAP32[i17 + (i8 + 28) >> 2] = i3;
6875 HEAP32[i17 + (i8 + 20) >> 2] = 0;
6876 HEAP32[i17 + (i8 + 16) >> 2] = 0;
6877 i9 = HEAP32[60 >> 2] | 0;
6878 i5 = 1 << i3;
6879 if ((i9 & i5 | 0) == 0) {
6880 HEAP32[60 >> 2] = i9 | i5;
6881 HEAP32[i4 >> 2] = i7;
6882 HEAP32[i17 + (i8 + 24) >> 2] = i4;
6883 HEAP32[i17 + (i8 + 12) >> 2] = i7;
6884 HEAP32[i17 + (i8 + 8) >> 2] = i7;
6885 break;
6886 }
6887 i4 = HEAP32[i4 >> 2] | 0;
6888 if ((i3 | 0) == 31) {
6889 i3 = 0;
6890 } else {
6891 i3 = 25 - (i3 >>> 1) | 0;
6892 }
6893 L444 : do {
6894 if ((HEAP32[i4 + 4 >> 2] & -8 | 0) != (i10 | 0)) {
6895 i3 = i10 << i3;
6896 while (1) {
6897 i5 = i4 + (i3 >>> 31 << 2) + 16 | 0;
6898 i9 = HEAP32[i5 >> 2] | 0;
6899 if ((i9 | 0) == 0) {
6900 break;
6901 }
6902 if ((HEAP32[i9 + 4 >> 2] & -8 | 0) == (i10 | 0)) {
6903 i2 = i9;
6904 break L444;
6905 } else {
6906 i3 = i3 << 1;
6907 i4 = i9;
6908 }
6909 }
6910 if (i5 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
6911 _abort();
6912 } else {
6913 HEAP32[i5 >> 2] = i7;
6914 HEAP32[i17 + (i8 + 24) >> 2] = i4;
6915 HEAP32[i17 + (i8 + 12) >> 2] = i7;
6916 HEAP32[i17 + (i8 + 8) >> 2] = i7;
6917 break L348;
6918 }
6919 } else {
6920 i2 = i4;
6921 }
6922 } while (0);
6923 i4 = i2 + 8 | 0;
6924 i3 = HEAP32[i4 >> 2] | 0;
6925 i5 = HEAP32[72 >> 2] | 0;
6926 if (i2 >>> 0 < i5 >>> 0) {
6927 _abort();
6928 }
6929 if (i3 >>> 0 < i5 >>> 0) {
6930 _abort();
6931 } else {
6932 HEAP32[i3 + 12 >> 2] = i7;
6933 HEAP32[i4 >> 2] = i7;
6934 HEAP32[i17 + (i8 + 8) >> 2] = i3;
6935 HEAP32[i17 + (i8 + 12) >> 2] = i2;
6936 HEAP32[i17 + (i8 + 24) >> 2] = 0;
6937 break;
6938 }
6939 } else {
6940 i32 = (HEAP32[68 >> 2] | 0) + i10 | 0;
6941 HEAP32[68 >> 2] = i32;
6942 HEAP32[80 >> 2] = i7;
6943 HEAP32[i17 + (i8 + 4) >> 2] = i32 | 1;
6944 }
6945 } while (0);
6946 i32 = i17 + (i6 | 8) | 0;
6947 STACKTOP = i1;
6948 return i32 | 0;
6949 }
6950 i3 = 504 | 0;
6951 while (1) {
6952 i2 = HEAP32[i3 >> 2] | 0;
6953 if (!(i2 >>> 0 > i15 >>> 0) ? (i11 = HEAP32[i3 + 4 >> 2] | 0, i10 = i2 + i1 1 | 0, i10 >>> 0 > i15 >>> 0) : 0) {
6954 break;
6955 }
6956 i3 = HEAP32[i3 + 8 >> 2] | 0;
6957 }
6958 i3 = i2 + (i11 + -39) | 0;
6959 if ((i3 & 7 | 0) == 0) {
6960 i3 = 0;
6961 } else {
6962 i3 = 0 - i3 & 7;
6963 }
6964 i2 = i2 + (i11 + -47 + i3) | 0;
6965 i2 = i2 >>> 0 < (i15 + 16 | 0) >>> 0 ? i15 : i2;
6966 i3 = i2 + 8 | 0;
6967 i4 = i17 + 8 | 0;
6968 if ((i4 & 7 | 0) == 0) {
6969 i4 = 0;
6970 } else {
6971 i4 = 0 - i4 & 7;
6972 }
6973 i32 = i14 + -40 - i4 | 0;
6974 HEAP32[80 >> 2] = i17 + i4;
6975 HEAP32[68 >> 2] = i32;
6976 HEAP32[i17 + (i4 + 4) >> 2] = i32 | 1;
6977 HEAP32[i17 + (i14 + -36) >> 2] = 40;
6978 HEAP32[84 >> 2] = HEAP32[544 >> 2];
6979 HEAP32[i2 + 4 >> 2] = 27;
6980 HEAP32[i3 + 0 >> 2] = HEAP32[504 >> 2];
6981 HEAP32[i3 + 4 >> 2] = HEAP32[508 >> 2];
6982 HEAP32[i3 + 8 >> 2] = HEAP32[512 >> 2];
6983 HEAP32[i3 + 12 >> 2] = HEAP32[516 >> 2];
6984 HEAP32[504 >> 2] = i17;
6985 HEAP32[508 >> 2] = i14;
6986 HEAP32[516 >> 2] = 0;
6987 HEAP32[512 >> 2] = i3;
6988 i4 = i2 + 28 | 0;
6989 HEAP32[i4 >> 2] = 7;
6990 if ((i2 + 32 | 0) >>> 0 < i10 >>> 0) {
6991 while (1) {
6992 i3 = i4 + 4 | 0;
6993 HEAP32[i3 >> 2] = 7;
6994 if ((i4 + 8 | 0) >>> 0 < i10 >>> 0) {
6995 i4 = i3;
6996 } else {
6997 break;
6998 }
6999 }
7000 }
7001 if ((i2 | 0) != (i15 | 0)) {
7002 i2 = i2 - i15 | 0;
7003 i3 = i15 + (i2 + 4) | 0;
7004 HEAP32[i3 >> 2] = HEAP32[i3 >> 2] & -2;
7005 HEAP32[i15 + 4 >> 2] = i2 | 1;
7006 HEAP32[i15 + i2 >> 2] = i2;
7007 i3 = i2 >>> 3;
7008 if (i2 >>> 0 < 256) {
7009 i4 = i3 << 1;
7010 i2 = 96 + (i4 << 2) | 0;
7011 i5 = HEAP32[14] | 0;
7012 i3 = 1 << i3;
7013 if ((i5 & i3 | 0) != 0) {
7014 i4 = 96 + (i4 + 2 << 2) | 0;
7015 i3 = HEAP32[i4 >> 2] | 0;
7016 if (i3 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7017 _abort();
7018 } else {
7019 i7 = i4;
7020 i8 = i3;
7021 }
7022 } else {
7023 HEAP32[14] = i5 | i3;
7024 i7 = 96 + (i4 + 2 << 2) | 0;
7025 i8 = i2;
7026 }
7027 HEAP32[i7 >> 2] = i15;
7028 HEAP32[i8 + 12 >> 2] = i15;
7029 HEAP32[i15 + 8 >> 2] = i8;
7030 HEAP32[i15 + 12 >> 2] = i2;
7031 break;
7032 }
7033 i3 = i2 >>> 8;
7034 if ((i3 | 0) != 0) {
7035 if (i2 >>> 0 > 16777215) {
7036 i3 = 31;
7037 } else {
7038 i31 = (i3 + 1048320 | 0) >>> 16 & 8;
7039 i32 = i3 << i31;
7040 i30 = (i32 + 520192 | 0) >>> 16 & 4;
7041 i32 = i32 << i30;
7042 i3 = (i32 + 245760 | 0) >>> 16 & 2;
7043 i3 = 14 - (i30 | i31 | i3) + (i32 << i3 >>> 15) | 0;
7044 i3 = i2 >>> (i3 + 7 | 0) & 1 | i3 << 1;
7045 }
7046 } else {
7047 i3 = 0;
7048 }
7049 i7 = 360 + (i3 << 2) | 0;
7050 HEAP32[i15 + 28 >> 2] = i3;
7051 HEAP32[i15 + 20 >> 2] = 0;
7052 HEAP32[i15 + 16 >> 2] = 0;
7053 i4 = HEAP32[60 >> 2] | 0;
7054 i5 = 1 << i3;
7055 if ((i4 & i5 | 0) == 0) {
7056 HEAP32[60 >> 2] = i4 | i5;
7057 HEAP32[i7 >> 2] = i15;
7058 HEAP32[i15 + 24 >> 2] = i7;
7059 HEAP32[i15 + 12 >> 2] = i15;
7060 HEAP32[i15 + 8 >> 2] = i15;
7061 break;
7062 }
7063 i4 = HEAP32[i7 >> 2] | 0;
7064 if ((i3 | 0) == 31) {
7065 i3 = 0;
7066 } else {
7067 i3 = 25 - (i3 >>> 1) | 0;
7068 }
7069 L499 : do {
7070 if ((HEAP32[i4 + 4 >> 2] & -8 | 0) != (i2 | 0)) {
7071 i3 = i2 << i3;
7072 while (1) {
7073 i7 = i4 + (i3 >>> 31 << 2) + 16 | 0;
7074 i5 = HEAP32[i7 >> 2] | 0;
7075 if ((i5 | 0) == 0) {
7076 break;
7077 }
7078 if ((HEAP32[i5 + 4 >> 2] & -8 | 0) == (i2 | 0)) {
7079 i6 = i5;
7080 break L499;
7081 } else {
7082 i3 = i3 << 1;
7083 i4 = i5;
7084 }
7085 }
7086 if (i7 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7087 _abort();
7088 } else {
7089 HEAP32[i7 >> 2] = i15;
7090 HEAP32[i15 + 24 >> 2] = i4;
7091 HEAP32[i15 + 12 >> 2] = i15;
7092 HEAP32[i15 + 8 >> 2] = i15;
7093 break L311;
7094 }
7095 } else {
7096 i6 = i4;
7097 }
7098 } while (0);
7099 i4 = i6 + 8 | 0;
7100 i3 = HEAP32[i4 >> 2] | 0;
7101 i2 = HEAP32[72 >> 2] | 0;
7102 if (i6 >>> 0 < i2 >>> 0) {
7103 _abort();
7104 }
7105 if (i3 >>> 0 < i2 >>> 0) {
7106 _abort();
7107 } else {
7108 HEAP32[i3 + 12 >> 2] = i15;
7109 HEAP32[i4 >> 2] = i15;
7110 HEAP32[i15 + 8 >> 2] = i3;
7111 HEAP32[i15 + 12 >> 2] = i6;
7112 HEAP32[i15 + 24 >> 2] = 0;
7113 break;
7114 }
7115 }
7116 } else {
7117 i32 = HEAP32[72 >> 2] | 0;
7118 if ((i32 | 0) == 0 | i17 >>> 0 < i32 >>> 0) {
7119 HEAP32[72 >> 2] = i17;
7120 }
7121 HEAP32[504 >> 2] = i17;
7122 HEAP32[508 >> 2] = i14;
7123 HEAP32[516 >> 2] = 0;
7124 HEAP32[92 >> 2] = HEAP32[132];
7125 HEAP32[88 >> 2] = -1;
7126 i2 = 0;
7127 do {
7128 i32 = i2 << 1;
7129 i31 = 96 + (i32 << 2) | 0;
7130 HEAP32[96 + (i32 + 3 << 2) >> 2] = i31;
7131 HEAP32[96 + (i32 + 2 << 2) >> 2] = i31;
7132 i2 = i2 + 1 | 0;
7133 } while ((i2 | 0) != 32);
7134 i2 = i17 + 8 | 0;
7135 if ((i2 & 7 | 0) == 0) {
7136 i2 = 0;
7137 } else {
7138 i2 = 0 - i2 & 7;
7139 }
7140 i32 = i14 + -40 - i2 | 0;
7141 HEAP32[80 >> 2] = i17 + i2;
7142 HEAP32[68 >> 2] = i32;
7143 HEAP32[i17 + (i2 + 4) >> 2] = i32 | 1;
7144 HEAP32[i17 + (i14 + -36) >> 2] = 40;
7145 HEAP32[84 >> 2] = HEAP32[544 >> 2];
7146 }
7147 } while (0);
7148 i2 = HEAP32[68 >> 2] | 0;
7149 if (i2 >>> 0 > i12 >>> 0) {
7150 i31 = i2 - i12 | 0;
7151 HEAP32[68 >> 2] = i31;
7152 i32 = HEAP32[80 >> 2] | 0;
7153 HEAP32[80 >> 2] = i32 + i12;
7154 HEAP32[i32 + (i12 + 4) >> 2] = i31 | 1;
7155 HEAP32[i32 + 4 >> 2] = i12 | 3;
7156 i32 = i32 + 8 | 0;
7157 STACKTOP = i1;
7158 return i32 | 0;
7159 }
7160 }
7161 HEAP32[(___errno_location() | 0) >> 2] = 12;
7162 i32 = 0;
7163 STACKTOP = i1;
7164 return i32 | 0;
7165 }
7166 function _free(i7) {
7167 i7 = i7 | 0;
7168 var i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i8 = 0, i9 = 0, i10 = 0, i1 1 = 0, i12 = 0, i13 = 0, i14 = 0, i15 = 0, i16 = 0, i17 = 0, i18 = 0, i19 = 0, i 20 = 0, i21 = 0;
7169 i1 = STACKTOP;
7170 if ((i7 | 0) == 0) {
7171 STACKTOP = i1;
7172 return;
7173 }
7174 i15 = i7 + -8 | 0;
7175 i16 = HEAP32[72 >> 2] | 0;
7176 if (i15 >>> 0 < i16 >>> 0) {
7177 _abort();
7178 }
7179 i13 = HEAP32[i7 + -4 >> 2] | 0;
7180 i12 = i13 & 3;
7181 if ((i12 | 0) == 1) {
7182 _abort();
7183 }
7184 i8 = i13 & -8;
7185 i6 = i7 + (i8 + -8) | 0;
7186 do {
7187 if ((i13 & 1 | 0) == 0) {
7188 i19 = HEAP32[i15 >> 2] | 0;
7189 if ((i12 | 0) == 0) {
7190 STACKTOP = i1;
7191 return;
7192 }
7193 i15 = -8 - i19 | 0;
7194 i13 = i7 + i15 | 0;
7195 i12 = i19 + i8 | 0;
7196 if (i13 >>> 0 < i16 >>> 0) {
7197 _abort();
7198 }
7199 if ((i13 | 0) == (HEAP32[76 >> 2] | 0)) {
7200 i2 = i7 + (i8 + -4) | 0;
7201 if ((HEAP32[i2 >> 2] & 3 | 0) != 3) {
7202 i2 = i13;
7203 i11 = i12;
7204 break;
7205 }
7206 HEAP32[64 >> 2] = i12;
7207 HEAP32[i2 >> 2] = HEAP32[i2 >> 2] & -2;
7208 HEAP32[i7 + (i15 + 4) >> 2] = i12 | 1;
7209 HEAP32[i6 >> 2] = i12;
7210 STACKTOP = i1;
7211 return;
7212 }
7213 i18 = i19 >>> 3;
7214 if (i19 >>> 0 < 256) {
7215 i2 = HEAP32[i7 + (i15 + 8) >> 2] | 0;
7216 i11 = HEAP32[i7 + (i15 + 12) >> 2] | 0;
7217 i14 = 96 + (i18 << 1 << 2) | 0;
7218 if ((i2 | 0) != (i14 | 0)) {
7219 if (i2 >>> 0 < i16 >>> 0) {
7220 _abort();
7221 }
7222 if ((HEAP32[i2 + 12 >> 2] | 0) != (i13 | 0)) {
7223 _abort();
7224 }
7225 }
7226 if ((i11 | 0) == (i2 | 0)) {
7227 HEAP32[14] = HEAP32[14] & ~(1 << i18);
7228 i2 = i13;
7229 i11 = i12;
7230 break;
7231 }
7232 if ((i11 | 0) != (i14 | 0)) {
7233 if (i11 >>> 0 < i16 >>> 0) {
7234 _abort();
7235 }
7236 i14 = i11 + 8 | 0;
7237 if ((HEAP32[i14 >> 2] | 0) == (i13 | 0)) {
7238 i17 = i14;
7239 } else {
7240 _abort();
7241 }
7242 } else {
7243 i17 = i11 + 8 | 0;
7244 }
7245 HEAP32[i2 + 12 >> 2] = i11;
7246 HEAP32[i17 >> 2] = i2;
7247 i2 = i13;
7248 i11 = i12;
7249 break;
7250 }
7251 i17 = HEAP32[i7 + (i15 + 24) >> 2] | 0;
7252 i18 = HEAP32[i7 + (i15 + 12) >> 2] | 0;
7253 do {
7254 if ((i18 | 0) == (i13 | 0)) {
7255 i19 = i7 + (i15 + 20) | 0;
7256 i18 = HEAP32[i19 >> 2] | 0;
7257 if ((i18 | 0) == 0) {
7258 i19 = i7 + (i15 + 16) | 0;
7259 i18 = HEAP32[i19 >> 2] | 0;
7260 if ((i18 | 0) == 0) {
7261 i14 = 0;
7262 break;
7263 }
7264 }
7265 while (1) {
7266 i21 = i18 + 20 | 0;
7267 i20 = HEAP32[i21 >> 2] | 0;
7268 if ((i20 | 0) != 0) {
7269 i18 = i20;
7270 i19 = i21;
7271 continue;
7272 }
7273 i20 = i18 + 16 | 0;
7274 i21 = HEAP32[i20 >> 2] | 0;
7275 if ((i21 | 0) == 0) {
7276 break;
7277 } else {
7278 i18 = i21;
7279 i19 = i20;
7280 }
7281 }
7282 if (i19 >>> 0 < i16 >>> 0) {
7283 _abort();
7284 } else {
7285 HEAP32[i19 >> 2] = 0;
7286 i14 = i18;
7287 break;
7288 }
7289 } else {
7290 i19 = HEAP32[i7 + (i15 + 8) >> 2] | 0;
7291 if (i19 >>> 0 < i16 >>> 0) {
7292 _abort();
7293 }
7294 i16 = i19 + 12 | 0;
7295 if ((HEAP32[i16 >> 2] | 0) != (i13 | 0)) {
7296 _abort();
7297 }
7298 i20 = i18 + 8 | 0;
7299 if ((HEAP32[i20 >> 2] | 0) == (i13 | 0)) {
7300 HEAP32[i16 >> 2] = i18;
7301 HEAP32[i20 >> 2] = i19;
7302 i14 = i18;
7303 break;
7304 } else {
7305 _abort();
7306 }
7307 }
7308 } while (0);
7309 if ((i17 | 0) != 0) {
7310 i18 = HEAP32[i7 + (i15 + 28) >> 2] | 0;
7311 i16 = 360 + (i18 << 2) | 0;
7312 if ((i13 | 0) == (HEAP32[i16 >> 2] | 0)) {
7313 HEAP32[i16 >> 2] = i14;
7314 if ((i14 | 0) == 0) {
7315 HEAP32[60 >> 2] = HEAP32[60 >> 2] & ~(1 << i18);
7316 i2 = i13;
7317 i11 = i12;
7318 break;
7319 }
7320 } else {
7321 if (i17 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7322 _abort();
7323 }
7324 i16 = i17 + 16 | 0;
7325 if ((HEAP32[i16 >> 2] | 0) == (i13 | 0)) {
7326 HEAP32[i16 >> 2] = i14;
7327 } else {
7328 HEAP32[i17 + 20 >> 2] = i14;
7329 }
7330 if ((i14 | 0) == 0) {
7331 i2 = i13;
7332 i11 = i12;
7333 break;
7334 }
7335 }
7336 if (i14 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7337 _abort();
7338 }
7339 HEAP32[i14 + 24 >> 2] = i17;
7340 i16 = HEAP32[i7 + (i15 + 16) >> 2] | 0;
7341 do {
7342 if ((i16 | 0) != 0) {
7343 if (i16 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7344 _abort();
7345 } else {
7346 HEAP32[i14 + 16 >> 2] = i16;
7347 HEAP32[i16 + 24 >> 2] = i14;
7348 break;
7349 }
7350 }
7351 } while (0);
7352 i15 = HEAP32[i7 + (i15 + 20) >> 2] | 0;
7353 if ((i15 | 0) != 0) {
7354 if (i15 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7355 _abort();
7356 } else {
7357 HEAP32[i14 + 20 >> 2] = i15;
7358 HEAP32[i15 + 24 >> 2] = i14;
7359 i2 = i13;
7360 i11 = i12;
7361 break;
7362 }
7363 } else {
7364 i2 = i13;
7365 i11 = i12;
7366 }
7367 } else {
7368 i2 = i13;
7369 i11 = i12;
7370 }
7371 } else {
7372 i2 = i15;
7373 i11 = i8;
7374 }
7375 } while (0);
7376 if (!(i2 >>> 0 < i6 >>> 0)) {
7377 _abort();
7378 }
7379 i12 = i7 + (i8 + -4) | 0;
7380 i13 = HEAP32[i12 >> 2] | 0;
7381 if ((i13 & 1 | 0) == 0) {
7382 _abort();
7383 }
7384 if ((i13 & 2 | 0) == 0) {
7385 if ((i6 | 0) == (HEAP32[80 >> 2] | 0)) {
7386 i21 = (HEAP32[68 >> 2] | 0) + i11 | 0;
7387 HEAP32[68 >> 2] = i21;
7388 HEAP32[80 >> 2] = i2;
7389 HEAP32[i2 + 4 >> 2] = i21 | 1;
7390 if ((i2 | 0) != (HEAP32[76 >> 2] | 0)) {
7391 STACKTOP = i1;
7392 return;
7393 }
7394 HEAP32[76 >> 2] = 0;
7395 HEAP32[64 >> 2] = 0;
7396 STACKTOP = i1;
7397 return;
7398 }
7399 if ((i6 | 0) == (HEAP32[76 >> 2] | 0)) {
7400 i21 = (HEAP32[64 >> 2] | 0) + i11 | 0;
7401 HEAP32[64 >> 2] = i21;
7402 HEAP32[76 >> 2] = i2;
7403 HEAP32[i2 + 4 >> 2] = i21 | 1;
7404 HEAP32[i2 + i21 >> 2] = i21;
7405 STACKTOP = i1;
7406 return;
7407 }
7408 i11 = (i13 & -8) + i11 | 0;
7409 i12 = i13 >>> 3;
7410 do {
7411 if (!(i13 >>> 0 < 256)) {
7412 i10 = HEAP32[i7 + (i8 + 16) >> 2] | 0;
7413 i15 = HEAP32[i7 + (i8 | 4) >> 2] | 0;
7414 do {
7415 if ((i15 | 0) == (i6 | 0)) {
7416 i13 = i7 + (i8 + 12) | 0;
7417 i12 = HEAP32[i13 >> 2] | 0;
7418 if ((i12 | 0) == 0) {
7419 i13 = i7 + (i8 + 8) | 0;
7420 i12 = HEAP32[i13 >> 2] | 0;
7421 if ((i12 | 0) == 0) {
7422 i9 = 0;
7423 break;
7424 }
7425 }
7426 while (1) {
7427 i14 = i12 + 20 | 0;
7428 i15 = HEAP32[i14 >> 2] | 0;
7429 if ((i15 | 0) != 0) {
7430 i12 = i15;
7431 i13 = i14;
7432 continue;
7433 }
7434 i14 = i12 + 16 | 0;
7435 i15 = HEAP32[i14 >> 2] | 0;
7436 if ((i15 | 0) == 0) {
7437 break;
7438 } else {
7439 i12 = i15;
7440 i13 = i14;
7441 }
7442 }
7443 if (i13 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7444 _abort();
7445 } else {
7446 HEAP32[i13 >> 2] = 0;
7447 i9 = i12;
7448 break;
7449 }
7450 } else {
7451 i13 = HEAP32[i7 + i8 >> 2] | 0;
7452 if (i13 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7453 _abort();
7454 }
7455 i14 = i13 + 12 | 0;
7456 if ((HEAP32[i14 >> 2] | 0) != (i6 | 0)) {
7457 _abort();
7458 }
7459 i12 = i15 + 8 | 0;
7460 if ((HEAP32[i12 >> 2] | 0) == (i6 | 0)) {
7461 HEAP32[i14 >> 2] = i15;
7462 HEAP32[i12 >> 2] = i13;
7463 i9 = i15;
7464 break;
7465 } else {
7466 _abort();
7467 }
7468 }
7469 } while (0);
7470 if ((i10 | 0) != 0) {
7471 i12 = HEAP32[i7 + (i8 + 20) >> 2] | 0;
7472 i13 = 360 + (i12 << 2) | 0;
7473 if ((i6 | 0) == (HEAP32[i13 >> 2] | 0)) {
7474 HEAP32[i13 >> 2] = i9;
7475 if ((i9 | 0) == 0) {
7476 HEAP32[60 >> 2] = HEAP32[60 >> 2] & ~(1 << i12);
7477 break;
7478 }
7479 } else {
7480 if (i10 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7481 _abort();
7482 }
7483 i12 = i10 + 16 | 0;
7484 if ((HEAP32[i12 >> 2] | 0) == (i6 | 0)) {
7485 HEAP32[i12 >> 2] = i9;
7486 } else {
7487 HEAP32[i10 + 20 >> 2] = i9;
7488 }
7489 if ((i9 | 0) == 0) {
7490 break;
7491 }
7492 }
7493 if (i9 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7494 _abort();
7495 }
7496 HEAP32[i9 + 24 >> 2] = i10;
7497 i6 = HEAP32[i7 + (i8 + 8) >> 2] | 0;
7498 do {
7499 if ((i6 | 0) != 0) {
7500 if (i6 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7501 _abort();
7502 } else {
7503 HEAP32[i9 + 16 >> 2] = i6;
7504 HEAP32[i6 + 24 >> 2] = i9;
7505 break;
7506 }
7507 }
7508 } while (0);
7509 i6 = HEAP32[i7 + (i8 + 12) >> 2] | 0;
7510 if ((i6 | 0) != 0) {
7511 if (i6 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7512 _abort();
7513 } else {
7514 HEAP32[i9 + 20 >> 2] = i6;
7515 HEAP32[i6 + 24 >> 2] = i9;
7516 break;
7517 }
7518 }
7519 }
7520 } else {
7521 i9 = HEAP32[i7 + i8 >> 2] | 0;
7522 i7 = HEAP32[i7 + (i8 | 4) >> 2] | 0;
7523 i8 = 96 + (i12 << 1 << 2) | 0;
7524 if ((i9 | 0) != (i8 | 0)) {
7525 if (i9 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7526 _abort();
7527 }
7528 if ((HEAP32[i9 + 12 >> 2] | 0) != (i6 | 0)) {
7529 _abort();
7530 }
7531 }
7532 if ((i7 | 0) == (i9 | 0)) {
7533 HEAP32[14] = HEAP32[14] & ~(1 << i12);
7534 break;
7535 }
7536 if ((i7 | 0) != (i8 | 0)) {
7537 if (i7 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7538 _abort();
7539 }
7540 i8 = i7 + 8 | 0;
7541 if ((HEAP32[i8 >> 2] | 0) == (i6 | 0)) {
7542 i10 = i8;
7543 } else {
7544 _abort();
7545 }
7546 } else {
7547 i10 = i7 + 8 | 0;
7548 }
7549 HEAP32[i9 + 12 >> 2] = i7;
7550 HEAP32[i10 >> 2] = i9;
7551 }
7552 } while (0);
7553 HEAP32[i2 + 4 >> 2] = i11 | 1;
7554 HEAP32[i2 + i11 >> 2] = i11;
7555 if ((i2 | 0) == (HEAP32[76 >> 2] | 0)) {
7556 HEAP32[64 >> 2] = i11;
7557 STACKTOP = i1;
7558 return;
7559 }
7560 } else {
7561 HEAP32[i12 >> 2] = i13 & -2;
7562 HEAP32[i2 + 4 >> 2] = i11 | 1;
7563 HEAP32[i2 + i11 >> 2] = i11;
7564 }
7565 i6 = i11 >>> 3;
7566 if (i11 >>> 0 < 256) {
7567 i7 = i6 << 1;
7568 i3 = 96 + (i7 << 2) | 0;
7569 i8 = HEAP32[14] | 0;
7570 i6 = 1 << i6;
7571 if ((i8 & i6 | 0) != 0) {
7572 i6 = 96 + (i7 + 2 << 2) | 0;
7573 i7 = HEAP32[i6 >> 2] | 0;
7574 if (i7 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7575 _abort();
7576 } else {
7577 i4 = i6;
7578 i5 = i7;
7579 }
7580 } else {
7581 HEAP32[14] = i8 | i6;
7582 i4 = 96 + (i7 + 2 << 2) | 0;
7583 i5 = i3;
7584 }
7585 HEAP32[i4 >> 2] = i2;
7586 HEAP32[i5 + 12 >> 2] = i2;
7587 HEAP32[i2 + 8 >> 2] = i5;
7588 HEAP32[i2 + 12 >> 2] = i3;
7589 STACKTOP = i1;
7590 return;
7591 }
7592 i4 = i11 >>> 8;
7593 if ((i4 | 0) != 0) {
7594 if (i11 >>> 0 > 16777215) {
7595 i4 = 31;
7596 } else {
7597 i20 = (i4 + 1048320 | 0) >>> 16 & 8;
7598 i21 = i4 << i20;
7599 i19 = (i21 + 520192 | 0) >>> 16 & 4;
7600 i21 = i21 << i19;
7601 i4 = (i21 + 245760 | 0) >>> 16 & 2;
7602 i4 = 14 - (i19 | i20 | i4) + (i21 << i4 >>> 15) | 0;
7603 i4 = i11 >>> (i4 + 7 | 0) & 1 | i4 << 1;
7604 }
7605 } else {
7606 i4 = 0;
7607 }
7608 i5 = 360 + (i4 << 2) | 0;
7609 HEAP32[i2 + 28 >> 2] = i4;
7610 HEAP32[i2 + 20 >> 2] = 0;
7611 HEAP32[i2 + 16 >> 2] = 0;
7612 i7 = HEAP32[60 >> 2] | 0;
7613 i6 = 1 << i4;
7614 L199 : do {
7615 if ((i7 & i6 | 0) != 0) {
7616 i5 = HEAP32[i5 >> 2] | 0;
7617 if ((i4 | 0) == 31) {
7618 i4 = 0;
7619 } else {
7620 i4 = 25 - (i4 >>> 1) | 0;
7621 }
7622 L205 : do {
7623 if ((HEAP32[i5 + 4 >> 2] & -8 | 0) != (i11 | 0)) {
7624 i4 = i11 << i4;
7625 i7 = i5;
7626 while (1) {
7627 i6 = i7 + (i4 >>> 31 << 2) + 16 | 0;
7628 i5 = HEAP32[i6 >> 2] | 0;
7629 if ((i5 | 0) == 0) {
7630 break;
7631 }
7632 if ((HEAP32[i5 + 4 >> 2] & -8 | 0) == (i11 | 0)) {
7633 i3 = i5;
7634 break L205;
7635 } else {
7636 i4 = i4 << 1;
7637 i7 = i5;
7638 }
7639 }
7640 if (i6 >>> 0 < (HEAP32[72 >> 2] | 0) >>> 0) {
7641 _abort();
7642 } else {
7643 HEAP32[i6 >> 2] = i2;
7644 HEAP32[i2 + 24 >> 2] = i7;
7645 HEAP32[i2 + 12 >> 2] = i2;
7646 HEAP32[i2 + 8 >> 2] = i2;
7647 break L199;
7648 }
7649 } else {
7650 i3 = i5;
7651 }
7652 } while (0);
7653 i5 = i3 + 8 | 0;
7654 i4 = HEAP32[i5 >> 2] | 0;
7655 i6 = HEAP32[72 >> 2] | 0;
7656 if (i3 >>> 0 < i6 >>> 0) {
7657 _abort();
7658 }
7659 if (i4 >>> 0 < i6 >>> 0) {
7660 _abort();
7661 } else {
7662 HEAP32[i4 + 12 >> 2] = i2;
7663 HEAP32[i5 >> 2] = i2;
7664 HEAP32[i2 + 8 >> 2] = i4;
7665 HEAP32[i2 + 12 >> 2] = i3;
7666 HEAP32[i2 + 24 >> 2] = 0;
7667 break;
7668 }
7669 } else {
7670 HEAP32[60 >> 2] = i7 | i6;
7671 HEAP32[i5 >> 2] = i2;
7672 HEAP32[i2 + 24 >> 2] = i5;
7673 HEAP32[i2 + 12 >> 2] = i2;
7674 HEAP32[i2 + 8 >> 2] = i2;
7675 }
7676 } while (0);
7677 i21 = (HEAP32[88 >> 2] | 0) + -1 | 0;
7678 HEAP32[88 >> 2] = i21;
7679 if ((i21 | 0) == 0) {
7680 i2 = 512 | 0;
7681 } else {
7682 STACKTOP = i1;
7683 return;
7684 }
7685 while (1) {
7686 i2 = HEAP32[i2 >> 2] | 0;
7687 if ((i2 | 0) == 0) {
7688 break;
7689 } else {
7690 i2 = i2 + 8 | 0;
7691 }
7692 }
7693 HEAP32[88 >> 2] = -1;
7694 STACKTOP = i1;
7695 return;
7696 }
7697 function __Z15fannkuch_workerPv(i9) {
7698 i9 = i9 | 0;
7699 var i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0, i10 = 0, i1 1 = 0, i12 = 0, i13 = 0, i14 = 0, i15 = 0, i16 = 0, i17 = 0, i18 = 0, i19 = 0, i 20 = 0;
7700 i3 = STACKTOP;
7701 i7 = HEAP32[i9 + 4 >> 2] | 0;
7702 i6 = i7 << 2;
7703 i5 = _malloc(i6) | 0;
7704 i2 = _malloc(i6) | 0;
7705 i6 = _malloc(i6) | 0;
7706 i10 = (i7 | 0) > 0;
7707 if (i10) {
7708 i8 = 0;
7709 do {
7710 HEAP32[i5 + (i8 << 2) >> 2] = i8;
7711 i8 = i8 + 1 | 0;
7712 } while ((i8 | 0) != (i7 | 0));
7713 i8 = i7 + -1 | 0;
7714 i17 = HEAP32[i9 >> 2] | 0;
7715 HEAP32[i5 + (i17 << 2) >> 2] = i8;
7716 i9 = i5 + (i8 << 2) | 0;
7717 HEAP32[i9 >> 2] = i17;
7718 if (i10) {
7719 i10 = i7 << 2;
7720 i11 = 0;
7721 i12 = i7;
7722 L7 : while (1) {
7723 if ((i12 | 0) > 1) {
7724 while (1) {
7725 i13 = i12 + -1 | 0;
7726 HEAP32[i6 + (i13 << 2) >> 2] = i12;
7727 if ((i13 | 0) > 1) {
7728 i12 = i13;
7729 } else {
7730 i12 = 1;
7731 break;
7732 }
7733 }
7734 }
7735 i13 = HEAP32[i5 >> 2] | 0;
7736 if ((i13 | 0) != 0 ? (HEAP32[i9 >> 2] | 0) != (i8 | 0) : 0) {
7737 _memcpy(i2 | 0, i5 | 0, i10 | 0) | 0;
7738 i15 = 0;
7739 i14 = HEAP32[i2 >> 2] | 0;
7740 while (1) {
7741 i17 = i14 + -1 | 0;
7742 if ((i17 | 0) > 1) {
7743 i16 = 1;
7744 do {
7745 i20 = i2 + (i16 << 2) | 0;
7746 i19 = HEAP32[i20 >> 2] | 0;
7747 i18 = i2 + (i17 << 2) | 0;
7748 HEAP32[i20 >> 2] = HEAP32[i18 >> 2];
7749 HEAP32[i18 >> 2] = i19;
7750 i16 = i16 + 1 | 0;
7751 i17 = i17 + -1 | 0;
7752 } while ((i16 | 0) < (i17 | 0));
7753 }
7754 i15 = i15 + 1 | 0;
7755 i20 = i2 + (i14 << 2) | 0;
7756 i16 = HEAP32[i20 >> 2] | 0;
7757 HEAP32[i20 >> 2] = i14;
7758 if ((i16 | 0) == 0) {
7759 break;
7760 } else {
7761 i14 = i16;
7762 }
7763 }
7764 i11 = (i11 | 0) < (i15 | 0) ? i15 : i11;
7765 }
7766 if ((i12 | 0) >= (i8 | 0)) {
7767 i8 = 34;
7768 break;
7769 }
7770 while (1) {
7771 if ((i12 | 0) > 0) {
7772 i14 = 0;
7773 while (1) {
7774 i15 = i14 + 1 | 0;
7775 HEAP32[i5 + (i14 << 2) >> 2] = HEAP32[i5 + (i15 << 2) >> 2];
7776 if ((i15 | 0) == (i12 | 0)) {
7777 i14 = i12;
7778 break;
7779 } else {
7780 i14 = i15;
7781 }
7782 }
7783 } else {
7784 i14 = 0;
7785 }
7786 HEAP32[i5 + (i14 << 2) >> 2] = i13;
7787 i14 = i6 + (i12 << 2) | 0;
7788 i20 = (HEAP32[i14 >> 2] | 0) + -1 | 0;
7789 HEAP32[i14 >> 2] = i20;
7790 i14 = i12 + 1 | 0;
7791 if ((i20 | 0) > 0) {
7792 continue L7;
7793 }
7794 if ((i14 | 0) >= (i8 | 0)) {
7795 i8 = 34;
7796 break L7;
7797 }
7798 i13 = HEAP32[i5 >> 2] | 0;
7799 i12 = i14;
7800 }
7801 }
7802 if ((i8 | 0) == 34) {
7803 _free(i5);
7804 _free(i2);
7805 _free(i6);
7806 STACKTOP = i3;
7807 return i11 | 0;
7808 }
7809 } else {
7810 i1 = i9;
7811 i4 = i8;
7812 }
7813 } else {
7814 i4 = i7 + -1 | 0;
7815 i20 = HEAP32[i9 >> 2] | 0;
7816 HEAP32[i5 + (i20 << 2) >> 2] = i4;
7817 i1 = i5 + (i4 << 2) | 0;
7818 HEAP32[i1 >> 2] = i20;
7819 }
7820 i11 = 0;
7821 L36 : while (1) {
7822 if ((i7 | 0) > 1) {
7823 while (1) {
7824 i8 = i7 + -1 | 0;
7825 HEAP32[i6 + (i8 << 2) >> 2] = i7;
7826 if ((i8 | 0) > 1) {
7827 i7 = i8;
7828 } else {
7829 i7 = 1;
7830 break;
7831 }
7832 }
7833 }
7834 i8 = HEAP32[i5 >> 2] | 0;
7835 if ((i8 | 0) != 0 ? (HEAP32[i1 >> 2] | 0) != (i4 | 0) : 0) {
7836 i10 = 0;
7837 i9 = HEAP32[i2 >> 2] | 0;
7838 while (1) {
7839 i13 = i9 + -1 | 0;
7840 if ((i13 | 0) > 1) {
7841 i12 = 1;
7842 do {
7843 i18 = i2 + (i12 << 2) | 0;
7844 i19 = HEAP32[i18 >> 2] | 0;
7845 i20 = i2 + (i13 << 2) | 0;
7846 HEAP32[i18 >> 2] = HEAP32[i20 >> 2];
7847 HEAP32[i20 >> 2] = i19;
7848 i12 = i12 + 1 | 0;
7849 i13 = i13 + -1 | 0;
7850 } while ((i12 | 0) < (i13 | 0));
7851 }
7852 i10 = i10 + 1 | 0;
7853 i20 = i2 + (i9 << 2) | 0;
7854 i12 = HEAP32[i20 >> 2] | 0;
7855 HEAP32[i20 >> 2] = i9;
7856 if ((i12 | 0) == 0) {
7857 break;
7858 } else {
7859 i9 = i12;
7860 }
7861 }
7862 i11 = (i11 | 0) < (i10 | 0) ? i10 : i11;
7863 }
7864 if ((i7 | 0) >= (i4 | 0)) {
7865 i8 = 34;
7866 break;
7867 }
7868 while (1) {
7869 if ((i7 | 0) > 0) {
7870 i9 = 0;
7871 while (1) {
7872 i10 = i9 + 1 | 0;
7873 HEAP32[i5 + (i9 << 2) >> 2] = HEAP32[i5 + (i10 << 2) >> 2];
7874 if ((i10 | 0) == (i7 | 0)) {
7875 i9 = i7;
7876 break;
7877 } else {
7878 i9 = i10;
7879 }
7880 }
7881 } else {
7882 i9 = 0;
7883 }
7884 HEAP32[i5 + (i9 << 2) >> 2] = i8;
7885 i9 = i6 + (i7 << 2) | 0;
7886 i20 = (HEAP32[i9 >> 2] | 0) + -1 | 0;
7887 HEAP32[i9 >> 2] = i20;
7888 i9 = i7 + 1 | 0;
7889 if ((i20 | 0) > 0) {
7890 continue L36;
7891 }
7892 if ((i9 | 0) >= (i4 | 0)) {
7893 i8 = 34;
7894 break L36;
7895 }
7896 i8 = HEAP32[i5 >> 2] | 0;
7897 i7 = i9;
7898 }
7899 }
7900 if ((i8 | 0) == 34) {
7901 _free(i5);
7902 _free(i2);
7903 _free(i6);
7904 STACKTOP = i3;
7905 return i11 | 0;
7906 }
7907 return 0;
7908 }
7909 function _main(i3, i5) {
7910 i3 = i3 | 0;
7911 i5 = i5 | 0;
7912 var i1 = 0, i2 = 0, i4 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0, i10 = 0, i11 = 0;
7913 i2 = STACKTOP;
7914 STACKTOP = STACKTOP + 16 | 0;
7915 i1 = i2;
7916 L1 : do {
7917 if ((i3 | 0) > 1) {
7918 i3 = HEAP8[HEAP32[i5 + 4 >> 2] | 0] | 0;
7919 switch (i3 | 0) {
7920 case 50:
7921 {
7922 i3 = 10;
7923 break L1;
7924 }
7925 case 51:
7926 {
7927 i4 = 4;
7928 break L1;
7929 }
7930 case 52:
7931 {
7932 i3 = 11;
7933 break L1;
7934 }
7935 case 53:
7936 {
7937 i3 = 12;
7938 break L1;
7939 }
7940 case 49:
7941 {
7942 i3 = 9;
7943 break L1;
7944 }
7945 case 48:
7946 {
7947 i11 = 0;
7948 STACKTOP = i2;
7949 return i11 | 0;
7950 }
7951 default:
7952 {
7953 HEAP32[i1 >> 2] = i3 + -48;
7954 _printf(8, i1 | 0) | 0;
7955 i11 = -1;
7956 STACKTOP = i2;
7957 return i11 | 0;
7958 }
7959 }
7960 } else {
7961 i4 = 4;
7962 }
7963 } while (0);
7964 if ((i4 | 0) == 4) {
7965 i3 = 11;
7966 }
7967 i5 = i3 + -1 | 0;
7968 i6 = 0;
7969 i7 = 0;
7970 while (1) {
7971 i4 = _malloc(12) | 0;
7972 HEAP32[i4 >> 2] = i7;
7973 HEAP32[i4 + 4 >> 2] = i3;
7974 HEAP32[i4 + 8 >> 2] = i6;
7975 i7 = i7 + 1 | 0;
7976 if ((i7 | 0) == (i5 | 0)) {
7977 break;
7978 } else {
7979 i6 = i4;
7980 }
7981 }
7982 i5 = i3 << 2;
7983 i6 = _malloc(i5) | 0;
7984 i5 = _malloc(i5) | 0;
7985 i7 = 0;
7986 do {
7987 HEAP32[i6 + (i7 << 2) >> 2] = i7;
7988 i7 = i7 + 1 | 0;
7989 } while ((i7 | 0) != (i3 | 0));
7990 i8 = i3;
7991 i7 = 30;
7992 L19 : do {
7993 i9 = 0;
7994 do {
7995 HEAP32[i1 >> 2] = (HEAP32[i6 + (i9 << 2) >> 2] | 0) + 1;
7996 _printf(48, i1 | 0) | 0;
7997 i9 = i9 + 1 | 0;
7998 } while ((i9 | 0) != (i3 | 0));
7999 _putchar(10) | 0;
8000 i7 = i7 + -1 | 0;
8001 if ((i8 | 0) <= 1) {
8002 if ((i8 | 0) == (i3 | 0)) {
8003 break;
8004 }
8005 } else {
8006 while (1) {
8007 i9 = i8 + -1 | 0;
8008 HEAP32[i5 + (i9 << 2) >> 2] = i8;
8009 if ((i9 | 0) > 1) {
8010 i8 = i9;
8011 } else {
8012 i8 = 1;
8013 break;
8014 }
8015 }
8016 }
8017 while (1) {
8018 i9 = HEAP32[i6 >> 2] | 0;
8019 if ((i8 | 0) > 0) {
8020 i11 = 0;
8021 while (1) {
8022 i10 = i11 + 1 | 0;
8023 HEAP32[i6 + (i11 << 2) >> 2] = HEAP32[i6 + (i10 << 2) >> 2];
8024 if ((i10 | 0) == (i8 | 0)) {
8025 i10 = i8;
8026 break;
8027 } else {
8028 i11 = i10;
8029 }
8030 }
8031 } else {
8032 i10 = 0;
8033 }
8034 HEAP32[i6 + (i10 << 2) >> 2] = i9;
8035 i9 = i5 + (i8 << 2) | 0;
8036 i11 = (HEAP32[i9 >> 2] | 0) + -1 | 0;
8037 HEAP32[i9 >> 2] = i11;
8038 i9 = i8 + 1 | 0;
8039 if ((i11 | 0) > 0) {
8040 break;
8041 }
8042 if ((i9 | 0) == (i3 | 0)) {
8043 break L19;
8044 } else {
8045 i8 = i9;
8046 }
8047 }
8048 } while ((i7 | 0) != 0);
8049 _free(i6);
8050 _free(i5);
8051 if ((i4 | 0) == 0) {
8052 i5 = 0;
8053 } else {
8054 i5 = 0;
8055 while (1) {
8056 i6 = __Z15fannkuch_workerPv(i4) | 0;
8057 i5 = (i5 | 0) < (i6 | 0) ? i6 : i5;
8058 i6 = HEAP32[i4 + 8 >> 2] | 0;
8059 _free(i4);
8060 if ((i6 | 0) == 0) {
8061 break;
8062 } else {
8063 i4 = i6;
8064 }
8065 }
8066 }
8067 HEAP32[i1 >> 2] = i3;
8068 HEAP32[i1 + 4 >> 2] = i5;
8069 _printf(24, i1 | 0) | 0;
8070 i11 = 0;
8071 STACKTOP = i2;
8072 return i11 | 0;
8073 }
8074 function _memcpy(i3, i2, i1) {
8075 i3 = i3 | 0;
8076 i2 = i2 | 0;
8077 i1 = i1 | 0;
8078 var i4 = 0;
8079 if ((i1 | 0) >= 4096) return _emscripten_memcpy_big(i3 | 0, i2 | 0, i1 | 0) | 0 ;
8080 i4 = i3 | 0;
8081 if ((i3 & 3) == (i2 & 3)) {
8082 while (i3 & 3) {
8083 if ((i1 | 0) == 0) return i4 | 0;
8084 HEAP8[i3] = HEAP8[i2] | 0;
8085 i3 = i3 + 1 | 0;
8086 i2 = i2 + 1 | 0;
8087 i1 = i1 - 1 | 0;
8088 }
8089 while ((i1 | 0) >= 4) {
8090 HEAP32[i3 >> 2] = HEAP32[i2 >> 2];
8091 i3 = i3 + 4 | 0;
8092 i2 = i2 + 4 | 0;
8093 i1 = i1 - 4 | 0;
8094 }
8095 }
8096 while ((i1 | 0) > 0) {
8097 HEAP8[i3] = HEAP8[i2] | 0;
8098 i3 = i3 + 1 | 0;
8099 i2 = i2 + 1 | 0;
8100 i1 = i1 - 1 | 0;
8101 }
8102 return i4 | 0;
8103 }
8104 function _memset(i1, i4, i3) {
8105 i1 = i1 | 0;
8106 i4 = i4 | 0;
8107 i3 = i3 | 0;
8108 var i2 = 0, i5 = 0, i6 = 0, i7 = 0;
8109 i2 = i1 + i3 | 0;
8110 if ((i3 | 0) >= 20) {
8111 i4 = i4 & 255;
8112 i7 = i1 & 3;
8113 i6 = i4 | i4 << 8 | i4 << 16 | i4 << 24;
8114 i5 = i2 & ~3;
8115 if (i7) {
8116 i7 = i1 + 4 - i7 | 0;
8117 while ((i1 | 0) < (i7 | 0)) {
8118 HEAP8[i1] = i4;
8119 i1 = i1 + 1 | 0;
8120 }
8121 }
8122 while ((i1 | 0) < (i5 | 0)) {
8123 HEAP32[i1 >> 2] = i6;
8124 i1 = i1 + 4 | 0;
8125 }
8126 }
8127 while ((i1 | 0) < (i2 | 0)) {
8128 HEAP8[i1] = i4;
8129 i1 = i1 + 1 | 0;
8130 }
8131 return i1 - i3 | 0;
8132 }
8133 function copyTempDouble(i1) {
8134 i1 = i1 | 0;
8135 HEAP8[tempDoublePtr] = HEAP8[i1];
8136 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
8137 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
8138 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
8139 HEAP8[tempDoublePtr + 4 | 0] = HEAP8[i1 + 4 | 0];
8140 HEAP8[tempDoublePtr + 5 | 0] = HEAP8[i1 + 5 | 0];
8141 HEAP8[tempDoublePtr + 6 | 0] = HEAP8[i1 + 6 | 0];
8142 HEAP8[tempDoublePtr + 7 | 0] = HEAP8[i1 + 7 | 0];
8143 }
8144 function copyTempFloat(i1) {
8145 i1 = i1 | 0;
8146 HEAP8[tempDoublePtr] = HEAP8[i1];
8147 HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
8148 HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
8149 HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
8150 }
8151 function runPostSets() {}
8152 function _strlen(i1) {
8153 i1 = i1 | 0;
8154 var i2 = 0;
8155 i2 = i1;
8156 while (HEAP8[i2] | 0) {
8157 i2 = i2 + 1 | 0;
8158 }
8159 return i2 - i1 | 0;
8160 }
8161 function stackAlloc(i1) {
8162 i1 = i1 | 0;
8163 var i2 = 0;
8164 i2 = STACKTOP;
8165 STACKTOP = STACKTOP + i1 | 0;
8166 STACKTOP = STACKTOP + 7 & -8;
8167 return i2 | 0;
8168 }
8169 function setThrew(i1, i2) {
8170 i1 = i1 | 0;
8171 i2 = i2 | 0;
8172 if ((__THREW__ | 0) == 0) {
8173 __THREW__ = i1;
8174 threwValue = i2;
8175 }
8176 }
8177 function stackRestore(i1) {
8178 i1 = i1 | 0;
8179 STACKTOP = i1;
8180 }
8181 function setTempRet9(i1) {
8182 i1 = i1 | 0;
8183 tempRet9 = i1;
8184 }
8185 function setTempRet8(i1) {
8186 i1 = i1 | 0;
8187 tempRet8 = i1;
8188 }
8189 function setTempRet7(i1) {
8190 i1 = i1 | 0;
8191 tempRet7 = i1;
8192 }
8193 function setTempRet6(i1) {
8194 i1 = i1 | 0;
8195 tempRet6 = i1;
8196 }
8197 function setTempRet5(i1) {
8198 i1 = i1 | 0;
8199 tempRet5 = i1;
8200 }
8201 function setTempRet4(i1) {
8202 i1 = i1 | 0;
8203 tempRet4 = i1;
8204 }
8205 function setTempRet3(i1) {
8206 i1 = i1 | 0;
8207 tempRet3 = i1;
8208 }
8209 function setTempRet2(i1) {
8210 i1 = i1 | 0;
8211 tempRet2 = i1;
8212 }
8213 function setTempRet1(i1) {
8214 i1 = i1 | 0;
8215 tempRet1 = i1;
8216 }
8217 function setTempRet0(i1) {
8218 i1 = i1 | 0;
8219 tempRet0 = i1;
8220 }
8221 function stackSave() {
8222 return STACKTOP | 0;
8223 }
8224
8225 // EMSCRIPTEN_END_FUNCS
8226
8227
8228 return { _strlen: _strlen, _free: _free, _main: _main, _memset: _memset, _mall oc: _malloc, _memcpy: _memcpy, runPostSets: runPostSets, stackAlloc: stackAlloc, stackSave: stackSave, stackRestore: stackRestore, setThrew: setThrew, setTempRe t0: setTempRet0, setTempRet1: setTempRet1, setTempRet2: setTempRet2, setTempRet3 : setTempRet3, setTempRet4: setTempRet4, setTempRet5: setTempRet5, setTempRet6: setTempRet6, setTempRet7: setTempRet7, setTempRet8: setTempRet8, setTempRet9: se tTempRet9 };
8229 })
8230 // EMSCRIPTEN_END_ASM
8231 ({ "Math": Math, "Int8Array": Int8Array, "Int16Array": Int16Array, "Int32Array": Int32Array, "Uint8Array": Uint8Array, "Uint16Array": Uint16Array, "Uint32Array" : Uint32Array, "Float32Array": Float32Array, "Float64Array": Float64Array }, { " abort": abort, "assert": assert, "asmPrintInt": asmPrintInt, "asmPrintFloat": as mPrintFloat, "min": Math_min, "_fflush": _fflush, "_emscripten_memcpy_big": _ems cripten_memcpy_big, "_putchar": _putchar, "_fputc": _fputc, "_send": _send, "_pw rite": _pwrite, "_abort": _abort, "__reallyNegative": __reallyNegative, "_fwrite ": _fwrite, "_sbrk": _sbrk, "_mkport": _mkport, "_fprintf": _fprintf, "___setErr No": ___setErrNo, "__formatString": __formatString, "_fileno": _fileno, "_printf ": _printf, "_time": _time, "_sysconf": _sysconf, "_write": _write, "___errno_lo cation": ___errno_location, "STACKTOP": STACKTOP, "STACK_MAX": STACK_MAX, "tempD oublePtr": tempDoublePtr, "ABORT": ABORT, "NaN": NaN, "Infinity": Infinity }, bu ffer);
8232 var _strlen = Module["_strlen"] = asm["_strlen"];
8233 var _free = Module["_free"] = asm["_free"];
8234 var _main = Module["_main"] = asm["_main"];
8235 var _memset = Module["_memset"] = asm["_memset"];
8236 var _malloc = Module["_malloc"] = asm["_malloc"];
8237 var _memcpy = Module["_memcpy"] = asm["_memcpy"];
8238 var runPostSets = Module["runPostSets"] = asm["runPostSets"];
8239
8240 Runtime.stackAlloc = function(size) { return asm['stackAlloc'](size) };
8241 Runtime.stackSave = function() { return asm['stackSave']() };
8242 Runtime.stackRestore = function(top) { asm['stackRestore'](top) };
8243
8244
8245 // Warning: printing of i64 values may be slightly rounded! No deep i64 math use d, so precise i64 code not included
8246 var i64Math = null;
8247
8248 // === Auto-generated postamble setup entry stuff ===
8249
8250 if (memoryInitializer) {
8251 if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
8252 var data = Module['readBinary'](memoryInitializer);
8253 HEAPU8.set(data, STATIC_BASE);
8254 } else {
8255 addRunDependency('memory initializer');
8256 Browser.asyncLoad(memoryInitializer, function(data) {
8257 HEAPU8.set(data, STATIC_BASE);
8258 removeRunDependency('memory initializer');
8259 }, function(data) {
8260 throw 'could not load memory initializer ' + memoryInitializer;
8261 });
8262 }
8263 }
8264
8265 function ExitStatus(status) {
8266 this.name = "ExitStatus";
8267 this.message = "Program terminated with exit(" + status + ")";
8268 this.status = status;
8269 };
8270 ExitStatus.prototype = new Error();
8271 ExitStatus.prototype.constructor = ExitStatus;
8272
8273 var initialStackTop;
8274 var preloadStartTime = null;
8275 var calledMain = false;
8276
8277 dependenciesFulfilled = function runCaller() {
8278 // If run has never been called, and we should call run (INVOKE_RUN is true, a nd Module.noInitialRun is not false)
8279 if (!Module['calledRun'] && shouldRunNow) run([].concat(Module["arguments"]));
8280 if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
8281 }
8282
8283 Module['callMain'] = Module.callMain = function callMain(args) {
8284 assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on __ATMAIN__)');
8285 assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remai n to be called');
8286
8287 args = args || [];
8288
8289 ensureInitRuntime();
8290
8291 var argc = args.length+1;
8292 function pad() {
8293 for (var i = 0; i < 4-1; i++) {
8294 argv.push(0);
8295 }
8296 }
8297 var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORM AL) ];
8298 pad();
8299 for (var i = 0; i < argc-1; i = i + 1) {
8300 argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
8301 pad();
8302 }
8303 argv.push(0);
8304 argv = allocate(argv, 'i32', ALLOC_NORMAL);
8305
8306 initialStackTop = STACKTOP;
8307
8308 try {
8309
8310 var ret = Module['_main'](argc, argv, 0);
8311
8312
8313 // if we're not running an evented main loop, it's time to exit
8314 if (!Module['noExitRuntime']) {
8315 exit(ret);
8316 }
8317 }
8318 catch(e) {
8319 if (e instanceof ExitStatus) {
8320 // exit() throws this once it's done to make sure execution
8321 // has been stopped completely
8322 return;
8323 } else if (e == 'SimulateInfiniteLoop') {
8324 // running an evented main loop, don't immediately exit
8325 Module['noExitRuntime'] = true;
8326 return;
8327 } else {
8328 if (e && typeof e === 'object' && e.stack) Module.printErr('exception thro wn: ' + [e, e.stack]);
8329 throw e;
8330 }
8331 } finally {
8332 calledMain = true;
8333 }
8334 }
8335
8336
8337
8338
8339 function run(args) {
8340 args = args || Module['arguments'];
8341
8342 if (preloadStartTime === null) preloadStartTime = Date.now();
8343
8344 if (runDependencies > 0) {
8345 Module.printErr('run() called, but dependencies remain, so not running');
8346 return;
8347 }
8348
8349 preRun();
8350
8351 if (runDependencies > 0) return; // a preRun added a dependency, run will be c alled later
8352 if (Module['calledRun']) return; // run may have just been called through depe ndencies being fulfilled just in this very frame
8353
8354 function doRun() {
8355 if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
8356 Module['calledRun'] = true;
8357
8358 ensureInitRuntime();
8359
8360 preMain();
8361
8362 if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
8363 Module.printErr('pre-main prep time: ' + (Date.now() - preloadStartTime) + ' ms');
8364 }
8365
8366 if (Module['_main'] && shouldRunNow) {
8367 Module['callMain'](args);
8368 }
8369
8370 postRun();
8371 }
8372
8373 if (Module['setStatus']) {
8374 Module['setStatus']('Running...');
8375 setTimeout(function() {
8376 setTimeout(function() {
8377 Module['setStatus']('');
8378 }, 1);
8379 if (!ABORT) doRun();
8380 }, 1);
8381 } else {
8382 doRun();
8383 }
8384 }
8385 Module['run'] = Module.run = run;
8386
8387 function exit(status) {
8388 ABORT = true;
8389 EXITSTATUS = status;
8390 STACKTOP = initialStackTop;
8391
8392 // exit the runtime
8393 exitRuntime();
8394
8395 // TODO We should handle this differently based on environment.
8396 // In the browser, the best we can do is throw an exception
8397 // to halt execution, but in node we could process.exit and
8398 // I'd imagine SM shell would have something equivalent.
8399 // This would let us set a proper exit status (which
8400 // would be great for checking test exit statuses).
8401 // https://github.com/kripken/emscripten/issues/1371
8402
8403 // throw an exception to halt the current execution
8404 throw new ExitStatus(status);
8405 }
8406 Module['exit'] = Module.exit = exit;
8407
8408 function abort(text) {
8409 if (text) {
8410 Module.print(text);
8411 Module.printErr(text);
8412 }
8413
8414 ABORT = true;
8415 EXITSTATUS = 1;
8416
8417 var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
8418
8419 throw 'abort() at ' + stackTrace() + extra;
8420 }
8421 Module['abort'] = Module.abort = abort;
8422
8423 // {{PRE_RUN_ADDITIONS}}
8424
8425 if (Module['preInit']) {
8426 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preIn it']];
8427 while (Module['preInit'].length > 0) {
8428 Module['preInit'].pop()();
8429 }
8430 }
8431
8432 // shouldRunNow refers to calling main(), not run().
8433 var shouldRunNow = true;
8434 if (Module['noInitialRun']) {
8435 shouldRunNow = false;
8436 }
8437
8438
8439 run([].concat(Module["arguments"]));
OLDNEW
« no previous file with comments | « test/mjsunit/asm/embenchen/corrections.js ('k') | test/mjsunit/asm/embenchen/fasta.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698