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