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