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