PageRenderTime 85ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/test/mjsunit/asm/embenchen/primes.js

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