PageRenderTime 44ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 2ms

/test/mjsunit/asm/embenchen/copy.js

http://v8.googlecode.com/
JavaScript | 5980 lines | 5052 code | 436 blank | 492 comment | 1295 complexity | d14fe9815c97ee7af1c46f6f360d7830 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 = 'sum:8930\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(27);
  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,115,117,109,58,37,100,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. 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};
  1278. 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"};
  1279. var ___errno_state=0;function ___setErrNo(value) {
  1280. // For convenient setting and returning of errno.
  1281. HEAP32[((___errno_state)>>2)]=value;
  1282. return value;
  1283. }
  1284. var TTY={ttys:[],init:function () {
  1285. // https://github.com/kripken/emscripten/pull/1555
  1286. // if (ENVIRONMENT_IS_NODE) {
  1287. // // currently, FS.init does not distinguish if process.stdin is a file or TTY
  1288. // // device, it always assumes it's a TTY device. because of this, we're forcing
  1289. // // process.stdin to UTF8 encoding to at least make stdin reading compatible
  1290. // // with text files until FS.init can be refactored.
  1291. // process['stdin']['setEncoding']('utf8');
  1292. // }
  1293. },shutdown:function () {
  1294. // https://github.com/kripken/emscripten/pull/1555
  1295. // if (ENVIRONMENT_IS_NODE) {
  1296. // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
  1297. // // 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
  1298. // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
  1299. // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
  1300. // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
  1301. // process['stdin']['pause']();
  1302. // }
  1303. },register:function (dev, ops) {
  1304. TTY.ttys[dev] = { input: [], output: [], ops: ops };
  1305. FS.registerDevice(dev, TTY.stream_ops);
  1306. },stream_ops:{open:function (stream) {
  1307. var tty = TTY.ttys[stream.node.rdev];
  1308. if (!tty) {
  1309. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  1310. }
  1311. stream.tty = tty;
  1312. stream.seekable = false;
  1313. },close:function (stream) {
  1314. // flush any pending line data
  1315. if (stream.tty.output.length) {
  1316. stream.tty.ops.put_char(stream.tty, 10);
  1317. }
  1318. },read:function (stream, buffer, offset, length, pos /* ignored */) {
  1319. if (!stream.tty || !stream.tty.ops.get_char) {
  1320. throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
  1321. }
  1322. var bytesRead = 0;
  1323. for (var i = 0; i < length; i++) {
  1324. var result;
  1325. try {
  1326. result = stream.tty.ops.get_char(stream.tty);
  1327. } catch (e) {
  1328. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  1329. }
  1330. if (result === undefined && bytesRead === 0) {
  1331. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  1332. }
  1333. if (result === null || result === undefined) break;
  1334. bytesRead++;
  1335. buffer[offset+i] = result;
  1336. }
  1337. if (bytesRead) {
  1338. stream.node.timestamp = Date.now();
  1339. }
  1340. return bytesRead;
  1341. },write:function (stream, buffer, offset, length, pos) {
  1342. if (!stream.tty || !stream.tty.ops.put_char) {
  1343. throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
  1344. }
  1345. for (var i = 0; i < length; i++) {
  1346. try {
  1347. stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
  1348. } catch (e) {
  1349. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  1350. }
  1351. }
  1352. if (length) {
  1353. stream.node.timestamp = Date.now();
  1354. }
  1355. return i;
  1356. }},default_tty_ops:{get_char:function (tty) {
  1357. if (!tty.input.length) {
  1358. var result = null;
  1359. if (ENVIRONMENT_IS_NODE) {
  1360. result = process['stdin']['read']();
  1361. if (!result) {
  1362. if (process['stdin']['_readableState'] && process['stdin']['_readableState']['ended']) {
  1363. return null; // EOF
  1364. }
  1365. return undefined; // no data available
  1366. }
  1367. } else if (typeof window != 'undefined' &&
  1368. typeof window.prompt == 'function') {
  1369. // Browser.
  1370. result = window.prompt('Input: '); // returns null on cancel
  1371. if (result !== null) {
  1372. result += '\n';
  1373. }
  1374. } else if (typeof readline == 'function') {
  1375. // Command line.
  1376. result = readline();
  1377. if (result !== null) {
  1378. result += '\n';
  1379. }
  1380. }
  1381. if (!result) {
  1382. return null;
  1383. }
  1384. tty.input = intArrayFromString(result, true);
  1385. }
  1386. return tty.input.shift();
  1387. },put_char:function (tty, val) {
  1388. if (val === null || val === 10) {
  1389. Module['print'](tty.output.join(''));
  1390. tty.output = [];
  1391. } else {
  1392. tty.output.push(TTY.utf8.processCChar(val));
  1393. }
  1394. }},default_tty1_ops:{put_char:function (tty, val) {
  1395. if (val === null || val === 10) {
  1396. Module['printErr'](tty.output.join(''));
  1397. tty.output = [];
  1398. } else {
  1399. tty.output.push(TTY.utf8.processCChar(val));
  1400. }
  1401. }}};
  1402. var MEMFS={ops_table:null,CONTENT_OWNING:1,CONTENT_FLEXIBLE:2,CONTENT_FIXED:3,mount:function (mount) {
  1403. return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  1404. },createNode:function (parent, name, mode, dev) {
  1405. if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
  1406. // no supported
  1407. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  1408. }
  1409. if (!MEMFS.ops_table) {
  1410. MEMFS.ops_table = {
  1411. dir: {
  1412. node: {
  1413. getattr: MEMFS.node_ops.getattr,
  1414. setattr: MEMFS.node_ops.setattr,
  1415. lookup: MEMFS.node_ops.lookup,
  1416. mknod: MEMFS.node_ops.mknod,
  1417. rename: MEMFS.node_ops.rename,
  1418. unlink: MEMFS.node_ops.unlink,
  1419. rmdir: MEMFS.node_ops.rmdir,
  1420. readdir: MEMFS.node_ops.readdir,
  1421. symlink: MEMFS.node_ops.symlink
  1422. },
  1423. stream: {
  1424. llseek: MEMFS.stream_ops.llseek
  1425. }
  1426. },
  1427. file: {
  1428. node: {
  1429. getattr: MEMFS.node_ops.getattr,
  1430. setattr: MEMFS.node_ops.setattr
  1431. },
  1432. stream: {
  1433. llseek: MEMFS.stream_ops.llseek,
  1434. read: MEMFS.stream_ops.read,
  1435. write: MEMFS.stream_ops.write,
  1436. allocate: MEMFS.stream_ops.allocate,
  1437. mmap: MEMFS.stream_ops.mmap
  1438. }
  1439. },
  1440. link: {
  1441. node: {
  1442. getattr: MEMFS.node_ops.getattr,
  1443. setattr: MEMFS.node_ops.setattr,
  1444. readlink: MEMFS.node_ops.readlink
  1445. },
  1446. stream: {}
  1447. },
  1448. chrdev: {
  1449. node: {
  1450. getattr: MEMFS.node_ops.getattr,
  1451. setattr: MEMFS.node_ops.setattr
  1452. },
  1453. stream: FS.chrdev_stream_ops
  1454. },
  1455. };
  1456. }
  1457. var node = FS.createNode(parent, name, mode, dev);
  1458. if (FS.isDir(node.mode)) {
  1459. node.node_ops = MEMFS.ops_table.dir.node;
  1460. node.stream_ops = MEMFS.ops_table.dir.stream;
  1461. node.contents = {};
  1462. } else if (FS.isFile(node.mode)) {
  1463. node.node_ops = MEMFS.ops_table.file.node;
  1464. node.stream_ops = MEMFS.ops_table.file.stream;
  1465. node.contents = [];
  1466. node.contentMode = MEMFS.CONTENT_FLEXIBLE;
  1467. } else if (FS.isLink(node.mode)) {
  1468. node.node_ops = MEMFS.ops_table.link.node;
  1469. node.stream_ops = MEMFS.ops_table.link.stream;
  1470. } else if (FS.isChrdev(node.mode)) {
  1471. node.node_ops = MEMFS.ops_table.chrdev.node;
  1472. node.stream_ops = MEMFS.ops_table.chrdev.stream;
  1473. }
  1474. node.timestamp = Date.now();
  1475. // add the new node to the parent
  1476. if (parent) {
  1477. parent.contents[name] = node;
  1478. }
  1479. return node;
  1480. },ensureFlexible:function (node) {
  1481. if (node.contentMode !== MEMFS.CONTENT_FLEXIBLE) {
  1482. var contents = node.contents;
  1483. node.contents = Array.prototype.slice.call(contents);
  1484. node.contentMode = MEMFS.CONTENT_FLEXIBLE;
  1485. }
  1486. },node_ops:{getattr:function (node) {
  1487. var attr = {};
  1488. // device numbers reuse inode numbers.
  1489. attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
  1490. attr.ino = node.id;
  1491. attr.mode = node.mode;
  1492. attr.nlink = 1;
  1493. attr.uid = 0;
  1494. attr.gid = 0;
  1495. attr.rdev = node.rdev;
  1496. if (FS.isDir(node.mode)) {
  1497. attr.size = 4096;
  1498. } else if (FS.isFile(node.mode)) {
  1499. attr.size = node.contents.length;
  1500. } else if (FS.isLink(node.mode)) {
  1501. attr.size = node.link.length;
  1502. } else {
  1503. attr.size = 0;
  1504. }
  1505. attr.atime = new Date(node.timestamp);
  1506. attr.mtime = new Date(node.timestamp);
  1507. attr.ctime = new Date(node.timestamp);
  1508. // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
  1509. // but this is not required by the standard.
  1510. attr.blksize = 4096;
  1511. attr.blocks = Math.ceil(attr.size / attr.blksize);
  1512. return attr;
  1513. },setattr:function (node, attr) {
  1514. if (attr.mode !== undefined) {
  1515. node.mode = attr.mode;
  1516. }
  1517. if (attr.timestamp !== undefined) {
  1518. node.timestamp = attr.timestamp;
  1519. }
  1520. if (attr.size !== undefined) {
  1521. MEMFS.ensureFlexible(node);
  1522. var contents = node.contents;
  1523. if (attr.size < contents.length) contents.length = attr.size;
  1524. else while (attr.size > contents.length) contents.push(0);
  1525. }
  1526. },lookup:function (parent, name) {
  1527. throw FS.genericErrors[ERRNO_CODES.ENOENT];
  1528. },mknod:function (parent, name, mode, dev) {
  1529. return MEMFS.createNode(parent, name, mode, dev);
  1530. },rename:function (old_node, new_dir, new_name) {
  1531. // if we're overwriting a directory at new_name, make sure it's empty.
  1532. if (FS.isDir(old_node.mode)) {
  1533. var new_node;
  1534. try {
  1535. new_node = FS.lookupNode(new_dir, new_name);
  1536. } catch (e) {
  1537. }
  1538. if (new_node) {
  1539. for (var i in new_node.contents) {
  1540. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  1541. }
  1542. }
  1543. }
  1544. // do the internal rewiring
  1545. delete old_node.parent.contents[old_node.name];
  1546. old_node.name = new_name;
  1547. new_dir.contents[new_name] = old_node;
  1548. old_node.parent = new_dir;
  1549. },unlink:function (parent, name) {
  1550. delete parent.contents[name];
  1551. },rmdir:function (parent, name) {
  1552. var node = FS.lookupNode(parent, name);
  1553. for (var i in node.contents) {
  1554. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  1555. }
  1556. delete parent.contents[name];
  1557. },readdir:function (node) {
  1558. var entries = ['.', '..']
  1559. for (var key in node.contents) {
  1560. if (!node.contents.hasOwnProperty(key)) {
  1561. continue;
  1562. }
  1563. entries.push(key);
  1564. }
  1565. return entries;
  1566. },symlink:function (parent, newname, oldpath) {
  1567. var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
  1568. node.link = oldpath;
  1569. return node;
  1570. },readlink:function (node) {
  1571. if (!FS.isLink(node.mode)) {
  1572. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  1573. }
  1574. return node.link;
  1575. }},stream_ops:{read:function (stream, buffer, offset, length, position) {
  1576. var contents = stream.node.contents;
  1577. if (position >= contents.length)
  1578. return 0;
  1579. var size = Math.min(contents.length - position, length);
  1580. assert(size >= 0);
  1581. if (size > 8 && contents.subarray) { // non-trivial, and typed array
  1582. buffer.set(contents.subarray(position, position + size), offset);
  1583. } else
  1584. {
  1585. for (var i = 0; i < size; i++) {
  1586. buffer[offset + i] = contents[position + i];
  1587. }
  1588. }
  1589. return size;
  1590. },write:function (stream, buffer, offset, length, position, canOwn) {
  1591. var node = stream.node;
  1592. node.timestamp = Date.now();
  1593. var contents = node.contents;
  1594. if (length && contents.length === 0 && position === 0 && buffer.subarray) {
  1595. // just replace it with the new data
  1596. if (canOwn && offset === 0) {
  1597. node.contents = buffer; // this could be a subarray of Emscripten HEAP, or allocated from some other source.
  1598. node.contentMode = (buffer.buffer === HEAP8.buffer) ? MEMFS.CONTENT_OWNING : MEMFS.CONTENT_FIXED;
  1599. } else {
  1600. node.contents = new Uint8Array(buffer.subarray(offset, offset+length));
  1601. node.contentMode = MEMFS.CONTENT_FIXED;
  1602. }
  1603. return length;
  1604. }
  1605. MEMFS.ensureFlexible(node);
  1606. var contents = node.contents;
  1607. while (contents.length < position) contents.push(0);
  1608. for (var i = 0; i < length; i++) {
  1609. contents[position + i] = buffer[offset + i];
  1610. }
  1611. return length;
  1612. },llseek:function (stream, offset, whence) {
  1613. var position = offset;
  1614. if (whence === 1) { // SEEK_CUR.
  1615. position += stream.position;
  1616. } else if (whence === 2) { // SEEK_END.
  1617. if (FS.isFile(stream.node.mode)) {
  1618. position += stream.node.contents.length;
  1619. }
  1620. }
  1621. if (position < 0) {
  1622. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  1623. }
  1624. stream.ungotten = [];
  1625. stream.position = position;
  1626. return position;
  1627. },allocate:function (stream, offset, length) {
  1628. MEMFS.ensureFlexible(stream.node);
  1629. var contents = stream.node.contents;
  1630. var limit = offset + length;
  1631. while (limit > contents.length) contents.push(0);
  1632. },mmap:function (stream, buffer, offset, length, position, prot, flags) {
  1633. if (!FS.isFile(stream.node.mode)) {
  1634. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  1635. }
  1636. var ptr;
  1637. var allocated;
  1638. var contents = stream.node.contents;
  1639. // Only make a new copy when MAP_PRIVATE is specified.
  1640. if ( !(flags & 2) &&
  1641. (contents.buffer === buffer || contents.buffer === buffer.buffer) ) {
  1642. // We can't emulate MAP_SHARED when the file is not backed by the buffer
  1643. // we're mapping to (e.g. the HEAP buffer).
  1644. allocated = false;
  1645. ptr = contents.byteOffset;
  1646. } else {
  1647. // Try to avoid unnecessary slices.
  1648. if (position > 0 || position + length < contents.length) {
  1649. if (contents.subarray) {
  1650. contents = contents.subarray(position, position + length);
  1651. } else {
  1652. contents = Array.prototype.slice.call(contents, position, position + length);
  1653. }
  1654. }
  1655. allocated = true;
  1656. ptr = _malloc(length);
  1657. if (!ptr) {
  1658. throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
  1659. }
  1660. buffer.set(contents, ptr);
  1661. }
  1662. return { ptr: ptr, allocated: allocated };
  1663. }}};
  1664. var IDBFS={dbs:{},indexedDB:function () {
  1665. return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  1666. },DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function (mount) {
  1667. // reuse all of the core MEMFS functionality
  1668. return MEMFS.mount.apply(null, arguments);
  1669. },syncfs:function (mount, populate, callback) {
  1670. IDBFS.getLocalSet(mount, function(err, local) {
  1671. if (err) return callback(err);
  1672. IDBFS.getRemoteSet(mount, function(err, remote) {
  1673. if (err) return callback(err);
  1674. var src = populate ? remote : local;
  1675. var dst = populate ? local : remote;
  1676. IDBFS.reconcile(src, dst, callback);
  1677. });
  1678. });
  1679. },getDB:function (name, callback) {
  1680. // check the cache first
  1681. var db = IDBFS.dbs[name];
  1682. if (db) {
  1683. return callback(null, db);
  1684. }
  1685. var req;
  1686. try {
  1687. req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
  1688. } catch (e) {
  1689. return callback(e);
  1690. }
  1691. req.onupgradeneeded = function(e) {
  1692. var db = e.target.result;
  1693. var transaction = e.target.transaction;
  1694. var fileStore;
  1695. if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
  1696. fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
  1697. } else {
  1698. fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
  1699. }
  1700. fileStore.createIndex('timestamp', 'timestamp', { unique: false });
  1701. };
  1702. req.onsuccess = function() {
  1703. db = req.result;
  1704. // add to the cache
  1705. IDBFS.dbs[name] = db;
  1706. callback(null, db);
  1707. };
  1708. req.onerror = function() {
  1709. callback(this.error);
  1710. };
  1711. },getLocalSet:function (mount, callback) {
  1712. var entries = {};
  1713. function isRealDir(p) {
  1714. return p !== '.' && p !== '..';
  1715. };
  1716. function toAbsolute(root) {
  1717. return function(p) {
  1718. return PATH.join2(root, p);
  1719. }
  1720. };
  1721. var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
  1722. while (check.length) {
  1723. var path = check.pop();
  1724. var stat;
  1725. try {
  1726. stat = FS.stat(path);
  1727. } catch (e) {
  1728. return callback(e);
  1729. }
  1730. if (FS.isDir(stat.mode)) {
  1731. check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
  1732. }
  1733. entries[path] = { timestamp: stat.mtime };
  1734. }
  1735. return callback(null, { type: 'local', entries: entries });
  1736. },getRemoteSet:function (mount, callback) {
  1737. var entries = {};
  1738. IDBFS.getDB(mount.mountpoint, function(err, db) {
  1739. if (err) return callback(err);
  1740. var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
  1741. transaction.onerror = function() { callback(this.error); };
  1742. var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
  1743. var index = store.index('timestamp');
  1744. index.openKeyCursor().onsuccess = function(event) {
  1745. var cursor = event.target.result;
  1746. if (!cursor) {
  1747. return callback(null, { type: 'remote', db: db, entries: entries });
  1748. }
  1749. entries[cursor.primaryKey] = { timestamp: cursor.key };
  1750. cursor.continue();
  1751. };
  1752. });
  1753. },loadLocalEntry:function (path, callback) {
  1754. var stat, node;
  1755. try {
  1756. var lookup = FS.lookupPath(path);
  1757. node = lookup.node;
  1758. stat = FS.stat(path);
  1759. } catch (e) {
  1760. return callback(e);
  1761. }
  1762. if (FS.isDir(stat.mode)) {
  1763. return callback(null, { timestamp: stat.mtime, mode: stat.mode });
  1764. } else if (FS.isFile(stat.mode)) {
  1765. return callback(null, { timestamp: stat.mtime, mode: stat.mode, contents: node.contents });
  1766. } else {
  1767. return callback(new Error('node type not supported'));
  1768. }
  1769. },storeLocalEntry:function (path, entry, callback) {
  1770. try {
  1771. if (FS.isDir(entry.mode)) {
  1772. FS.mkdir(path, entry.mode);
  1773. } else if (FS.isFile(entry.mode)) {
  1774. FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: true });
  1775. } else {
  1776. return callback(new Error('node type not supported'));
  1777. }
  1778. FS.utime(path, entry.timestamp, entry.timestamp);
  1779. } catch (e) {
  1780. return callback(e);
  1781. }
  1782. callback(null);
  1783. },removeLocalEntry:function (path, callback) {
  1784. try {
  1785. var lookup = FS.lookupPath(path);
  1786. var stat = FS.stat(path);
  1787. if (FS.isDir(stat.mode)) {
  1788. FS.rmdir(path);
  1789. } else if (FS.isFile(stat.mode)) {
  1790. FS.unlink(path);
  1791. }
  1792. } catch (e) {
  1793. return callback(e);
  1794. }
  1795. callback(null);
  1796. },loadRemoteEntry:function (store, path, callback) {
  1797. var req = store.get(path);
  1798. req.onsuccess = function(event) { callback(null, event.target.result); };
  1799. req.onerror = function() { callback(this.error); };
  1800. },storeRemoteEntry:function (store, path, entry, callback) {
  1801. var req = store.put(entry, path);
  1802. req.onsuccess = function() { callback(null); };
  1803. req.onerror = function() { callback(this.error); };
  1804. },removeRemoteEntry:function (store, path, callback) {
  1805. var req = store.delete(path);
  1806. req.onsuccess = function() { callback(null); };
  1807. req.onerror = function() { callback(this.error); };
  1808. },reconcile:function (src, dst, callback) {
  1809. var total = 0;
  1810. var create = [];
  1811. Object.keys(src.entries).forEach(function (key) {
  1812. var e = src.entries[key];
  1813. var e2 = dst.entries[key];
  1814. if (!e2 || e.timestamp > e2.timestamp) {
  1815. create.push(key);
  1816. total++;
  1817. }
  1818. });
  1819. var remove = [];
  1820. Object.keys(dst.entries).forEach(function (key) {
  1821. var e = dst.entries[key];
  1822. var e2 = src.entries[key];
  1823. if (!e2) {
  1824. remove.push(key);
  1825. total++;
  1826. }
  1827. });
  1828. if (!total) {
  1829. return callback(null);
  1830. }
  1831. var errored = false;
  1832. var completed = 0;
  1833. var db = src.type === 'remote' ? src.db : dst.db;
  1834. var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
  1835. var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
  1836. function done(err) {
  1837. if (err) {
  1838. if (!done.errored) {
  1839. done.errored = true;
  1840. return callback(err);
  1841. }
  1842. return;
  1843. }
  1844. if (++completed >= total) {
  1845. return callback(null);
  1846. }
  1847. };
  1848. transaction.onerror = function() { done(this.error); };
  1849. // sort paths in ascending order so directory entries are created
  1850. // before the files inside them
  1851. create.sort().forEach(function (path) {
  1852. if (dst.type === 'local') {
  1853. IDBFS.loadRemoteEntry(store, path, function (err, entry) {
  1854. if (err) return done(err);
  1855. IDBFS.storeLocalEntry(path, entry, done);
  1856. });
  1857. } else {
  1858. IDBFS.loadLocalEntry(path, function (err, entry) {
  1859. if (err) return done(err);
  1860. IDBFS.storeRemoteEntry(store, path, entry, done);
  1861. });
  1862. }
  1863. });
  1864. // sort paths in descending order so files are deleted before their
  1865. // parent directories
  1866. remove.sort().reverse().forEach(function(path) {
  1867. if (dst.type === 'local') {
  1868. IDBFS.removeLocalEntry(path, done);
  1869. } else {
  1870. IDBFS.removeRemoteEntry(store, path, done);
  1871. }
  1872. });
  1873. }};
  1874. var NODEFS={isWindows:false,staticInit:function () {
  1875. NODEFS.isWindows = !!process.platform.match(/^win/);
  1876. },mount:function (mount) {
  1877. assert(ENVIRONMENT_IS_NODE);
  1878. return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
  1879. },createNode:function (parent, name, mode, dev) {
  1880. if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
  1881. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  1882. }
  1883. var node = FS.createNode(parent, name, mode);
  1884. node.node_ops = NODEFS.node_ops;
  1885. node.stream_ops = NODEFS.stream_ops;
  1886. return node;
  1887. },getMode:function (path) {
  1888. var stat;
  1889. try {
  1890. stat = fs.lstatSync(path);
  1891. if (NODEFS.isWindows) {
  1892. // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
  1893. // propagate write bits to execute bits.
  1894. stat.mode = stat.mode | ((stat.mode & 146) >> 1);
  1895. }
  1896. } catch (e) {
  1897. if (!e.code) throw e;
  1898. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  1899. }
  1900. return stat.mode;
  1901. },realPath:function (node) {
  1902. var parts = [];
  1903. while (node.parent !== node) {
  1904. parts.push(node.name);
  1905. node = node.parent;
  1906. }
  1907. parts.push(node.mount.opts.root);
  1908. parts.reverse();
  1909. return PATH.join.apply(null, parts);
  1910. },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) {
  1911. if (flags in NODEFS.flagsToPermissionStringMap) {
  1912. return NODEFS.flagsToPermissionStringMap[flags];
  1913. } else {
  1914. return flags;
  1915. }
  1916. },node_ops:{getattr:function (node) {
  1917. var path = NODEFS.realPath(node);
  1918. var stat;
  1919. try {
  1920. stat = fs.lstatSync(path);
  1921. } catch (e) {
  1922. if (!e.code) throw e;
  1923. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  1924. }
  1925. // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
  1926. // See http://support.microsoft.com/kb/140365
  1927. if (NODEFS.isWindows && !stat.blksize) {
  1928. stat.blksize = 4096;
  1929. }
  1930. if (NODEFS.isWindows && !stat.blocks) {
  1931. stat.blocks = (stat.size+stat.blksize-1)/stat.blksize|0;
  1932. }
  1933. return {
  1934. dev: stat.dev,
  1935. ino: stat.ino,
  1936. mode: stat.mode,
  1937. nlink: stat.nlink,
  1938. uid: stat.uid,
  1939. gid: stat.gid,
  1940. rdev: stat.rdev,
  1941. size: stat.size,
  1942. atime: stat.atime,
  1943. mtime: stat.mtime,
  1944. ctime: stat.ctime,
  1945. blksize: stat.blksize,
  1946. blocks: stat.blocks
  1947. };
  1948. },setattr:function (node, attr) {
  1949. var path = NODEFS.realPath(node);
  1950. try {
  1951. if (attr.mode !== undefined) {
  1952. fs.chmodSync(path, attr.mode);
  1953. // update the common node structure mode as well
  1954. node.mode = attr.mode;
  1955. }
  1956. if (attr.timestamp !== undefined) {
  1957. var date = new Date(attr.timestamp);
  1958. fs.utimesSync(path, date, date);
  1959. }
  1960. if (attr.size !== undefined) {
  1961. fs.truncateSync(path, attr.size);
  1962. }
  1963. } catch (e) {
  1964. if (!e.code) throw e;
  1965. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  1966. }
  1967. },lookup:function (parent, name) {
  1968. var path = PATH.join2(NODEFS.realPath(parent), name);
  1969. var mode = NODEFS.getMode(path);
  1970. return NODEFS.createNode(parent, name, mode);
  1971. },mknod:function (parent, name, mode, dev) {
  1972. var node = NODEFS.createNode(parent, name, mode, dev);
  1973. // create the backing node for this in the fs root as well
  1974. var path = NODEFS.realPath(node);
  1975. try {
  1976. if (FS.isDir(node.mode)) {
  1977. fs.mkdirSync(path, node.mode);
  1978. } else {
  1979. fs.writeFileSync(path, '', { mode: node.mode });
  1980. }
  1981. } catch (e) {
  1982. if (!e.code) throw e;
  1983. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  1984. }
  1985. return node;
  1986. },rename:function (oldNode, newDir, newName) {
  1987. var oldPath = NODEFS.realPath(oldNode);
  1988. var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
  1989. try {
  1990. fs.renameSync(oldPath, newPath);
  1991. } catch (e) {
  1992. if (!e.code) throw e;
  1993. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  1994. }
  1995. },unlink:function (parent, name) {
  1996. var path = PATH.join2(NODEFS.realPath(parent), name);
  1997. try {
  1998. fs.unlinkSync(path);
  1999. } catch (e) {
  2000. if (!e.code) throw e;
  2001. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2002. }
  2003. },rmdir:function (parent, name) {
  2004. var path = PATH.join2(NODEFS.realPath(parent), name);
  2005. try {
  2006. fs.rmdirSync(path);
  2007. } catch (e) {
  2008. if (!e.code) throw e;
  2009. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2010. }
  2011. },readdir:function (node) {
  2012. var path = NODEFS.realPath(node);
  2013. try {
  2014. return fs.readdirSync(path);
  2015. } catch (e) {
  2016. if (!e.code) throw e;
  2017. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2018. }
  2019. },symlink:function (parent, newName, oldPath) {
  2020. var newPath = PATH.join2(NODEFS.realPath(parent), newName);
  2021. try {
  2022. fs.symlinkSync(oldPath, newPath);
  2023. } catch (e) {
  2024. if (!e.code) throw e;
  2025. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2026. }
  2027. },readlink:function (node) {
  2028. var path = NODEFS.realPath(node);
  2029. try {
  2030. return fs.readlinkSync(path);
  2031. } catch (e) {
  2032. if (!e.code) throw e;
  2033. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2034. }
  2035. }},stream_ops:{open:function (stream) {
  2036. var path = NODEFS.realPath(stream.node);
  2037. try {
  2038. if (FS.isFile(stream.node.mode)) {
  2039. stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
  2040. }
  2041. } catch (e) {
  2042. if (!e.code) throw e;
  2043. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2044. }
  2045. },close:function (stream) {
  2046. try {
  2047. if (FS.isFile(stream.node.mode) && stream.nfd) {
  2048. fs.closeSync(stream.nfd);
  2049. }
  2050. } catch (e) {
  2051. if (!e.code) throw e;
  2052. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2053. }
  2054. },read:function (stream, buffer, offset, length, position) {
  2055. // FIXME this is terrible.
  2056. var nbuffer = new Buffer(length);
  2057. var res;
  2058. try {
  2059. res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
  2060. } catch (e) {
  2061. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2062. }
  2063. if (res > 0) {
  2064. for (var i = 0; i < res; i++) {
  2065. buffer[offset + i] = nbuffer[i];
  2066. }
  2067. }
  2068. return res;
  2069. },write:function (stream, buffer, offset, length, position) {
  2070. // FIXME this is terrible.
  2071. var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
  2072. var res;
  2073. try {
  2074. res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
  2075. } catch (e) {
  2076. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2077. }
  2078. return res;
  2079. },llseek:function (stream, offset, whence) {
  2080. var position = offset;
  2081. if (whence === 1) { // SEEK_CUR.
  2082. position += stream.position;
  2083. } else if (whence === 2) { // SEEK_END.
  2084. if (FS.isFile(stream.node.mode)) {
  2085. try {
  2086. var stat = fs.fstatSync(stream.nfd);
  2087. position += stat.size;
  2088. } catch (e) {
  2089. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  2090. }
  2091. }
  2092. }
  2093. if (position < 0) {
  2094. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2095. }
  2096. stream.position = position;
  2097. return position;
  2098. }}};
  2099. var _stdin=allocate(1, "i32*", ALLOC_STATIC);
  2100. var _stdout=allocate(1, "i32*", ALLOC_STATIC);
  2101. var _stderr=allocate(1, "i32*", ALLOC_STATIC);
  2102. function _fflush(stream) {
  2103. // int fflush(FILE *stream);
  2104. // http://pubs.opengroup.org/onlinepubs/000095399/functions/fflush.html
  2105. // we don't currently perform any user-space buffering of data
  2106. }var FS={root:null,mounts:[],devices:[null],streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},handleFSError:function (e) {
  2107. if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
  2108. return ___setErrNo(e.errno);
  2109. },lookupPath:function (path, opts) {
  2110. path = PATH.resolve(FS.cwd(), path);
  2111. opts = opts || {};
  2112. var defaults = {
  2113. follow_mount: true,
  2114. recurse_count: 0
  2115. };
  2116. for (var key in defaults) {
  2117. if (opts[key] === undefined) {
  2118. opts[key] = defaults[key];
  2119. }
  2120. }
  2121. if (opts.recurse_count > 8) { // max recursive lookup of 8
  2122. throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
  2123. }
  2124. // split the path
  2125. var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
  2126. return !!p;
  2127. }), false);
  2128. // start at the root
  2129. var current = FS.root;
  2130. var current_path = '/';
  2131. for (var i = 0; i < parts.length; i++) {
  2132. var islast = (i === parts.length-1);
  2133. if (islast && opts.parent) {
  2134. // stop resolving
  2135. break;
  2136. }
  2137. current = FS.lookupNode(current, parts[i]);
  2138. current_path = PATH.join2(current_path, parts[i]);
  2139. // jump to the mount's root node if this is a mountpoint
  2140. if (FS.isMountpoint(current)) {
  2141. if (!islast || (islast && opts.follow_mount)) {
  2142. current = current.mounted.root;
  2143. }
  2144. }
  2145. // by default, lookupPath will not follow a symlink if it is the final path component.
  2146. // setting opts.follow = true will override this behavior.
  2147. if (!islast || opts.follow) {
  2148. var count = 0;
  2149. while (FS.isLink(current.mode)) {
  2150. var link = FS.readlink(current_path);
  2151. current_path = PATH.resolve(PATH.dirname(current_path), link);
  2152. var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
  2153. current = lookup.node;
  2154. if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
  2155. throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
  2156. }
  2157. }
  2158. }
  2159. }
  2160. return { path: current_path, node: current };
  2161. },getPath:function (node) {
  2162. var path;
  2163. while (true) {
  2164. if (FS.isRoot(node)) {
  2165. var mount = node.mount.mountpoint;
  2166. if (!path) return mount;
  2167. return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
  2168. }
  2169. path = path ? node.name + '/' + path : node.name;
  2170. node = node.parent;
  2171. }
  2172. },hashName:function (parentid, name) {
  2173. var hash = 0;
  2174. for (var i = 0; i < name.length; i++) {
  2175. hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
  2176. }
  2177. return ((parentid + hash) >>> 0) % FS.nameTable.length;
  2178. },hashAddNode:function (node) {
  2179. var hash = FS.hashName(node.parent.id, node.name);
  2180. node.name_next = FS.nameTable[hash];
  2181. FS.nameTable[hash] = node;
  2182. },hashRemoveNode:function (node) {
  2183. var hash = FS.hashName(node.parent.id, node.name);
  2184. if (FS.nameTable[hash] === node) {
  2185. FS.nameTable[hash] = node.name_next;
  2186. } else {
  2187. var current = FS.nameTable[hash];
  2188. while (current) {
  2189. if (current.name_next === node) {
  2190. current.name_next = node.name_next;
  2191. break;
  2192. }
  2193. current = current.name_next;
  2194. }
  2195. }
  2196. },lookupNode:function (parent, name) {
  2197. var err = FS.mayLookup(parent);
  2198. if (err) {
  2199. throw new FS.ErrnoError(err);
  2200. }
  2201. var hash = FS.hashName(parent.id, name);
  2202. for (var node = FS.nameTable[hash]; node; node = node.name_next) {
  2203. var nodeName = node.name;
  2204. if (node.parent.id === parent.id && nodeName === name) {
  2205. return node;
  2206. }
  2207. }
  2208. // if we failed to find it in the cache, call into the VFS
  2209. return FS.lookup(parent, name);
  2210. },createNode:function (parent, name, mode, rdev) {
  2211. if (!FS.FSNode) {
  2212. FS.FSNode = function(parent, name, mode, rdev) {
  2213. if (!parent) {
  2214. parent = this; // root node sets parent to itself
  2215. }
  2216. this.parent = parent;
  2217. this.mount = parent.mount;
  2218. this.mounted = null;
  2219. this.id = FS.nextInode++;
  2220. this.name = name;
  2221. this.mode = mode;
  2222. this.node_ops = {};
  2223. this.stream_ops = {};
  2224. this.rdev = rdev;
  2225. };
  2226. FS.FSNode.prototype = {};
  2227. // compatibility
  2228. var readMode = 292 | 73;
  2229. var writeMode = 146;
  2230. // NOTE we must use Object.defineProperties instead of individual calls to
  2231. // Object.defineProperty in order to make closure compiler happy
  2232. Object.defineProperties(FS.FSNode.prototype, {
  2233. read: {
  2234. get: function() { return (this.mode & readMode) === readMode; },
  2235. set: function(val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
  2236. },
  2237. write: {
  2238. get: function() { return (this.mode & writeMode) === writeMode; },
  2239. set: function(val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
  2240. },
  2241. isFolder: {
  2242. get: function() { return FS.isDir(this.mode); },
  2243. },
  2244. isDevice: {
  2245. get: function() { return FS.isChrdev(this.mode); },
  2246. },
  2247. });
  2248. }
  2249. var node = new FS.FSNode(parent, name, mode, rdev);
  2250. FS.hashAddNode(node);
  2251. return node;
  2252. },destroyNode:function (node) {
  2253. FS.hashRemoveNode(node);
  2254. },isRoot:function (node) {
  2255. return node === node.parent;
  2256. },isMountpoint:function (node) {
  2257. return !!node.mounted;
  2258. },isFile:function (mode) {
  2259. return (mode & 61440) === 32768;
  2260. },isDir:function (mode) {
  2261. return (mode & 61440) === 16384;
  2262. },isLink:function (mode) {
  2263. return (mode & 61440) === 40960;
  2264. },isChrdev:function (mode) {
  2265. return (mode & 61440) === 8192;
  2266. },isBlkdev:function (mode) {
  2267. return (mode & 61440) === 24576;
  2268. },isFIFO:function (mode) {
  2269. return (mode & 61440) === 4096;
  2270. },isSocket:function (mode) {
  2271. return (mode & 49152) === 49152;
  2272. },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) {
  2273. var flags = FS.flagModes[str];
  2274. if (typeof flags === 'undefined') {
  2275. throw new Error('Unknown file open mode: ' + str);
  2276. }
  2277. return flags;
  2278. },flagsToPermissionString:function (flag) {
  2279. var accmode = flag & 2097155;
  2280. var perms = ['r', 'w', 'rw'][accmode];
  2281. if ((flag & 512)) {
  2282. perms += 'w';
  2283. }
  2284. return perms;
  2285. },nodePermissions:function (node, perms) {
  2286. if (FS.ignorePermissions) {
  2287. return 0;
  2288. }
  2289. // return 0 if any user, group or owner bits are set.
  2290. if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
  2291. return ERRNO_CODES.EACCES;
  2292. } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
  2293. return ERRNO_CODES.EACCES;
  2294. } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
  2295. return ERRNO_CODES.EACCES;
  2296. }
  2297. return 0;
  2298. },mayLookup:function (dir) {
  2299. return FS.nodePermissions(dir, 'x');
  2300. },mayCreate:function (dir, name) {
  2301. try {
  2302. var node = FS.lookupNode(dir, name);
  2303. return ERRNO_CODES.EEXIST;
  2304. } catch (e) {
  2305. }
  2306. return FS.nodePermissions(dir, 'wx');
  2307. },mayDelete:function (dir, name, isdir) {
  2308. var node;
  2309. try {
  2310. node = FS.lookupNode(dir, name);
  2311. } catch (e) {
  2312. return e.errno;
  2313. }
  2314. var err = FS.nodePermissions(dir, 'wx');
  2315. if (err) {
  2316. return err;
  2317. }
  2318. if (isdir) {
  2319. if (!FS.isDir(node.mode)) {
  2320. return ERRNO_CODES.ENOTDIR;
  2321. }
  2322. if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
  2323. return ERRNO_CODES.EBUSY;
  2324. }
  2325. } else {
  2326. if (FS.isDir(node.mode)) {
  2327. return ERRNO_CODES.EISDIR;
  2328. }
  2329. }
  2330. return 0;
  2331. },mayOpen:function (node, flags) {
  2332. if (!node) {
  2333. return ERRNO_CODES.ENOENT;
  2334. }
  2335. if (FS.isLink(node.mode)) {
  2336. return ERRNO_CODES.ELOOP;
  2337. } else if (FS.isDir(node.mode)) {
  2338. if ((flags & 2097155) !== 0 || // opening for write
  2339. (flags & 512)) {
  2340. return ERRNO_CODES.EISDIR;
  2341. }
  2342. }
  2343. return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
  2344. },MAX_OPEN_FDS:4096,nextfd:function (fd_start, fd_end) {
  2345. fd_start = fd_start || 0;
  2346. fd_end = fd_end || FS.MAX_OPEN_FDS;
  2347. for (var fd = fd_start; fd <= fd_end; fd++) {
  2348. if (!FS.streams[fd]) {
  2349. return fd;
  2350. }
  2351. }
  2352. throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
  2353. },getStream:function (fd) {
  2354. return FS.streams[fd];
  2355. },createStream:function (stream, fd_start, fd_end) {
  2356. if (!FS.FSStream) {
  2357. FS.FSStream = function(){};
  2358. FS.FSStream.prototype = {};
  2359. // compatibility
  2360. Object.defineProperties(FS.FSStream.prototype, {
  2361. object: {
  2362. get: function() { return this.node; },
  2363. set: function(val) { this.node = val; }
  2364. },
  2365. isRead: {
  2366. get: function() { return (this.flags & 2097155) !== 1; }
  2367. },
  2368. isWrite: {
  2369. get: function() { return (this.flags & 2097155) !== 0; }
  2370. },
  2371. isAppend: {
  2372. get: function() { return (this.flags & 1024); }
  2373. }
  2374. });
  2375. }
  2376. if (0) {
  2377. // reuse the object
  2378. stream.__proto__ = FS.FSStream.prototype;
  2379. } else {
  2380. var newStream = new FS.FSStream();
  2381. for (var p in stream) {
  2382. newStream[p] = stream[p];
  2383. }
  2384. stream = newStream;
  2385. }
  2386. var fd = FS.nextfd(fd_start, fd_end);
  2387. stream.fd = fd;
  2388. FS.streams[fd] = stream;
  2389. return stream;
  2390. },closeStream:function (fd) {
  2391. FS.streams[fd] = null;
  2392. },getStreamFromPtr:function (ptr) {
  2393. return FS.streams[ptr - 1];
  2394. },getPtrForStream:function (stream) {
  2395. return stream ? stream.fd + 1 : 0;
  2396. },chrdev_stream_ops:{open:function (stream) {
  2397. var device = FS.getDevice(stream.node.rdev);
  2398. // override node's stream ops with the device's
  2399. stream.stream_ops = device.stream_ops;
  2400. // forward the open call
  2401. if (stream.stream_ops.open) {
  2402. stream.stream_ops.open(stream);
  2403. }
  2404. },llseek:function () {
  2405. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  2406. }},major:function (dev) {
  2407. return ((dev) >> 8);
  2408. },minor:function (dev) {
  2409. return ((dev) & 0xff);
  2410. },makedev:function (ma, mi) {
  2411. return ((ma) << 8 | (mi));
  2412. },registerDevice:function (dev, ops) {
  2413. FS.devices[dev] = { stream_ops: ops };
  2414. },getDevice:function (dev) {
  2415. return FS.devices[dev];
  2416. },getMounts:function (mount) {
  2417. var mounts = [];
  2418. var check = [mount];
  2419. while (check.length) {
  2420. var m = check.pop();
  2421. mounts.push(m);
  2422. check.push.apply(check, m.mounts);
  2423. }
  2424. return mounts;
  2425. },syncfs:function (populate, callback) {
  2426. if (typeof(populate) === 'function') {
  2427. callback = populate;
  2428. populate = false;
  2429. }
  2430. var mounts = FS.getMounts(FS.root.mount);
  2431. var completed = 0;
  2432. function done(err) {
  2433. if (err) {
  2434. if (!done.errored) {
  2435. done.errored = true;
  2436. return callback(err);
  2437. }
  2438. return;
  2439. }
  2440. if (++completed >= mounts.length) {
  2441. callback(null);
  2442. }
  2443. };
  2444. // sync all mounts
  2445. mounts.forEach(function (mount) {
  2446. if (!mount.type.syncfs) {
  2447. return done(null);
  2448. }
  2449. mount.type.syncfs(mount, populate, done);
  2450. });
  2451. },mount:function (type, opts, mountpoint) {
  2452. var root = mountpoint === '/';
  2453. var pseudo = !mountpoint;
  2454. var node;
  2455. if (root && FS.root) {
  2456. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2457. } else if (!root && !pseudo) {
  2458. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2459. mountpoint = lookup.path; // use the absolute path
  2460. node = lookup.node;
  2461. if (FS.isMountpoint(node)) {
  2462. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2463. }
  2464. if (!FS.isDir(node.mode)) {
  2465. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  2466. }
  2467. }
  2468. var mount = {
  2469. type: type,
  2470. opts: opts,
  2471. mountpoint: mountpoint,
  2472. mounts: []
  2473. };
  2474. // create a root node for the fs
  2475. var mountRoot = type.mount(mount);
  2476. mountRoot.mount = mount;
  2477. mount.root = mountRoot;
  2478. if (root) {
  2479. FS.root = mountRoot;
  2480. } else if (node) {
  2481. // set as a mountpoint
  2482. node.mounted = mount;
  2483. // add the new mount to the current mount's children
  2484. if (node.mount) {
  2485. node.mount.mounts.push(mount);
  2486. }
  2487. }
  2488. return mountRoot;
  2489. },unmount:function (mountpoint) {
  2490. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2491. if (!FS.isMountpoint(lookup.node)) {
  2492. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2493. }
  2494. // destroy the nodes for this mount, and all its child mounts
  2495. var node = lookup.node;
  2496. var mount = node.mounted;
  2497. var mounts = FS.getMounts(mount);
  2498. Object.keys(FS.nameTable).forEach(function (hash) {
  2499. var current = FS.nameTable[hash];
  2500. while (current) {
  2501. var next = current.name_next;
  2502. if (mounts.indexOf(current.mount) !== -1) {
  2503. FS.destroyNode(current);
  2504. }
  2505. current = next;
  2506. }
  2507. });
  2508. // no longer a mountpoint
  2509. node.mounted = null;
  2510. // remove this mount from the child mounts
  2511. var idx = node.mount.mounts.indexOf(mount);
  2512. assert(idx !== -1);
  2513. node.mount.mounts.splice(idx, 1);
  2514. },lookup:function (parent, name) {
  2515. return parent.node_ops.lookup(parent, name);
  2516. },mknod:function (path, mode, dev) {
  2517. var lookup = FS.lookupPath(path, { parent: true });
  2518. var parent = lookup.node;
  2519. var name = PATH.basename(path);
  2520. var err = FS.mayCreate(parent, name);
  2521. if (err) {
  2522. throw new FS.ErrnoError(err);
  2523. }
  2524. if (!parent.node_ops.mknod) {
  2525. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2526. }
  2527. return parent.node_ops.mknod(parent, name, mode, dev);
  2528. },create:function (path, mode) {
  2529. mode = mode !== undefined ? mode : 438 /* 0666 */;
  2530. mode &= 4095;
  2531. mode |= 32768;
  2532. return FS.mknod(path, mode, 0);
  2533. },mkdir:function (path, mode) {
  2534. mode = mode !== undefined ? mode : 511 /* 0777 */;
  2535. mode &= 511 | 512;
  2536. mode |= 16384;
  2537. return FS.mknod(path, mode, 0);
  2538. },mkdev:function (path, mode, dev) {
  2539. if (typeof(dev) === 'undefined') {
  2540. dev = mode;
  2541. mode = 438 /* 0666 */;
  2542. }
  2543. mode |= 8192;
  2544. return FS.mknod(path, mode, dev);
  2545. },symlink:function (oldpath, newpath) {
  2546. var lookup = FS.lookupPath(newpath, { parent: true });
  2547. var parent = lookup.node;
  2548. var newname = PATH.basename(newpath);
  2549. var err = FS.mayCreate(parent, newname);
  2550. if (err) {
  2551. throw new FS.ErrnoError(err);
  2552. }
  2553. if (!parent.node_ops.symlink) {
  2554. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2555. }
  2556. return parent.node_ops.symlink(parent, newname, oldpath);
  2557. },rename:function (old_path, new_path) {
  2558. var old_dirname = PATH.dirname(old_path);
  2559. var new_dirname = PATH.dirname(new_path);
  2560. var old_name = PATH.basename(old_path);
  2561. var new_name = PATH.basename(new_path);
  2562. // parents must exist
  2563. var lookup, old_dir, new_dir;
  2564. try {
  2565. lookup = FS.lookupPath(old_path, { parent: true });
  2566. old_dir = lookup.node;
  2567. lookup = FS.lookupPath(new_path, { parent: true });
  2568. new_dir = lookup.node;
  2569. } catch (e) {
  2570. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2571. }
  2572. // need to be part of the same mount
  2573. if (old_dir.mount !== new_dir.mount) {
  2574. throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
  2575. }
  2576. // source must exist
  2577. var old_node = FS.lookupNode(old_dir, old_name);
  2578. // old path should not be an ancestor of the new path
  2579. var relative = PATH.relative(old_path, new_dirname);
  2580. if (relative.charAt(0) !== '.') {
  2581. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2582. }
  2583. // new path should not be an ancestor of the old path
  2584. relative = PATH.relative(new_path, old_dirname);
  2585. if (relative.charAt(0) !== '.') {
  2586. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  2587. }
  2588. // see if the new path already exists
  2589. var new_node;
  2590. try {
  2591. new_node = FS.lookupNode(new_dir, new_name);
  2592. } catch (e) {
  2593. // not fatal
  2594. }
  2595. // early out if nothing needs to change
  2596. if (old_node === new_node) {
  2597. return;
  2598. }
  2599. // we'll need to delete the old entry
  2600. var isdir = FS.isDir(old_node.mode);
  2601. var err = FS.mayDelete(old_dir, old_name, isdir);
  2602. if (err) {
  2603. throw new FS.ErrnoError(err);
  2604. }
  2605. // need delete permissions if we'll be overwriting.
  2606. // need create permissions if new doesn't already exist.
  2607. err = new_node ?
  2608. FS.mayDelete(new_dir, new_name, isdir) :
  2609. FS.mayCreate(new_dir, new_name);
  2610. if (err) {
  2611. throw new FS.ErrnoError(err);
  2612. }
  2613. if (!old_dir.node_ops.rename) {
  2614. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2615. }
  2616. if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
  2617. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2618. }
  2619. // if we are going to change the parent, check write permissions
  2620. if (new_dir !== old_dir) {
  2621. err = FS.nodePermissions(old_dir, 'w');
  2622. if (err) {
  2623. throw new FS.ErrnoError(err);
  2624. }
  2625. }
  2626. // remove the node from the lookup hash
  2627. FS.hashRemoveNode(old_node);
  2628. // do the underlying fs rename
  2629. try {
  2630. old_dir.node_ops.rename(old_node, new_dir, new_name);
  2631. } catch (e) {
  2632. throw e;
  2633. } finally {
  2634. // add the node back to the hash (in case node_ops.rename
  2635. // changed its name)
  2636. FS.hashAddNode(old_node);
  2637. }
  2638. },rmdir:function (path) {
  2639. var lookup = FS.lookupPath(path, { parent: true });
  2640. var parent = lookup.node;
  2641. var name = PATH.basename(path);
  2642. var node = FS.lookupNode(parent, name);
  2643. var err = FS.mayDelete(parent, name, true);
  2644. if (err) {
  2645. throw new FS.ErrnoError(err);
  2646. }
  2647. if (!parent.node_ops.rmdir) {
  2648. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2649. }
  2650. if (FS.isMountpoint(node)) {
  2651. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2652. }
  2653. parent.node_ops.rmdir(parent, name);
  2654. FS.destroyNode(node);
  2655. },readdir:function (path) {
  2656. var lookup = FS.lookupPath(path, { follow: true });
  2657. var node = lookup.node;
  2658. if (!node.node_ops.readdir) {
  2659. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  2660. }
  2661. return node.node_ops.readdir(node);
  2662. },unlink:function (path) {
  2663. var lookup = FS.lookupPath(path, { parent: true });
  2664. var parent = lookup.node;
  2665. var name = PATH.basename(path);
  2666. var node = FS.lookupNode(parent, name);
  2667. var err = FS.mayDelete(parent, name, false);
  2668. if (err) {
  2669. // POSIX says unlink should set EPERM, not EISDIR
  2670. if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
  2671. throw new FS.ErrnoError(err);
  2672. }
  2673. if (!parent.node_ops.unlink) {
  2674. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2675. }
  2676. if (FS.isMountpoint(node)) {
  2677. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  2678. }
  2679. parent.node_ops.unlink(parent, name);
  2680. FS.destroyNode(node);
  2681. },readlink:function (path) {
  2682. var lookup = FS.lookupPath(path);
  2683. var link = lookup.node;
  2684. if (!link.node_ops.readlink) {
  2685. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2686. }
  2687. return link.node_ops.readlink(link);
  2688. },stat:function (path, dontFollow) {
  2689. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2690. var node = lookup.node;
  2691. if (!node.node_ops.getattr) {
  2692. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2693. }
  2694. return node.node_ops.getattr(node);
  2695. },lstat:function (path) {
  2696. return FS.stat(path, true);
  2697. },chmod:function (path, mode, dontFollow) {
  2698. var node;
  2699. if (typeof path === 'string') {
  2700. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2701. node = lookup.node;
  2702. } else {
  2703. node = path;
  2704. }
  2705. if (!node.node_ops.setattr) {
  2706. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2707. }
  2708. node.node_ops.setattr(node, {
  2709. mode: (mode & 4095) | (node.mode & ~4095),
  2710. timestamp: Date.now()
  2711. });
  2712. },lchmod:function (path, mode) {
  2713. FS.chmod(path, mode, true);
  2714. },fchmod:function (fd, mode) {
  2715. var stream = FS.getStream(fd);
  2716. if (!stream) {
  2717. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2718. }
  2719. FS.chmod(stream.node, mode);
  2720. },chown:function (path, uid, gid, dontFollow) {
  2721. var node;
  2722. if (typeof path === 'string') {
  2723. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2724. node = lookup.node;
  2725. } else {
  2726. node = path;
  2727. }
  2728. if (!node.node_ops.setattr) {
  2729. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2730. }
  2731. node.node_ops.setattr(node, {
  2732. timestamp: Date.now()
  2733. // we ignore the uid / gid for now
  2734. });
  2735. },lchown:function (path, uid, gid) {
  2736. FS.chown(path, uid, gid, true);
  2737. },fchown:function (fd, uid, gid) {
  2738. var stream = FS.getStream(fd);
  2739. if (!stream) {
  2740. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2741. }
  2742. FS.chown(stream.node, uid, gid);
  2743. },truncate:function (path, len) {
  2744. if (len < 0) {
  2745. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2746. }
  2747. var node;
  2748. if (typeof path === 'string') {
  2749. var lookup = FS.lookupPath(path, { follow: true });
  2750. node = lookup.node;
  2751. } else {
  2752. node = path;
  2753. }
  2754. if (!node.node_ops.setattr) {
  2755. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2756. }
  2757. if (FS.isDir(node.mode)) {
  2758. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  2759. }
  2760. if (!FS.isFile(node.mode)) {
  2761. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2762. }
  2763. var err = FS.nodePermissions(node, 'w');
  2764. if (err) {
  2765. throw new FS.ErrnoError(err);
  2766. }
  2767. node.node_ops.setattr(node, {
  2768. size: len,
  2769. timestamp: Date.now()
  2770. });
  2771. },ftruncate:function (fd, len) {
  2772. var stream = FS.getStream(fd);
  2773. if (!stream) {
  2774. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2775. }
  2776. if ((stream.flags & 2097155) === 0) {
  2777. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2778. }
  2779. FS.truncate(stream.node, len);
  2780. },utime:function (path, atime, mtime) {
  2781. var lookup = FS.lookupPath(path, { follow: true });
  2782. var node = lookup.node;
  2783. node.node_ops.setattr(node, {
  2784. timestamp: Math.max(atime, mtime)
  2785. });
  2786. },open:function (path, flags, mode, fd_start, fd_end) {
  2787. flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
  2788. mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
  2789. if ((flags & 64)) {
  2790. mode = (mode & 4095) | 32768;
  2791. } else {
  2792. mode = 0;
  2793. }
  2794. var node;
  2795. if (typeof path === 'object') {
  2796. node = path;
  2797. } else {
  2798. path = PATH.normalize(path);
  2799. try {
  2800. var lookup = FS.lookupPath(path, {
  2801. follow: !(flags & 131072)
  2802. });
  2803. node = lookup.node;
  2804. } catch (e) {
  2805. // ignore
  2806. }
  2807. }
  2808. // perhaps we need to create the node
  2809. if ((flags & 64)) {
  2810. if (node) {
  2811. // if O_CREAT and O_EXCL are set, error out if the node already exists
  2812. if ((flags & 128)) {
  2813. throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
  2814. }
  2815. } else {
  2816. // node doesn't exist, try to create it
  2817. node = FS.mknod(path, mode, 0);
  2818. }
  2819. }
  2820. if (!node) {
  2821. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  2822. }
  2823. // can't truncate a device
  2824. if (FS.isChrdev(node.mode)) {
  2825. flags &= ~512;
  2826. }
  2827. // check permissions
  2828. var err = FS.mayOpen(node, flags);
  2829. if (err) {
  2830. throw new FS.ErrnoError(err);
  2831. }
  2832. // do truncation if necessary
  2833. if ((flags & 512)) {
  2834. FS.truncate(node, 0);
  2835. }
  2836. // we've already handled these, don't pass down to the underlying vfs
  2837. flags &= ~(128 | 512);
  2838. // register the stream with the filesystem
  2839. var stream = FS.createStream({
  2840. node: node,
  2841. path: FS.getPath(node), // we want the absolute path to the node
  2842. flags: flags,
  2843. seekable: true,
  2844. position: 0,
  2845. stream_ops: node.stream_ops,
  2846. // used by the file family libc calls (fopen, fwrite, ferror, etc.)
  2847. ungotten: [],
  2848. error: false
  2849. }, fd_start, fd_end);
  2850. // call the new stream's open function
  2851. if (stream.stream_ops.open) {
  2852. stream.stream_ops.open(stream);
  2853. }
  2854. if (Module['logReadFiles'] && !(flags & 1)) {
  2855. if (!FS.readFiles) FS.readFiles = {};
  2856. if (!(path in FS.readFiles)) {
  2857. FS.readFiles[path] = 1;
  2858. Module['printErr']('read file: ' + path);
  2859. }
  2860. }
  2861. return stream;
  2862. },close:function (stream) {
  2863. try {
  2864. if (stream.stream_ops.close) {
  2865. stream.stream_ops.close(stream);
  2866. }
  2867. } catch (e) {
  2868. throw e;
  2869. } finally {
  2870. FS.closeStream(stream.fd);
  2871. }
  2872. },llseek:function (stream, offset, whence) {
  2873. if (!stream.seekable || !stream.stream_ops.llseek) {
  2874. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  2875. }
  2876. return stream.stream_ops.llseek(stream, offset, whence);
  2877. },read:function (stream, buffer, offset, length, position) {
  2878. if (length < 0 || position < 0) {
  2879. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2880. }
  2881. if ((stream.flags & 2097155) === 1) {
  2882. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2883. }
  2884. if (FS.isDir(stream.node.mode)) {
  2885. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  2886. }
  2887. if (!stream.stream_ops.read) {
  2888. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2889. }
  2890. var seeking = true;
  2891. if (typeof position === 'undefined') {
  2892. position = stream.position;
  2893. seeking = false;
  2894. } else if (!stream.seekable) {
  2895. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  2896. }
  2897. var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
  2898. if (!seeking) stream.position += bytesRead;
  2899. return bytesRead;
  2900. },write:function (stream, buffer, offset, length, position, canOwn) {
  2901. if (length < 0 || position < 0) {
  2902. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2903. }
  2904. if ((stream.flags & 2097155) === 0) {
  2905. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2906. }
  2907. if (FS.isDir(stream.node.mode)) {
  2908. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  2909. }
  2910. if (!stream.stream_ops.write) {
  2911. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2912. }
  2913. var seeking = true;
  2914. if (typeof position === 'undefined') {
  2915. position = stream.position;
  2916. seeking = false;
  2917. } else if (!stream.seekable) {
  2918. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  2919. }
  2920. if (stream.flags & 1024) {
  2921. // seek to the end before writing in append mode
  2922. FS.llseek(stream, 0, 2);
  2923. }
  2924. var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
  2925. if (!seeking) stream.position += bytesWritten;
  2926. return bytesWritten;
  2927. },allocate:function (stream, offset, length) {
  2928. if (offset < 0 || length <= 0) {
  2929. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2930. }
  2931. if ((stream.flags & 2097155) === 0) {
  2932. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  2933. }
  2934. if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
  2935. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  2936. }
  2937. if (!stream.stream_ops.allocate) {
  2938. throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
  2939. }
  2940. stream.stream_ops.allocate(stream, offset, length);
  2941. },mmap:function (stream, buffer, offset, length, position, prot, flags) {
  2942. // TODO if PROT is PROT_WRITE, make sure we have write access
  2943. if ((stream.flags & 2097155) === 1) {
  2944. throw new FS.ErrnoError(ERRNO_CODES.EACCES);
  2945. }
  2946. if (!stream.stream_ops.mmap) {
  2947. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  2948. }
  2949. return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
  2950. },ioctl:function (stream, cmd, arg) {
  2951. if (!stream.stream_ops.ioctl) {
  2952. throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
  2953. }
  2954. return stream.stream_ops.ioctl(stream, cmd, arg);
  2955. },readFile:function (path, opts) {
  2956. opts = opts || {};
  2957. opts.flags = opts.flags || 'r';
  2958. opts.encoding = opts.encoding || 'binary';
  2959. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  2960. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  2961. }
  2962. var ret;
  2963. var stream = FS.open(path, opts.flags);
  2964. var stat = FS.stat(path);
  2965. var length = stat.size;
  2966. var buf = new Uint8Array(length);
  2967. FS.read(stream, buf, 0, length, 0);
  2968. if (opts.encoding === 'utf8') {
  2969. ret = '';
  2970. var utf8 = new Runtime.UTF8Processor();
  2971. for (var i = 0; i < length; i++) {
  2972. ret += utf8.processCChar(buf[i]);
  2973. }
  2974. } else if (opts.encoding === 'binary') {
  2975. ret = buf;
  2976. }
  2977. FS.close(stream);
  2978. return ret;
  2979. },writeFile:function (path, data, opts) {
  2980. opts = opts || {};
  2981. opts.flags = opts.flags || 'w';
  2982. opts.encoding = opts.encoding || 'utf8';
  2983. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  2984. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  2985. }
  2986. var stream = FS.open(path, opts.flags, opts.mode);
  2987. if (opts.encoding === 'utf8') {
  2988. var utf8 = new Runtime.UTF8Processor();
  2989. var buf = new Uint8Array(utf8.processJSString(data));
  2990. FS.write(stream, buf, 0, buf.length, 0, opts.canOwn);
  2991. } else if (opts.encoding === 'binary') {
  2992. FS.write(stream, data, 0, data.length, 0, opts.canOwn);
  2993. }
  2994. FS.close(stream);
  2995. },cwd:function () {
  2996. return FS.currentPath;
  2997. },chdir:function (path) {
  2998. var lookup = FS.lookupPath(path, { follow: true });
  2999. if (!FS.isDir(lookup.node.mode)) {
  3000. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  3001. }
  3002. var err = FS.nodePermissions(lookup.node, 'x');
  3003. if (err) {
  3004. throw new FS.ErrnoError(err);
  3005. }
  3006. FS.currentPath = lookup.path;
  3007. },createDefaultDirectories:function () {
  3008. FS.mkdir('/tmp');
  3009. },createDefaultDevices:function () {
  3010. // create /dev
  3011. FS.mkdir('/dev');
  3012. // setup /dev/null
  3013. FS.registerDevice(FS.makedev(1, 3), {
  3014. read: function() { return 0; },
  3015. write: function() { return 0; }
  3016. });
  3017. FS.mkdev('/dev/null', FS.makedev(1, 3));
  3018. // setup /dev/tty and /dev/tty1
  3019. // stderr needs to print output using Module['printErr']
  3020. // so we register a second tty just for it.
  3021. TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
  3022. TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
  3023. FS.mkdev('/dev/tty', FS.makedev(5, 0));
  3024. FS.mkdev('/dev/tty1', FS.makedev(6, 0));
  3025. // we're not going to emulate the actual shm device,
  3026. // just create the tmp dirs that reside in it commonly
  3027. FS.mkdir('/dev/shm');
  3028. FS.mkdir('/dev/shm/tmp');
  3029. },createStandardStreams:function () {
  3030. // TODO deprecate the old functionality of a single
  3031. // input / output callback and that utilizes FS.createDevice
  3032. // and instead require a unique set of stream ops
  3033. // by default, we symlink the standard streams to the
  3034. // default tty devices. however, if the standard streams
  3035. // have been overwritten we create a unique device for
  3036. // them instead.
  3037. if (Module['stdin']) {
  3038. FS.createDevice('/dev', 'stdin', Module['stdin']);
  3039. } else {
  3040. FS.symlink('/dev/tty', '/dev/stdin');
  3041. }
  3042. if (Module['stdout']) {
  3043. FS.createDevice('/dev', 'stdout', null, Module['stdout']);
  3044. } else {
  3045. FS.symlink('/dev/tty', '/dev/stdout');
  3046. }
  3047. if (Module['stderr']) {
  3048. FS.createDevice('/dev', 'stderr', null, Module['stderr']);
  3049. } else {
  3050. FS.symlink('/dev/tty1', '/dev/stderr');
  3051. }
  3052. // open default streams for the stdin, stdout and stderr devices
  3053. var stdin = FS.open('/dev/stdin', 'r');
  3054. HEAP32[((_stdin)>>2)]=FS.getPtrForStream(stdin);
  3055. assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
  3056. var stdout = FS.open('/dev/stdout', 'w');
  3057. HEAP32[((_stdout)>>2)]=FS.getPtrForStream(stdout);
  3058. assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
  3059. var stderr = FS.open('/dev/stderr', 'w');
  3060. HEAP32[((_stderr)>>2)]=FS.getPtrForStream(stderr);
  3061. assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
  3062. },ensureErrnoError:function () {
  3063. if (FS.ErrnoError) return;
  3064. FS.ErrnoError = function ErrnoError(errno) {
  3065. this.errno = errno;
  3066. for (var key in ERRNO_CODES) {
  3067. if (ERRNO_CODES[key] === errno) {
  3068. this.code = key;
  3069. break;
  3070. }
  3071. }
  3072. this.message = ERRNO_MESSAGES[errno];
  3073. };
  3074. FS.ErrnoError.prototype = new Error();
  3075. FS.ErrnoError.prototype.constructor = FS.ErrnoError;
  3076. // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
  3077. [ERRNO_CODES.ENOENT].forEach(function(code) {
  3078. FS.genericErrors[code] = new FS.ErrnoError(code);
  3079. FS.genericErrors[code].stack = '<generic error, no stack>';
  3080. });
  3081. },staticInit:function () {
  3082. FS.ensureErrnoError();
  3083. FS.nameTable = new Array(4096);
  3084. FS.mount(MEMFS, {}, '/');
  3085. FS.createDefaultDirectories();
  3086. FS.createDefaultDevices();
  3087. },init:function (input, output, error) {
  3088. 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)');
  3089. FS.init.initialized = true;
  3090. FS.ensureErrnoError();
  3091. // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
  3092. Module['stdin'] = input || Module['stdin'];
  3093. Module['stdout'] = output || Module['stdout'];
  3094. Module['stderr'] = error || Module['stderr'];
  3095. FS.createStandardStreams();
  3096. },quit:function () {
  3097. FS.init.initialized = false;
  3098. for (var i = 0; i < FS.streams.length; i++) {
  3099. var stream = FS.streams[i];
  3100. if (!stream) {
  3101. continue;
  3102. }
  3103. FS.close(stream);
  3104. }
  3105. },getMode:function (canRead, canWrite) {
  3106. var mode = 0;
  3107. if (canRead) mode |= 292 | 73;
  3108. if (canWrite) mode |= 146;
  3109. return mode;
  3110. },joinPath:function (parts, forceRelative) {
  3111. var path = PATH.join.apply(null, parts);
  3112. if (forceRelative && path[0] == '/') path = path.substr(1);
  3113. return path;
  3114. },absolutePath:function (relative, base) {
  3115. return PATH.resolve(base, relative);
  3116. },standardizePath:function (path) {
  3117. return PATH.normalize(path);
  3118. },findObject:function (path, dontResolveLastLink) {
  3119. var ret = FS.analyzePath(path, dontResolveLastLink);
  3120. if (ret.exists) {
  3121. return ret.object;
  3122. } else {
  3123. ___setErrNo(ret.error);
  3124. return null;
  3125. }
  3126. },analyzePath:function (path, dontResolveLastLink) {
  3127. // operate from within the context of the symlink's target
  3128. try {
  3129. var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  3130. path = lookup.path;
  3131. } catch (e) {
  3132. }
  3133. var ret = {
  3134. isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
  3135. parentExists: false, parentPath: null, parentObject: null
  3136. };
  3137. try {
  3138. var lookup = FS.lookupPath(path, { parent: true });
  3139. ret.parentExists = true;
  3140. ret.parentPath = lookup.path;
  3141. ret.parentObject = lookup.node;
  3142. ret.name = PATH.basename(path);
  3143. lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  3144. ret.exists = true;
  3145. ret.path = lookup.path;
  3146. ret.object = lookup.node;
  3147. ret.name = lookup.node.name;
  3148. ret.isRoot = lookup.path === '/';
  3149. } catch (e) {
  3150. ret.error = e.errno;
  3151. };
  3152. return ret;
  3153. },createFolder:function (parent, name, canRead, canWrite) {
  3154. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3155. var mode = FS.getMode(canRead, canWrite);
  3156. return FS.mkdir(path, mode);
  3157. },createPath:function (parent, path, canRead, canWrite) {
  3158. parent = typeof parent === 'string' ? parent : FS.getPath(parent);
  3159. var parts = path.split('/').reverse();
  3160. while (parts.length) {
  3161. var part = parts.pop();
  3162. if (!part) continue;
  3163. var current = PATH.join2(parent, part);
  3164. try {
  3165. FS.mkdir(current);
  3166. } catch (e) {
  3167. // ignore EEXIST
  3168. }
  3169. parent = current;
  3170. }
  3171. return current;
  3172. },createFile:function (parent, name, properties, canRead, canWrite) {
  3173. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3174. var mode = FS.getMode(canRead, canWrite);
  3175. return FS.create(path, mode);
  3176. },createDataFile:function (parent, name, data, canRead, canWrite, canOwn) {
  3177. var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
  3178. var mode = FS.getMode(canRead, canWrite);
  3179. var node = FS.create(path, mode);
  3180. if (data) {
  3181. if (typeof data === 'string') {
  3182. var arr = new Array(data.length);
  3183. for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
  3184. data = arr;
  3185. }
  3186. // make sure we can write to the file
  3187. FS.chmod(node, mode | 146);
  3188. var stream = FS.open(node, 'w');
  3189. FS.write(stream, data, 0, data.length, 0, canOwn);
  3190. FS.close(stream);
  3191. FS.chmod(node, mode);
  3192. }
  3193. return node;
  3194. },createDevice:function (parent, name, input, output) {
  3195. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3196. var mode = FS.getMode(!!input, !!output);
  3197. if (!FS.createDevice.major) FS.createDevice.major = 64;
  3198. var dev = FS.makedev(FS.createDevice.major++, 0);
  3199. // Create a fake device that a set of stream ops to emulate
  3200. // the old behavior.
  3201. FS.registerDevice(dev, {
  3202. open: function(stream) {
  3203. stream.seekable = false;
  3204. },
  3205. close: function(stream) {
  3206. // flush any pending line data
  3207. if (output && output.buffer && output.buffer.length) {
  3208. output(10);
  3209. }
  3210. },
  3211. read: function(stream, buffer, offset, length, pos /* ignored */) {
  3212. var bytesRead = 0;
  3213. for (var i = 0; i < length; i++) {
  3214. var result;
  3215. try {
  3216. result = input();
  3217. } catch (e) {
  3218. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  3219. }
  3220. if (result === undefined && bytesRead === 0) {
  3221. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  3222. }
  3223. if (result === null || result === undefined) break;
  3224. bytesRead++;
  3225. buffer[offset+i] = result;
  3226. }
  3227. if (bytesRead) {
  3228. stream.node.timestamp = Date.now();
  3229. }
  3230. return bytesRead;
  3231. },
  3232. write: function(stream, buffer, offset, length, pos) {
  3233. for (var i = 0; i < length; i++) {
  3234. try {
  3235. output(buffer[offset+i]);
  3236. } catch (e) {
  3237. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  3238. }
  3239. }
  3240. if (length) {
  3241. stream.node.timestamp = Date.now();
  3242. }
  3243. return i;
  3244. }
  3245. });
  3246. return FS.mkdev(path, mode, dev);
  3247. },createLink:function (parent, name, target, canRead, canWrite) {
  3248. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3249. return FS.symlink(target, path);
  3250. },forceLoadFile:function (obj) {
  3251. if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
  3252. var success = true;
  3253. if (typeof XMLHttpRequest !== 'undefined') {
  3254. 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.");
  3255. } else if (Module['read']) {
  3256. // Command-line.
  3257. try {
  3258. // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
  3259. // read() will try to parse UTF8.
  3260. obj.contents = intArrayFromString(Module['read'](obj.url), true);
  3261. } catch (e) {
  3262. success = false;
  3263. }
  3264. } else {
  3265. throw new Error('Cannot load without read() or XMLHttpRequest.');
  3266. }
  3267. if (!success) ___setErrNo(ERRNO_CODES.EIO);
  3268. return success;
  3269. },createLazyFile:function (parent, name, url, canRead, canWrite) {
  3270. // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
  3271. function LazyUint8Array() {
  3272. this.lengthKnown = false;
  3273. this.chunks = []; // Loaded chunks. Index is the chunk number
  3274. }
  3275. LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
  3276. if (idx > this.length-1 || idx < 0) {
  3277. return undefined;
  3278. }
  3279. var chunkOffset = idx % this.chunkSize;
  3280. var chunkNum = Math.floor(idx / this.chunkSize);
  3281. return this.getter(chunkNum)[chunkOffset];
  3282. }
  3283. LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
  3284. this.getter = getter;
  3285. }
  3286. LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
  3287. // Find length
  3288. var xhr = new XMLHttpRequest();
  3289. xhr.open('HEAD', url, false);
  3290. xhr.send(null);
  3291. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3292. var datalength = Number(xhr.getResponseHeader("Content-length"));
  3293. var header;
  3294. var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
  3295. var chunkSize = 1024*1024; // Chunk size in bytes
  3296. if (!hasByteServing) chunkSize = datalength;
  3297. // Function to get a range from the remote URL.
  3298. var doXHR = (function(from, to) {
  3299. if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
  3300. if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
  3301. // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
  3302. var xhr = new XMLHttpRequest();
  3303. xhr.open('GET', url, false);
  3304. if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
  3305. // Some hints to the browser that we want binary data.
  3306. if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
  3307. if (xhr.overrideMimeType) {
  3308. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  3309. }
  3310. xhr.send(null);
  3311. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3312. if (xhr.response !== undefined) {
  3313. return new Uint8Array(xhr.response || []);
  3314. } else {
  3315. return intArrayFromString(xhr.responseText || '', true);
  3316. }
  3317. });
  3318. var lazyArray = this;
  3319. lazyArray.setDataGetter(function(chunkNum) {
  3320. var start = chunkNum * chunkSize;
  3321. var end = (chunkNum+1) * chunkSize - 1; // including this byte
  3322. end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
  3323. if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
  3324. lazyArray.chunks[chunkNum] = doXHR(start, end);
  3325. }
  3326. if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
  3327. return lazyArray.chunks[chunkNum];
  3328. });
  3329. this._length = datalength;
  3330. this._chunkSize = chunkSize;
  3331. this.lengthKnown = true;
  3332. }
  3333. if (typeof XMLHttpRequest !== 'undefined') {
  3334. if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
  3335. var lazyArray = new LazyUint8Array();
  3336. Object.defineProperty(lazyArray, "length", {
  3337. get: function() {
  3338. if(!this.lengthKnown) {
  3339. this.cacheLength();
  3340. }
  3341. return this._length;
  3342. }
  3343. });
  3344. Object.defineProperty(lazyArray, "chunkSize", {
  3345. get: function() {
  3346. if(!this.lengthKnown) {
  3347. this.cacheLength();
  3348. }
  3349. return this._chunkSize;
  3350. }
  3351. });
  3352. var properties = { isDevice: false, contents: lazyArray };
  3353. } else {
  3354. var properties = { isDevice: false, url: url };
  3355. }
  3356. var node = FS.createFile(parent, name, properties, canRead, canWrite);
  3357. // This is a total hack, but I want to get this lazy file code out of the
  3358. // core of MEMFS. If we want to keep this lazy file concept I feel it should
  3359. // be its own thin LAZYFS proxying calls to MEMFS.
  3360. if (properties.contents) {
  3361. node.contents = properties.contents;
  3362. } else if (properties.url) {
  3363. node.contents = null;
  3364. node.url = properties.url;
  3365. }
  3366. // override each stream op with one that tries to force load the lazy file first
  3367. var stream_ops = {};
  3368. var keys = Object.keys(node.stream_ops);
  3369. keys.forEach(function(key) {
  3370. var fn = node.stream_ops[key];
  3371. stream_ops[key] = function forceLoadLazyFile() {
  3372. if (!FS.forceLoadFile(node)) {
  3373. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  3374. }
  3375. return fn.apply(null, arguments);
  3376. };
  3377. });
  3378. // use a custom read function
  3379. stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
  3380. if (!FS.forceLoadFile(node)) {
  3381. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  3382. }
  3383. var contents = stream.node.contents;
  3384. if (position >= contents.length)
  3385. return 0;
  3386. var size = Math.min(contents.length - position, length);
  3387. assert(size >= 0);
  3388. if (contents.slice) { // normal array
  3389. for (var i = 0; i < size; i++) {
  3390. buffer[offset + i] = contents[position + i];
  3391. }
  3392. } else {
  3393. for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
  3394. buffer[offset + i] = contents.get(position + i);
  3395. }
  3396. }
  3397. return size;
  3398. };
  3399. node.stream_ops = stream_ops;
  3400. return node;
  3401. },createPreloadedFile:function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn) {
  3402. Browser.init();
  3403. // TODO we should allow people to just pass in a complete filename instead
  3404. // of parent and name being that we just join them anyways
  3405. var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
  3406. function processData(byteArray) {
  3407. function finish(byteArray) {
  3408. if (!dontCreateFile) {
  3409. FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
  3410. }
  3411. if (onload) onload();
  3412. removeRunDependency('cp ' + fullname);
  3413. }
  3414. var handled = false;
  3415. Module['preloadPlugins'].forEach(function(plugin) {
  3416. if (handled) return;
  3417. if (plugin['canHandle'](fullname)) {
  3418. plugin['handle'](byteArray, fullname, finish, function() {
  3419. if (onerror) onerror();
  3420. removeRunDependency('cp ' + fullname);
  3421. });
  3422. handled = true;
  3423. }
  3424. });
  3425. if (!handled) finish(byteArray);
  3426. }
  3427. addRunDependency('cp ' + fullname);
  3428. if (typeof url == 'string') {
  3429. Browser.asyncLoad(url, function(byteArray) {
  3430. processData(byteArray);
  3431. }, onerror);
  3432. } else {
  3433. processData(url);
  3434. }
  3435. },indexedDB:function () {
  3436. return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  3437. },DB_NAME:function () {
  3438. return 'EM_FS_' + window.location.pathname;
  3439. },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function (paths, onload, onerror) {
  3440. onload = onload || function(){};
  3441. onerror = onerror || function(){};
  3442. var indexedDB = FS.indexedDB();
  3443. try {
  3444. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3445. } catch (e) {
  3446. return onerror(e);
  3447. }
  3448. openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
  3449. console.log('creating db');
  3450. var db = openRequest.result;
  3451. db.createObjectStore(FS.DB_STORE_NAME);
  3452. };
  3453. openRequest.onsuccess = function openRequest_onsuccess() {
  3454. var db = openRequest.result;
  3455. var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
  3456. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3457. var ok = 0, fail = 0, total = paths.length;
  3458. function finish() {
  3459. if (fail == 0) onload(); else onerror();
  3460. }
  3461. paths.forEach(function(path) {
  3462. var putRequest = files.put(FS.analyzePath(path).object.contents, path);
  3463. putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
  3464. putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
  3465. });
  3466. transaction.onerror = onerror;
  3467. };
  3468. openRequest.onerror = onerror;
  3469. },loadFilesFromDB:function (paths, onload, onerror) {
  3470. onload = onload || function(){};
  3471. onerror = onerror || function(){};
  3472. var indexedDB = FS.indexedDB();
  3473. try {
  3474. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3475. } catch (e) {
  3476. return onerror(e);
  3477. }
  3478. openRequest.onupgradeneeded = onerror; // no database to load from
  3479. openRequest.onsuccess = function openRequest_onsuccess() {
  3480. var db = openRequest.result;
  3481. try {
  3482. var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
  3483. } catch(e) {
  3484. onerror(e);
  3485. return;
  3486. }
  3487. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3488. var ok = 0, fail = 0, total = paths.length;
  3489. function finish() {
  3490. if (fail == 0) onload(); else onerror();
  3491. }
  3492. paths.forEach(function(path) {
  3493. var getRequest = files.get(path);
  3494. getRequest.onsuccess = function getRequest_onsuccess() {
  3495. if (FS.analyzePath(path).exists) {
  3496. FS.unlink(path);
  3497. }
  3498. FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
  3499. ok++;
  3500. if (ok + fail == total) finish();
  3501. };
  3502. getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
  3503. });
  3504. transaction.onerror = onerror;
  3505. };
  3506. openRequest.onerror = onerror;
  3507. }};var PATH={splitPath:function (filename) {
  3508. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  3509. return splitPathRe.exec(filename).slice(1);
  3510. },normalizeArray:function (parts, allowAboveRoot) {
  3511. // if the path tries to go above the root, `up` ends up > 0
  3512. var up = 0;
  3513. for (var i = parts.length - 1; i >= 0; i--) {
  3514. var last = parts[i];
  3515. if (last === '.') {
  3516. parts.splice(i, 1);
  3517. } else if (last === '..') {
  3518. parts.splice(i, 1);
  3519. up++;
  3520. } else if (up) {
  3521. parts.splice(i, 1);
  3522. up--;
  3523. }
  3524. }
  3525. // if the path is allowed to go above the root, restore leading ..s
  3526. if (allowAboveRoot) {
  3527. for (; up--; up) {
  3528. parts.unshift('..');
  3529. }
  3530. }
  3531. return parts;
  3532. },normalize:function (path) {
  3533. var isAbsolute = path.charAt(0) === '/',
  3534. trailingSlash = path.substr(-1) === '/';
  3535. // Normalize the path
  3536. path = PATH.normalizeArray(path.split('/').filter(function(p) {
  3537. return !!p;
  3538. }), !isAbsolute).join('/');
  3539. if (!path && !isAbsolute) {
  3540. path = '.';
  3541. }
  3542. if (path && trailingSlash) {
  3543. path += '/';
  3544. }
  3545. return (isAbsolute ? '/' : '') + path;
  3546. },dirname:function (path) {
  3547. var result = PATH.splitPath(path),
  3548. root = result[0],
  3549. dir = result[1];
  3550. if (!root && !dir) {
  3551. // No dirname whatsoever
  3552. return '.';
  3553. }
  3554. if (dir) {
  3555. // It has a dirname, strip trailing slash
  3556. dir = dir.substr(0, dir.length - 1);
  3557. }
  3558. return root + dir;
  3559. },basename:function (path) {
  3560. // EMSCRIPTEN return '/'' for '/', not an empty string
  3561. if (path === '/') return '/';
  3562. var lastSlash = path.lastIndexOf('/');
  3563. if (lastSlash === -1) return path;
  3564. return path.substr(lastSlash+1);
  3565. },extname:function (path) {
  3566. return PATH.splitPath(path)[3];
  3567. },join:function () {
  3568. var paths = Array.prototype.slice.call(arguments, 0);
  3569. return PATH.normalize(paths.join('/'));
  3570. },join2:function (l, r) {
  3571. return PATH.normalize(l + '/' + r);
  3572. },resolve:function () {
  3573. var resolvedPath = '',
  3574. resolvedAbsolute = false;
  3575. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  3576. var path = (i >= 0) ? arguments[i] : FS.cwd();
  3577. // Skip empty and invalid entries
  3578. if (typeof path !== 'string') {
  3579. throw new TypeError('Arguments to path.resolve must be strings');
  3580. } else if (!path) {
  3581. continue;
  3582. }
  3583. resolvedPath = path + '/' + resolvedPath;
  3584. resolvedAbsolute = path.charAt(0) === '/';
  3585. }
  3586. // At this point the path should be resolved to a full absolute path, but
  3587. // handle relative paths to be safe (might happen when process.cwd() fails)
  3588. resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
  3589. return !!p;
  3590. }), !resolvedAbsolute).join('/');
  3591. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  3592. },relative:function (from, to) {
  3593. from = PATH.resolve(from).substr(1);
  3594. to = PATH.resolve(to).substr(1);
  3595. function trim(arr) {
  3596. var start = 0;
  3597. for (; start < arr.length; start++) {
  3598. if (arr[start] !== '') break;
  3599. }
  3600. var end = arr.length - 1;
  3601. for (; end >= 0; end--) {
  3602. if (arr[end] !== '') break;
  3603. }
  3604. if (start > end) return [];
  3605. return arr.slice(start, end - start + 1);
  3606. }
  3607. var fromParts = trim(from.split('/'));
  3608. var toParts = trim(to.split('/'));
  3609. var length = Math.min(fromParts.length, toParts.length);
  3610. var samePartsLength = length;
  3611. for (var i = 0; i < length; i++) {
  3612. if (fromParts[i] !== toParts[i]) {
  3613. samePartsLength = i;
  3614. break;
  3615. }
  3616. }
  3617. var outputParts = [];
  3618. for (var i = samePartsLength; i < fromParts.length; i++) {
  3619. outputParts.push('..');
  3620. }
  3621. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  3622. return outputParts.join('/');
  3623. }};var Browser={mainLoop:{scheduler:null,method:"",shouldPause:false,paused:false,queue:[],pause:function () {
  3624. Browser.mainLoop.shouldPause = true;
  3625. },resume:function () {
  3626. if (Browser.mainLoop.paused) {
  3627. Browser.mainLoop.paused = false;
  3628. Browser.mainLoop.scheduler();
  3629. }
  3630. Browser.mainLoop.shouldPause = false;
  3631. },updateStatus:function () {
  3632. if (Module['setStatus']) {
  3633. var message = Module['statusMessage'] || 'Please wait...';
  3634. var remaining = Browser.mainLoop.remainingBlockers;
  3635. var expected = Browser.mainLoop.expectedBlockers;
  3636. if (remaining) {
  3637. if (remaining < expected) {
  3638. Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
  3639. } else {
  3640. Module['setStatus'](message);
  3641. }
  3642. } else {
  3643. Module['setStatus']('');
  3644. }
  3645. }
  3646. }},isFullScreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function () {
  3647. if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
  3648. if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
  3649. Browser.initted = true;
  3650. try {
  3651. new Blob();
  3652. Browser.hasBlobConstructor = true;
  3653. } catch(e) {
  3654. Browser.hasBlobConstructor = false;
  3655. console.log("warning: no blob constructor, cannot create blobs with mimetypes");
  3656. }
  3657. Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
  3658. Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
  3659. if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
  3660. console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
  3661. Module.noImageDecoding = true;
  3662. }
  3663. // Support for plugins that can process preloaded files. You can add more of these to
  3664. // your app by creating and appending to Module.preloadPlugins.
  3665. //
  3666. // Each plugin is asked if it can handle a file based on the file's name. If it can,
  3667. // it is given the file's raw data. When it is done, it calls a callback with the file's
  3668. // (possibly modified) data. For example, a plugin might decompress a file, or it
  3669. // might create some side data structure for use later (like an Image element, etc.).
  3670. var imagePlugin = {};
  3671. imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
  3672. return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
  3673. };
  3674. imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
  3675. var b = null;
  3676. if (Browser.hasBlobConstructor) {
  3677. try {
  3678. b = new Blob([byteArray], { type: Browser.getMimetype(name) });
  3679. if (b.size !== byteArray.length) { // Safari bug #118630
  3680. // Safari's Blob can only take an ArrayBuffer
  3681. b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
  3682. }
  3683. } catch(e) {
  3684. Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
  3685. }
  3686. }
  3687. if (!b) {
  3688. var bb = new Browser.BlobBuilder();
  3689. bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
  3690. b = bb.getBlob();
  3691. }
  3692. var url = Browser.URLObject.createObjectURL(b);
  3693. var img = new Image();
  3694. img.onload = function img_onload() {
  3695. assert(img.complete, 'Image ' + name + ' could not be decoded');
  3696. var canvas = document.createElement('canvas');
  3697. canvas.width = img.width;
  3698. canvas.height = img.height;
  3699. var ctx = canvas.getContext('2d');
  3700. ctx.drawImage(img, 0, 0);
  3701. Module["preloadedImages"][name] = canvas;
  3702. Browser.URLObject.revokeObjectURL(url);
  3703. if (onload) onload(byteArray);
  3704. };
  3705. img.onerror = function img_onerror(event) {
  3706. console.log('Image ' + url + ' could not be decoded');
  3707. if (onerror) onerror();
  3708. };
  3709. img.src = url;
  3710. };
  3711. Module['preloadPlugins'].push(imagePlugin);
  3712. var audioPlugin = {};
  3713. audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
  3714. return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
  3715. };
  3716. audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
  3717. var done = false;
  3718. function finish(audio) {
  3719. if (done) return;
  3720. done = true;
  3721. Module["preloadedAudios"][name] = audio;
  3722. if (onload) onload(byteArray);
  3723. }
  3724. function fail() {
  3725. if (done) return;
  3726. done = true;
  3727. Module["preloadedAudios"][name] = new Audio(); // empty shim
  3728. if (onerror) onerror();
  3729. }
  3730. if (Browser.hasBlobConstructor) {
  3731. try {
  3732. var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
  3733. } catch(e) {
  3734. return fail();
  3735. }
  3736. var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
  3737. var audio = new Audio();
  3738. audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
  3739. audio.onerror = function audio_onerror(event) {
  3740. if (done) return;
  3741. console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
  3742. function encode64(data) {
  3743. var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3744. var PAD = '=';
  3745. var ret = '';
  3746. var leftchar = 0;
  3747. var leftbits = 0;
  3748. for (var i = 0; i < data.length; i++) {
  3749. leftchar = (leftchar << 8) | data[i];
  3750. leftbits += 8;
  3751. while (leftbits >= 6) {
  3752. var curr = (leftchar >> (leftbits-6)) & 0x3f;
  3753. leftbits -= 6;
  3754. ret += BASE[curr];
  3755. }
  3756. }
  3757. if (leftbits == 2) {
  3758. ret += BASE[(leftchar&3) << 4];
  3759. ret += PAD + PAD;
  3760. } else if (leftbits == 4) {
  3761. ret += BASE[(leftchar&0xf) << 2];
  3762. ret += PAD;
  3763. }
  3764. return ret;
  3765. }
  3766. audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
  3767. finish(audio); // we don't wait for confirmation this worked - but it's worth trying
  3768. };
  3769. audio.src = url;
  3770. // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
  3771. Browser.safeSetTimeout(function() {
  3772. finish(audio); // try to use it even though it is not necessarily ready to play
  3773. }, 10000);
  3774. } else {
  3775. return fail();
  3776. }
  3777. };
  3778. Module['preloadPlugins'].push(audioPlugin);
  3779. // Canvas event setup
  3780. var canvas = Module['canvas'];
  3781. // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
  3782. // Module['forcedAspectRatio'] = 4 / 3;
  3783. canvas.requestPointerLock = canvas['requestPointerLock'] ||
  3784. canvas['mozRequestPointerLock'] ||
  3785. canvas['webkitRequestPointerLock'] ||
  3786. canvas['msRequestPointerLock'] ||
  3787. function(){};
  3788. canvas.exitPointerLock = document['exitPointerLock'] ||
  3789. document['mozExitPointerLock'] ||
  3790. document['webkitExitPointerLock'] ||
  3791. document['msExitPointerLock'] ||
  3792. function(){}; // no-op if function does not exist
  3793. canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
  3794. function pointerLockChange() {
  3795. Browser.pointerLock = document['pointerLockElement'] === canvas ||
  3796. document['mozPointerLockElement'] === canvas ||
  3797. document['webkitPointerLockElement'] === canvas ||
  3798. document['msPointerLockElement'] === canvas;
  3799. }
  3800. document.addEventListener('pointerlockchange', pointerLockChange, false);
  3801. document.addEventListener('mozpointerlockchange', pointerLockChange, false);
  3802. document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
  3803. document.addEventListener('mspointerlockchange', pointerLockChange, false);
  3804. if (Module['elementPointerLock']) {
  3805. canvas.addEventListener("click", function(ev) {
  3806. if (!Browser.pointerLock && canvas.requestPointerLock) {
  3807. canvas.requestPointerLock();
  3808. ev.preventDefault();
  3809. }
  3810. }, false);
  3811. }
  3812. },createContext:function (canvas, useWebGL, setInModule, webGLContextAttributes) {
  3813. var ctx;
  3814. var errorInfo = '?';
  3815. function onContextCreationError(event) {
  3816. errorInfo = event.statusMessage || errorInfo;
  3817. }
  3818. try {
  3819. if (useWebGL) {
  3820. var contextAttributes = {
  3821. antialias: false,
  3822. alpha: false
  3823. };
  3824. if (webGLContextAttributes) {
  3825. for (var attribute in webGLContextAttributes) {
  3826. contextAttributes[attribute] = webGLContextAttributes[attribute];
  3827. }
  3828. }
  3829. canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  3830. try {
  3831. ['experimental-webgl', 'webgl'].some(function(webglId) {
  3832. return ctx = canvas.getContext(webglId, contextAttributes);
  3833. });
  3834. } finally {
  3835. canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  3836. }
  3837. } else {
  3838. ctx = canvas.getContext('2d');
  3839. }
  3840. if (!ctx) throw ':(';
  3841. } catch (e) {
  3842. Module.print('Could not create canvas: ' + [errorInfo, e]);
  3843. return null;
  3844. }
  3845. if (useWebGL) {
  3846. // Set the background of the WebGL canvas to black
  3847. canvas.style.backgroundColor = "black";
  3848. // Warn on context loss
  3849. canvas.addEventListener('webglcontextlost', function(event) {
  3850. alert('WebGL context lost. You will need to reload the page.');
  3851. }, false);
  3852. }
  3853. if (setInModule) {
  3854. GLctx = Module.ctx = ctx;
  3855. Module.useWebGL = useWebGL;
  3856. Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
  3857. Browser.init();
  3858. }
  3859. return ctx;
  3860. },destroyContext:function (canvas, useWebGL, setInModule) {},fullScreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullScreen:function (lockPointer, resizeCanvas) {
  3861. Browser.lockPointer = lockPointer;
  3862. Browser.resizeCanvas = resizeCanvas;
  3863. if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
  3864. if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
  3865. var canvas = Module['canvas'];
  3866. function fullScreenChange() {
  3867. Browser.isFullScreen = false;
  3868. var canvasContainer = canvas.parentNode;
  3869. if ((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
  3870. document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
  3871. document['fullScreenElement'] || document['fullscreenElement'] ||
  3872. document['msFullScreenElement'] || document['msFullscreenElement'] ||
  3873. document['webkitCurrentFullScreenElement']) === canvasContainer) {
  3874. canvas.cancelFullScreen = document['cancelFullScreen'] ||
  3875. document['mozCancelFullScreen'] ||
  3876. document['webkitCancelFullScreen'] ||
  3877. document['msExitFullscreen'] ||
  3878. document['exitFullscreen'] ||
  3879. function() {};
  3880. canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
  3881. if (Browser.lockPointer) canvas.requestPointerLock();
  3882. Browser.isFullScreen = true;
  3883. if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
  3884. } else {
  3885. // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
  3886. canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
  3887. canvasContainer.parentNode.removeChild(canvasContainer);
  3888. if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
  3889. }
  3890. if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScreen);
  3891. Browser.updateCanvasDimensions(canvas);
  3892. }
  3893. if (!Browser.fullScreenHandlersInstalled) {
  3894. Browser.fullScreenHandlersInstalled = true;
  3895. document.addEventListener('fullscreenchange', fullScreenChange, false);
  3896. document.addEventListener('mozfullscreenchange', fullScreenChange, false);
  3897. document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
  3898. document.addEventListener('MSFullscreenChange', fullScreenChange, false);
  3899. }
  3900. // 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
  3901. var canvasContainer = document.createElement("div");
  3902. canvas.parentNode.insertBefore(canvasContainer, canvas);
  3903. canvasContainer.appendChild(canvas);
  3904. // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
  3905. canvasContainer.requestFullScreen = canvasContainer['requestFullScreen'] ||
  3906. canvasContainer['mozRequestFullScreen'] ||
  3907. canvasContainer['msRequestFullscreen'] ||
  3908. (canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
  3909. canvasContainer.requestFullScreen();
  3910. },requestAnimationFrame:function requestAnimationFrame(func) {
  3911. if (typeof window === 'undefined') { // Provide fallback to setTimeout if window is undefined (e.g. in Node.js)
  3912. setTimeout(func, 1000/60);
  3913. } else {
  3914. if (!window.requestAnimationFrame) {
  3915. window.requestAnimationFrame = window['requestAnimationFrame'] ||
  3916. window['mozRequestAnimationFrame'] ||
  3917. window['webkitRequestAnimationFrame'] ||
  3918. window['msRequestAnimationFrame'] ||
  3919. window['oRequestAnimationFrame'] ||
  3920. window['setTimeout'];
  3921. }
  3922. window.requestAnimationFrame(func);
  3923. }
  3924. },safeCallback:function (func) {
  3925. return function() {
  3926. if (!ABORT) return func.apply(null, arguments);
  3927. };
  3928. },safeRequestAnimationFrame:function (func) {
  3929. return Browser.requestAnimationFrame(function() {
  3930. if (!ABORT) func();
  3931. });
  3932. },safeSetTimeout:function (func, timeout) {
  3933. return setTimeout(function() {
  3934. if (!ABORT) func();
  3935. }, timeout);
  3936. },safeSetInterval:function (func, timeout) {
  3937. return setInterval(function() {
  3938. if (!ABORT) func();
  3939. }, timeout);
  3940. },getMimetype:function (name) {
  3941. return {
  3942. 'jpg': 'image/jpeg',
  3943. 'jpeg': 'image/jpeg',
  3944. 'png': 'image/png',
  3945. 'bmp': 'image/bmp',
  3946. 'ogg': 'audio/ogg',
  3947. 'wav': 'audio/wav',
  3948. 'mp3': 'audio/mpeg'
  3949. }[name.substr(name.lastIndexOf('.')+1)];
  3950. },getUserMedia:function (func) {
  3951. if(!window.getUserMedia) {
  3952. window.getUserMedia = navigator['getUserMedia'] ||
  3953. navigator['mozGetUserMedia'];
  3954. }
  3955. window.getUserMedia(func);
  3956. },getMovementX:function (event) {
  3957. return event['movementX'] ||
  3958. event['mozMovementX'] ||
  3959. event['webkitMovementX'] ||
  3960. 0;
  3961. },getMovementY:function (event) {
  3962. return event['movementY'] ||
  3963. event['mozMovementY'] ||
  3964. event['webkitMovementY'] ||
  3965. 0;
  3966. },getMouseWheelDelta:function (event) {
  3967. return Math.max(-1, Math.min(1, event.type === 'DOMMouseScroll' ? event.detail : -event.wheelDelta));
  3968. },mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,calculateMouseEvent:function (event) { // event should be mousemove, mousedown or mouseup
  3969. if (Browser.pointerLock) {
  3970. // When the pointer is locked, calculate the coordinates
  3971. // based on the movement of the mouse.
  3972. // Workaround for Firefox bug 764498
  3973. if (event.type != 'mousemove' &&
  3974. ('mozMovementX' in event)) {
  3975. Browser.mouseMovementX = Browser.mouseMovementY = 0;
  3976. } else {
  3977. Browser.mouseMovementX = Browser.getMovementX(event);
  3978. Browser.mouseMovementY = Browser.getMovementY(event);
  3979. }
  3980. // check if SDL is available
  3981. if (typeof SDL != "undefined") {
  3982. Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
  3983. Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
  3984. } else {
  3985. // just add the mouse delta to the current absolut mouse position
  3986. // FIXME: ideally this should be clamped against the canvas size and zero
  3987. Browser.mouseX += Browser.mouseMovementX;
  3988. Browser.mouseY += Browser.mouseMovementY;
  3989. }
  3990. } else {
  3991. // Otherwise, calculate the movement based on the changes
  3992. // in the coordinates.
  3993. var rect = Module["canvas"].getBoundingClientRect();
  3994. var x, y;
  3995. // Neither .scrollX or .pageXOffset are defined in a spec, but
  3996. // we prefer .scrollX because it is currently in a spec draft.
  3997. // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
  3998. var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
  3999. var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
  4000. if (event.type == 'touchstart' ||
  4001. event.type == 'touchend' ||
  4002. event.type == 'touchmove') {
  4003. var t = event.touches.item(0);
  4004. if (t) {
  4005. x = t.pageX - (scrollX + rect.left);
  4006. y = t.pageY - (scrollY + rect.top);
  4007. } else {
  4008. return;
  4009. }
  4010. } else {
  4011. x = event.pageX - (scrollX + rect.left);
  4012. y = event.pageY - (scrollY + rect.top);
  4013. }
  4014. // the canvas might be CSS-scaled compared to its backbuffer;
  4015. // SDL-using content will want mouse coordinates in terms
  4016. // of backbuffer units.
  4017. var cw = Module["canvas"].width;
  4018. var ch = Module["canvas"].height;
  4019. x = x * (cw / rect.width);
  4020. y = y * (ch / rect.height);
  4021. Browser.mouseMovementX = x - Browser.mouseX;
  4022. Browser.mouseMovementY = y - Browser.mouseY;
  4023. Browser.mouseX = x;
  4024. Browser.mouseY = y;
  4025. }
  4026. },xhrLoad:function (url, onload, onerror) {
  4027. var xhr = new XMLHttpRequest();
  4028. xhr.open('GET', url, true);
  4029. xhr.responseType = 'arraybuffer';
  4030. xhr.onload = function xhr_onload() {
  4031. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  4032. onload(xhr.response);
  4033. } else {
  4034. onerror();
  4035. }
  4036. };
  4037. xhr.onerror = onerror;
  4038. xhr.send(null);
  4039. },asyncLoad:function (url, onload, onerror, noRunDep) {
  4040. Browser.xhrLoad(url, function(arrayBuffer) {
  4041. assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
  4042. onload(new Uint8Array(arrayBuffer));
  4043. if (!noRunDep) removeRunDependency('al ' + url);
  4044. }, function(event) {
  4045. if (onerror) {
  4046. onerror();
  4047. } else {
  4048. throw 'Loading data file "' + url + '" failed.';
  4049. }
  4050. });
  4051. if (!noRunDep) addRunDependency('al ' + url);
  4052. },resizeListeners:[],updateResizeListeners:function () {
  4053. var canvas = Module['canvas'];
  4054. Browser.resizeListeners.forEach(function(listener) {
  4055. listener(canvas.width, canvas.height);
  4056. });
  4057. },setCanvasSize:function (width, height, noUpdates) {
  4058. var canvas = Module['canvas'];
  4059. Browser.updateCanvasDimensions(canvas, width, height);
  4060. if (!noUpdates) Browser.updateResizeListeners();
  4061. },windowedWidth:0,windowedHeight:0,setFullScreenCanvasSize:function () {
  4062. // check if SDL is available
  4063. if (typeof SDL != "undefined") {
  4064. var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
  4065. flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
  4066. HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
  4067. }
  4068. Browser.updateResizeListeners();
  4069. },setWindowedCanvasSize:function () {
  4070. // check if SDL is available
  4071. if (typeof SDL != "undefined") {
  4072. var flags = HEAPU32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)];
  4073. flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
  4074. HEAP32[((SDL.screen+Runtime.QUANTUM_SIZE*0)>>2)]=flags
  4075. }
  4076. Browser.updateResizeListeners();
  4077. },updateCanvasDimensions:function (canvas, wNative, hNative) {
  4078. if (wNative && hNative) {
  4079. canvas.widthNative = wNative;
  4080. canvas.heightNative = hNative;
  4081. } else {
  4082. wNative = canvas.widthNative;
  4083. hNative = canvas.heightNative;
  4084. }
  4085. var w = wNative;
  4086. var h = hNative;
  4087. if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
  4088. if (w/h < Module['forcedAspectRatio']) {
  4089. w = Math.round(h * Module['forcedAspectRatio']);
  4090. } else {
  4091. h = Math.round(w / Module['forcedAspectRatio']);
  4092. }
  4093. }
  4094. if (((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
  4095. document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
  4096. document['fullScreenElement'] || document['fullscreenElement'] ||
  4097. document['msFullScreenElement'] || document['msFullscreenElement'] ||
  4098. document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
  4099. var factor = Math.min(screen.width / w, screen.height / h);
  4100. w = Math.round(w * factor);
  4101. h = Math.round(h * factor);
  4102. }
  4103. if (Browser.resizeCanvas) {
  4104. if (canvas.width != w) canvas.width = w;
  4105. if (canvas.height != h) canvas.height = h;
  4106. if (typeof canvas.style != 'undefined') {
  4107. canvas.style.removeProperty( "width");
  4108. canvas.style.removeProperty("height");
  4109. }
  4110. } else {
  4111. if (canvas.width != wNative) canvas.width = wNative;
  4112. if (canvas.height != hNative) canvas.height = hNative;
  4113. if (typeof canvas.style != 'undefined') {
  4114. if (w != wNative || h != hNative) {
  4115. canvas.style.setProperty( "width", w + "px", "important");
  4116. canvas.style.setProperty("height", h + "px", "important");
  4117. } else {
  4118. canvas.style.removeProperty( "width");
  4119. canvas.style.removeProperty("height");
  4120. }
  4121. }
  4122. }
  4123. }};
  4124. function _mkport() { throw 'TODO' }var SOCKFS={mount:function (mount) {
  4125. return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  4126. },createSocket:function (family, type, protocol) {
  4127. var streaming = type == 1;
  4128. if (protocol) {
  4129. assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
  4130. }
  4131. // create our internal socket structure
  4132. var sock = {
  4133. family: family,
  4134. type: type,
  4135. protocol: protocol,
  4136. server: null,
  4137. peers: {},
  4138. pending: [],
  4139. recv_queue: [],
  4140. sock_ops: SOCKFS.websocket_sock_ops
  4141. };
  4142. // create the filesystem node to store the socket structure
  4143. var name = SOCKFS.nextname();
  4144. var node = FS.createNode(SOCKFS.root, name, 49152, 0);
  4145. node.sock = sock;
  4146. // and the wrapping stream that enables library functions such
  4147. // as read and write to indirectly interact with the socket
  4148. var stream = FS.createStream({
  4149. path: name,
  4150. node: node,
  4151. flags: FS.modeStringToFlags('r+'),
  4152. seekable: false,
  4153. stream_ops: SOCKFS.stream_ops
  4154. });
  4155. // map the new stream to the socket structure (sockets have a 1:1
  4156. // relationship with a stream)
  4157. sock.stream = stream;
  4158. return sock;
  4159. },getSocket:function (fd) {
  4160. var stream = FS.getStream(fd);
  4161. if (!stream || !FS.isSocket(stream.node.mode)) {
  4162. return null;
  4163. }
  4164. return stream.node.sock;
  4165. },stream_ops:{poll:function (stream) {
  4166. var sock = stream.node.sock;
  4167. return sock.sock_ops.poll(sock);
  4168. },ioctl:function (stream, request, varargs) {
  4169. var sock = stream.node.sock;
  4170. return sock.sock_ops.ioctl(sock, request, varargs);
  4171. },read:function (stream, buffer, offset, length, position /* ignored */) {
  4172. var sock = stream.node.sock;
  4173. var msg = sock.sock_ops.recvmsg(sock, length);
  4174. if (!msg) {
  4175. // socket is closed
  4176. return 0;
  4177. }
  4178. buffer.set(msg.buffer, offset);
  4179. return msg.buffer.length;
  4180. },write:function (stream, buffer, offset, length, position /* ignored */) {
  4181. var sock = stream.node.sock;
  4182. return sock.sock_ops.sendmsg(sock, buffer, offset, length);
  4183. },close:function (stream) {
  4184. var sock = stream.node.sock;
  4185. sock.sock_ops.close(sock);
  4186. }},nextname:function () {
  4187. if (!SOCKFS.nextname.current) {
  4188. SOCKFS.nextname.current = 0;
  4189. }
  4190. return 'socket[' + (SOCKFS.nextname.current++) + ']';
  4191. },websocket_sock_ops:{createPeer:function (sock, addr, port) {
  4192. var ws;
  4193. if (typeof addr === 'object') {
  4194. ws = addr;
  4195. addr = null;
  4196. port = null;
  4197. }
  4198. if (ws) {
  4199. // for sockets that've already connected (e.g. we're the server)
  4200. // we can inspect the _socket property for the address
  4201. if (ws._socket) {
  4202. addr = ws._socket.remoteAddress;
  4203. port = ws._socket.remotePort;
  4204. }
  4205. // if we're just now initializing a connection to the remote,
  4206. // inspect the url property
  4207. else {
  4208. var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
  4209. if (!result) {
  4210. throw new Error('WebSocket URL must be in the format ws(s)://address:port');
  4211. }
  4212. addr = result[1];
  4213. port = parseInt(result[2], 10);
  4214. }
  4215. } else {
  4216. // create the actual websocket object and connect
  4217. try {
  4218. // runtimeConfig gets set to true if WebSocket runtime configuration is available.
  4219. var runtimeConfig = (Module['websocket'] && ('object' === typeof Module['websocket']));
  4220. // The default value is 'ws://' the replace is needed because the compiler replaces "//" comments with '#'
  4221. // comments without checking context, so we'd end up with ws:#, the replace swaps the "#" for "//" again.
  4222. var url = 'ws:#'.replace('#', '//');
  4223. if (runtimeConfig) {
  4224. if ('string' === typeof Module['websocket']['url']) {
  4225. url = Module['websocket']['url']; // Fetch runtime WebSocket URL config.
  4226. }
  4227. }
  4228. if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
  4229. url = url + addr + ':' + port;
  4230. }
  4231. // Make the WebSocket subprotocol (Sec-WebSocket-Protocol) default to binary if no configuration is set.
  4232. var subProtocols = 'binary'; // The default value is 'binary'
  4233. if (runtimeConfig) {
  4234. if ('string' === typeof Module['websocket']['subprotocol']) {
  4235. subProtocols = Module['websocket']['subprotocol']; // Fetch runtime WebSocket subprotocol config.
  4236. }
  4237. }
  4238. // The regex trims the string (removes spaces at the beginning and end, then splits the string by
  4239. // <any space>,<any space> into an Array. Whitespace removal is important for Websockify and ws.
  4240. subProtocols = subProtocols.replace(/^ +| +$/g,"").split(/ *, */);
  4241. // The node ws library API for specifying optional subprotocol is slightly different than the browser's.
  4242. var opts = ENVIRONMENT_IS_NODE ? {'protocol': subProtocols.toString()} : subProtocols;
  4243. // If node we use the ws library.
  4244. var WebSocket = ENVIRONMENT_IS_NODE ? require('ws') : window['WebSocket'];
  4245. ws = new WebSocket(url, opts);
  4246. ws.binaryType = 'arraybuffer';
  4247. } catch (e) {
  4248. throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
  4249. }
  4250. }
  4251. var peer = {
  4252. addr: addr,
  4253. port: port,
  4254. socket: ws,
  4255. dgram_send_queue: []
  4256. };
  4257. SOCKFS.websocket_sock_ops.addPeer(sock, peer);
  4258. SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
  4259. // if this is a bound dgram socket, send the port number first to allow
  4260. // us to override the ephemeral port reported to us by remotePort on the
  4261. // remote end.
  4262. if (sock.type === 2 && typeof sock.sport !== 'undefined') {
  4263. peer.dgram_send_queue.push(new Uint8Array([
  4264. 255, 255, 255, 255,
  4265. 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0),
  4266. ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
  4267. ]));
  4268. }
  4269. return peer;
  4270. },getPeer:function (sock, addr, port) {
  4271. return sock.peers[addr + ':' + port];
  4272. },addPeer:function (sock, peer) {
  4273. sock.peers[peer.addr + ':' + peer.port] = peer;
  4274. },removePeer:function (sock, peer) {
  4275. delete sock.peers[peer.addr + ':' + peer.port];
  4276. },handlePeerEvents:function (sock, peer) {
  4277. var first = true;
  4278. var handleOpen = function () {
  4279. try {
  4280. var queued = peer.dgram_send_queue.shift();
  4281. while (queued) {
  4282. peer.socket.send(queued);
  4283. queued = peer.dgram_send_queue.shift();
  4284. }
  4285. } catch (e) {
  4286. // not much we can do here in the way of proper error handling as we've already
  4287. // lied and said this data was sent. shut it down.
  4288. peer.socket.close();
  4289. }
  4290. };
  4291. function handleMessage(data) {
  4292. assert(typeof data !== 'string' && data.byteLength !== undefined); // must receive an ArrayBuffer
  4293. data = new Uint8Array(data); // make a typed array view on the array buffer
  4294. // if this is the port message, override the peer's port with it
  4295. var wasfirst = first;
  4296. first = false;
  4297. if (wasfirst &&
  4298. data.length === 10 &&
  4299. data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
  4300. data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) && data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
  4301. // update the peer's port and it's key in the peer map
  4302. var newport = ((data[8] << 8) | data[9]);
  4303. SOCKFS.websocket_sock_ops.removePeer(sock, peer);
  4304. peer.port = newport;
  4305. SOCKFS.websocket_sock_ops.addPeer(sock, peer);
  4306. return;
  4307. }
  4308. sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
  4309. };
  4310. if (ENVIRONMENT_IS_NODE) {
  4311. peer.socket.on('open', handleOpen);
  4312. peer.socket.on('message', function(data, flags) {
  4313. if (!flags.binary) {
  4314. return;
  4315. }
  4316. handleMessage((new Uint8Array(data)).buffer); // copy from node Buffer -> ArrayBuffer
  4317. });
  4318. peer.socket.on('error', function() {
  4319. // don't throw
  4320. });
  4321. } else {
  4322. peer.socket.onopen = handleOpen;
  4323. peer.socket.onmessage = function peer_socket_onmessage(event) {
  4324. handleMessage(event.data);
  4325. };
  4326. }
  4327. },poll:function (sock) {
  4328. if (sock.type === 1 && sock.server) {
  4329. // listen sockets should only say they're available for reading
  4330. // if there are pending clients.
  4331. return sock.pending.length ? (64 | 1) : 0;
  4332. }
  4333. var mask = 0;
  4334. var dest = sock.type === 1 ? // we only care about the socket state for connection-based sockets
  4335. SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
  4336. null;
  4337. if (sock.recv_queue.length ||
  4338. !dest || // connection-less sockets are always ready to read
  4339. (dest && dest.socket.readyState === dest.socket.CLOSING) ||
  4340. (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
  4341. mask |= (64 | 1);
  4342. }
  4343. if (!dest || // connection-less sockets are always ready to write
  4344. (dest && dest.socket.readyState === dest.socket.OPEN)) {
  4345. mask |= 4;
  4346. }
  4347. if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
  4348. (dest && dest.socket.readyState === dest.socket.CLOSED)) {
  4349. mask |= 16;
  4350. }
  4351. return mask;
  4352. },ioctl:function (sock, request, arg) {
  4353. switch (request) {
  4354. case 21531:
  4355. var bytes = 0;
  4356. if (sock.recv_queue.length) {
  4357. bytes = sock.recv_queue[0].data.length;
  4358. }
  4359. HEAP32[((arg)>>2)]=bytes;
  4360. return 0;
  4361. default:
  4362. return ERRNO_CODES.EINVAL;
  4363. }
  4364. },close:function (sock) {
  4365. // if we've spawned a listen server, close it
  4366. if (sock.server) {
  4367. try {
  4368. sock.server.close();
  4369. } catch (e) {
  4370. }
  4371. sock.server = null;
  4372. }
  4373. // close any peer connections
  4374. var peers = Object.keys(sock.peers);
  4375. for (var i = 0; i < peers.length; i++) {
  4376. var peer = sock.peers[peers[i]];
  4377. try {
  4378. peer.socket.close();
  4379. } catch (e) {
  4380. }
  4381. SOCKFS.websocket_sock_ops.removePeer(sock, peer);
  4382. }
  4383. return 0;
  4384. },bind:function (sock, addr, port) {
  4385. if (typeof sock.saddr !== 'undefined' || typeof sock.sport !== 'undefined') {
  4386. throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already bound
  4387. }
  4388. sock.saddr = addr;
  4389. sock.sport = port || _mkport();
  4390. // in order to emulate dgram sockets, we need to launch a listen server when
  4391. // binding on a connection-less socket
  4392. // note: this is only required on the server side
  4393. if (sock.type === 2) {
  4394. // close the existing server if it exists
  4395. if (sock.server) {
  4396. sock.server.close();
  4397. sock.server = null;
  4398. }
  4399. // swallow error operation not supported error that occurs when binding in the
  4400. // browser where this isn't supported
  4401. try {
  4402. sock.sock_ops.listen(sock, 0);
  4403. } catch (e) {
  4404. if (!(e instanceof FS.ErrnoError)) throw e;
  4405. if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
  4406. }
  4407. }
  4408. },connect:function (sock, addr, port) {
  4409. if (sock.server) {
  4410. throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
  4411. }
  4412. // TODO autobind
  4413. // if (!sock.addr && sock.type == 2) {
  4414. // }
  4415. // early out if we're already connected / in the middle of connecting
  4416. if (typeof sock.daddr !== 'undefined' && typeof sock.dport !== 'undefined') {
  4417. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
  4418. if (dest) {
  4419. if (dest.socket.readyState === dest.socket.CONNECTING) {
  4420. throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
  4421. } else {
  4422. throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
  4423. }
  4424. }
  4425. }
  4426. // add the socket to our peer list and set our
  4427. // destination address / port to match
  4428. var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
  4429. sock.daddr = peer.addr;
  4430. sock.dport = peer.port;
  4431. // always "fail" in non-blocking mode
  4432. throw new FS.ErrnoError(ERRNO_CODES.EINPROGRESS);
  4433. },listen:function (sock, backlog) {
  4434. if (!ENVIRONMENT_IS_NODE) {
  4435. throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
  4436. }
  4437. if (sock.server) {
  4438. throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already listening
  4439. }
  4440. var WebSocketServer = require('ws').Server;
  4441. var host = sock.saddr;
  4442. sock.server = new WebSocketServer({
  4443. host: host,
  4444. port: sock.sport
  4445. // TODO support backlog
  4446. });
  4447. sock.server.on('connection', function(ws) {
  4448. if (sock.type === 1) {
  4449. var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
  4450. // create a peer on the new socket
  4451. var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
  4452. newsock.daddr = peer.addr;
  4453. newsock.dport = peer.port;
  4454. // push to queue for accept to pick up
  4455. sock.pending.push(newsock);
  4456. } else {
  4457. // create a peer on the listen socket so calling sendto
  4458. // with the listen socket and an address will resolve
  4459. // to the correct client
  4460. SOCKFS.websocket_sock_ops.createPeer(sock, ws);
  4461. }
  4462. });
  4463. sock.server.on('closed', function() {
  4464. sock.server = null;
  4465. });
  4466. sock.server.on('error', function() {
  4467. // don't throw
  4468. });
  4469. },accept:function (listensock) {
  4470. if (!listensock.server) {
  4471. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4472. }
  4473. var newsock = listensock.pending.shift();
  4474. newsock.stream.flags = listensock.stream.flags;
  4475. return newsock;
  4476. },getname:function (sock, peer) {
  4477. var addr, port;
  4478. if (peer) {
  4479. if (sock.daddr === undefined || sock.dport === undefined) {
  4480. throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
  4481. }
  4482. addr = sock.daddr;
  4483. port = sock.dport;
  4484. } else {
  4485. // TODO saddr and sport will be set for bind()'d UDP sockets, but what
  4486. // should we be returning for TCP sockets that've been connect()'d?
  4487. addr = sock.saddr || 0;
  4488. port = sock.sport || 0;
  4489. }
  4490. return { addr: addr, port: port };
  4491. },sendmsg:function (sock, buffer, offset, length, addr, port) {
  4492. if (sock.type === 2) {
  4493. // connection-less sockets will honor the message address,
  4494. // and otherwise fall back to the bound destination address
  4495. if (addr === undefined || port === undefined) {
  4496. addr = sock.daddr;
  4497. port = sock.dport;
  4498. }
  4499. // if there was no address to fall back to, error out
  4500. if (addr === undefined || port === undefined) {
  4501. throw new FS.ErrnoError(ERRNO_CODES.EDESTADDRREQ);
  4502. }
  4503. } else {
  4504. // connection-based sockets will only use the bound
  4505. addr = sock.daddr;
  4506. port = sock.dport;
  4507. }
  4508. // find the peer for the destination address
  4509. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
  4510. // early out if not connected with a connection-based socket
  4511. if (sock.type === 1) {
  4512. if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  4513. throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
  4514. } else if (dest.socket.readyState === dest.socket.CONNECTING) {
  4515. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  4516. }
  4517. }
  4518. // create a copy of the incoming data to send, as the WebSocket API
  4519. // doesn't work entirely with an ArrayBufferView, it'll just send
  4520. // the entire underlying buffer
  4521. var data;
  4522. if (buffer instanceof Array || buffer instanceof ArrayBuffer) {
  4523. data = buffer.slice(offset, offset + length);
  4524. } else { // ArrayBufferView
  4525. data = buffer.buffer.slice(buffer.byteOffset + offset, buffer.byteOffset + offset + length);
  4526. }
  4527. // if we're emulating a connection-less dgram socket and don't have
  4528. // a cached connection, queue the buffer to send upon connect and
  4529. // lie, saying the data was sent now.
  4530. if (sock.type === 2) {
  4531. if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
  4532. // if we're not connected, open a new connection
  4533. if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  4534. dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
  4535. }
  4536. dest.dgram_send_queue.push(data);
  4537. return length;
  4538. }
  4539. }
  4540. try {
  4541. // send the actual data
  4542. dest.socket.send(data);
  4543. return length;
  4544. } catch (e) {
  4545. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4546. }
  4547. },recvmsg:function (sock, length) {
  4548. // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
  4549. if (sock.type === 1 && sock.server) {
  4550. // tcp servers should not be recv()'ing on the listen socket
  4551. throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
  4552. }
  4553. var queued = sock.recv_queue.shift();
  4554. if (!queued) {
  4555. if (sock.type === 1) {
  4556. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
  4557. if (!dest) {
  4558. // if we have a destination address but are not connected, error out
  4559. throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
  4560. }
  4561. else if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  4562. // return null if the socket has closed
  4563. return null;
  4564. }
  4565. else {
  4566. // else, our socket is in a valid state but truly has nothing available
  4567. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  4568. }
  4569. } else {
  4570. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  4571. }
  4572. }
  4573. // queued.data will be an ArrayBuffer if it's unadulterated, but if it's
  4574. // requeued TCP data it'll be an ArrayBufferView
  4575. var queuedLength = queued.data.byteLength || queued.data.length;
  4576. var queuedOffset = queued.data.byteOffset || 0;
  4577. var queuedBuffer = queued.data.buffer || queued.data;
  4578. var bytesRead = Math.min(length, queuedLength);
  4579. var res = {
  4580. buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
  4581. addr: queued.addr,
  4582. port: queued.port
  4583. };
  4584. // push back any unread data for TCP connections
  4585. if (sock.type === 1 && bytesRead < queuedLength) {
  4586. var bytesRemaining = queuedLength - bytesRead;
  4587. queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
  4588. sock.recv_queue.unshift(queued);
  4589. }
  4590. return res;
  4591. }}};function _send(fd, buf, len, flags) {
  4592. var sock = SOCKFS.getSocket(fd);
  4593. if (!sock) {
  4594. ___setErrNo(ERRNO_CODES.EBADF);
  4595. return -1;
  4596. }
  4597. // TODO honor flags
  4598. return _write(fd, buf, len);
  4599. }
  4600. function _pwrite(fildes, buf, nbyte, offset) {
  4601. // ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset);
  4602. // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
  4603. var stream = FS.getStream(fildes);
  4604. if (!stream) {
  4605. ___setErrNo(ERRNO_CODES.EBADF);
  4606. return -1;
  4607. }
  4608. try {
  4609. var slab = HEAP8;
  4610. return FS.write(stream, slab, buf, nbyte, offset);
  4611. } catch (e) {
  4612. FS.handleFSError(e);
  4613. return -1;
  4614. }
  4615. }function _write(fildes, buf, nbyte) {
  4616. // ssize_t write(int fildes, const void *buf, size_t nbyte);
  4617. // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
  4618. var stream = FS.getStream(fildes);
  4619. if (!stream) {
  4620. ___setErrNo(ERRNO_CODES.EBADF);
  4621. return -1;
  4622. }
  4623. try {
  4624. var slab = HEAP8;
  4625. return FS.write(stream, slab, buf, nbyte);
  4626. } catch (e) {
  4627. FS.handleFSError(e);
  4628. return -1;
  4629. }
  4630. }
  4631. function _fileno(stream) {
  4632. // int fileno(FILE *stream);
  4633. // http://pubs.opengroup.org/onlinepubs/000095399/functions/fileno.html
  4634. stream = FS.getStreamFromPtr(stream);
  4635. if (!stream) return -1;
  4636. return stream.fd;
  4637. }function _fwrite(ptr, size, nitems, stream) {
  4638. // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
  4639. // http://pubs.opengroup.org/onlinepubs/000095399/functions/fwrite.html
  4640. var bytesToWrite = nitems * size;
  4641. if (bytesToWrite == 0) return 0;
  4642. var fd = _fileno(stream);
  4643. var bytesWritten = _write(fd, ptr, bytesToWrite);
  4644. if (bytesWritten == -1) {
  4645. var streamObj = FS.getStreamFromPtr(stream);
  4646. if (streamObj) streamObj.error = true;
  4647. return 0;
  4648. } else {
  4649. return Math.floor(bytesWritten / size);
  4650. }
  4651. }
  4652. Module["_strlen"] = _strlen;
  4653. function __reallyNegative(x) {
  4654. return x < 0 || (x === 0 && (1/x) === -Infinity);
  4655. }function __formatString(format, varargs) {
  4656. var textIndex = format;
  4657. var argIndex = 0;
  4658. function getNextArg(type) {
  4659. // NOTE: Explicitly ignoring type safety. Otherwise this fails:
  4660. // int x = 4; printf("%c\n", (char)x);
  4661. var ret;
  4662. if (type === 'double') {
  4663. ret = HEAPF64[(((varargs)+(argIndex))>>3)];
  4664. } else if (type == 'i64') {
  4665. ret = [HEAP32[(((varargs)+(argIndex))>>2)],
  4666. HEAP32[(((varargs)+(argIndex+4))>>2)]];
  4667. } else {
  4668. type = 'i32'; // varargs are always i32, i64, or double
  4669. ret = HEAP32[(((varargs)+(argIndex))>>2)];
  4670. }
  4671. argIndex += Runtime.getNativeFieldSize(type);
  4672. return ret;
  4673. }
  4674. var ret = [];
  4675. var curr, next, currArg;
  4676. while(1) {
  4677. var startTextIndex = textIndex;
  4678. curr = HEAP8[(textIndex)];
  4679. if (curr === 0) break;
  4680. next = HEAP8[((textIndex+1)|0)];
  4681. if (curr == 37) {
  4682. // Handle flags.
  4683. var flagAlwaysSigned = false;
  4684. var flagLeftAlign = false;
  4685. var flagAlternative = false;
  4686. var flagZeroPad = false;
  4687. var flagPadSign = false;
  4688. flagsLoop: while (1) {
  4689. switch (next) {
  4690. case 43:
  4691. flagAlwaysSigned = true;
  4692. break;
  4693. case 45:
  4694. flagLeftAlign = true;
  4695. break;
  4696. case 35:
  4697. flagAlternative = true;
  4698. break;
  4699. case 48:
  4700. if (flagZeroPad) {
  4701. break flagsLoop;
  4702. } else {
  4703. flagZeroPad = true;
  4704. break;
  4705. }
  4706. case 32:
  4707. flagPadSign = true;
  4708. break;
  4709. default:
  4710. break flagsLoop;
  4711. }
  4712. textIndex++;
  4713. next = HEAP8[((textIndex+1)|0)];
  4714. }
  4715. // Handle width.
  4716. var width = 0;
  4717. if (next == 42) {
  4718. width = getNextArg('i32');
  4719. textIndex++;
  4720. next = HEAP8[((textIndex+1)|0)];
  4721. } else {
  4722. while (next >= 48 && next <= 57) {
  4723. width = width * 10 + (next - 48);
  4724. textIndex++;
  4725. next = HEAP8[((textIndex+1)|0)];
  4726. }
  4727. }
  4728. // Handle precision.
  4729. var precisionSet = false, precision = -1;
  4730. if (next == 46) {
  4731. precision = 0;
  4732. precisionSet = true;
  4733. textIndex++;
  4734. next = HEAP8[((textIndex+1)|0)];
  4735. if (next == 42) {
  4736. precision = getNextArg('i32');
  4737. textIndex++;
  4738. } else {
  4739. while(1) {
  4740. var precisionChr = HEAP8[((textIndex+1)|0)];
  4741. if (precisionChr < 48 ||
  4742. precisionChr > 57) break;
  4743. precision = precision * 10 + (precisionChr - 48);
  4744. textIndex++;
  4745. }
  4746. }
  4747. next = HEAP8[((textIndex+1)|0)];
  4748. }
  4749. if (precision < 0) {
  4750. precision = 6; // Standard default.
  4751. precisionSet = false;
  4752. }
  4753. // Handle integer sizes. WARNING: These assume a 32-bit architecture!
  4754. var argSize;
  4755. switch (String.fromCharCode(next)) {
  4756. case 'h':
  4757. var nextNext = HEAP8[((textIndex+2)|0)];
  4758. if (nextNext == 104) {
  4759. textIndex++;
  4760. argSize = 1; // char (actually i32 in varargs)
  4761. } else {
  4762. argSize = 2; // short (actually i32 in varargs)
  4763. }
  4764. break;
  4765. case 'l':
  4766. var nextNext = HEAP8[((textIndex+2)|0)];
  4767. if (nextNext == 108) {
  4768. textIndex++;
  4769. argSize = 8; // long long
  4770. } else {
  4771. argSize = 4; // long
  4772. }
  4773. break;
  4774. case 'L': // long long
  4775. case 'q': // int64_t
  4776. case 'j': // intmax_t
  4777. argSize = 8;
  4778. break;
  4779. case 'z': // size_t
  4780. case 't': // ptrdiff_t
  4781. case 'I': // signed ptrdiff_t or unsigned size_t
  4782. argSize = 4;
  4783. break;
  4784. default:
  4785. argSize = null;
  4786. }
  4787. if (argSize) textIndex++;
  4788. next = HEAP8[((textIndex+1)|0)];
  4789. // Handle type specifier.
  4790. switch (String.fromCharCode(next)) {
  4791. case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': {
  4792. // Integer.
  4793. var signed = next == 100 || next == 105;
  4794. argSize = argSize || 4;
  4795. var currArg = getNextArg('i' + (argSize * 8));
  4796. var argText;
  4797. // Flatten i64-1 [low, high] into a (slightly rounded) double
  4798. if (argSize == 8) {
  4799. currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117);
  4800. }
  4801. // Truncate to requested size.
  4802. if (argSize <= 4) {
  4803. var limit = Math.pow(256, argSize) - 1;
  4804. currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
  4805. }
  4806. // Format the number.
  4807. var currAbsArg = Math.abs(currArg);
  4808. var prefix = '';
  4809. if (next == 100 || next == 105) {
  4810. argText = reSign(currArg, 8 * argSize, 1).toString(10);
  4811. } else if (next == 117) {
  4812. argText = unSign(currArg, 8 * argSize, 1).toString(10);
  4813. currArg = Math.abs(currArg);
  4814. } else if (next == 111) {
  4815. argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
  4816. } else if (next == 120 || next == 88) {
  4817. prefix = (flagAlternative && currArg != 0) ? '0x' : '';
  4818. if (currArg < 0) {
  4819. // Represent negative numbers in hex as 2's complement.
  4820. currArg = -currArg;
  4821. argText = (currAbsArg - 1).toString(16);
  4822. var buffer = [];
  4823. for (var i = 0; i < argText.length; i++) {
  4824. buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
  4825. }
  4826. argText = buffer.join('');
  4827. while (argText.length < argSize * 2) argText = 'f' + argText;
  4828. } else {
  4829. argText = currAbsArg.toString(16);
  4830. }
  4831. if (next == 88) {
  4832. prefix = prefix.toUpperCase();
  4833. argText = argText.toUpperCase();
  4834. }
  4835. } else if (next == 112) {
  4836. if (currAbsArg === 0) {
  4837. argText = '(nil)';
  4838. } else {
  4839. prefix = '0x';
  4840. argText = currAbsArg.toString(16);
  4841. }
  4842. }
  4843. if (precisionSet) {
  4844. while (argText.length < precision) {
  4845. argText = '0' + argText;
  4846. }
  4847. }
  4848. // Add sign if needed
  4849. if (currArg >= 0) {
  4850. if (flagAlwaysSigned) {
  4851. prefix = '+' + prefix;
  4852. } else if (flagPadSign) {
  4853. prefix = ' ' + prefix;
  4854. }
  4855. }
  4856. // Move sign to prefix so we zero-pad after the sign
  4857. if (argText.charAt(0) == '-') {
  4858. prefix = '-' + prefix;
  4859. argText = argText.substr(1);
  4860. }
  4861. // Add padding.
  4862. while (prefix.length + argText.length < width) {
  4863. if (flagLeftAlign) {
  4864. argText += ' ';
  4865. } else {
  4866. if (flagZeroPad) {
  4867. argText = '0' + argText;
  4868. } else {
  4869. prefix = ' ' + prefix;
  4870. }
  4871. }
  4872. }
  4873. // Insert the result into the buffer.
  4874. argText = prefix + argText;
  4875. argText.split('').forEach(function(chr) {
  4876. ret.push(chr.charCodeAt(0));
  4877. });
  4878. break;
  4879. }
  4880. case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': {
  4881. // Float.
  4882. var currArg = getNextArg('double');
  4883. var argText;
  4884. if (isNaN(currArg)) {
  4885. argText = 'nan';
  4886. flagZeroPad = false;
  4887. } else if (!isFinite(currArg)) {
  4888. argText = (currArg < 0 ? '-' : '') + 'inf';
  4889. flagZeroPad = false;
  4890. } else {
  4891. var isGeneral = false;
  4892. var effectivePrecision = Math.min(precision, 20);
  4893. // Convert g/G to f/F or e/E, as per:
  4894. // http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
  4895. if (next == 103 || next == 71) {
  4896. isGeneral = true;
  4897. precision = precision || 1;
  4898. var exponent = parseInt(currArg.toExponential(effectivePrecision).split('e')[1], 10);
  4899. if (precision > exponent && exponent >= -4) {
  4900. next = ((next == 103) ? 'f' : 'F').charCodeAt(0);
  4901. precision -= exponent + 1;
  4902. } else {
  4903. next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
  4904. precision--;
  4905. }
  4906. effectivePrecision = Math.min(precision, 20);
  4907. }
  4908. if (next == 101 || next == 69) {
  4909. argText = currArg.toExponential(effectivePrecision);
  4910. // Make sure the exponent has at least 2 digits.
  4911. if (/[eE][-+]\d$/.test(argText)) {
  4912. argText = argText.slice(0, -1) + '0' + argText.slice(-1);
  4913. }
  4914. } else if (next == 102 || next == 70) {
  4915. argText = currArg.toFixed(effectivePrecision);
  4916. if (currArg === 0 && __reallyNegative(currArg)) {
  4917. argText = '-' + argText;
  4918. }
  4919. }
  4920. var parts = argText.split('e');
  4921. if (isGeneral && !flagAlternative) {
  4922. // Discard trailing zeros and periods.
  4923. while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
  4924. (parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.')) {
  4925. parts[0] = parts[0].slice(0, -1);
  4926. }
  4927. } else {
  4928. // Make sure we have a period in alternative mode.
  4929. if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
  4930. // Zero pad until required precision.
  4931. while (precision > effectivePrecision++) parts[0] += '0';
  4932. }
  4933. argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
  4934. // Capitalize 'E' if needed.
  4935. if (next == 69) argText = argText.toUpperCase();
  4936. // Add sign.
  4937. if (currArg >= 0) {
  4938. if (flagAlwaysSigned) {
  4939. argText = '+' + argText;
  4940. } else if (flagPadSign) {
  4941. argText = ' ' + argText;
  4942. }
  4943. }
  4944. }
  4945. // Add padding.
  4946. while (argText.length < width) {
  4947. if (flagLeftAlign) {
  4948. argText += ' ';
  4949. } else {
  4950. if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
  4951. argText = argText[0] + '0' + argText.slice(1);
  4952. } else {
  4953. argText = (flagZeroPad ? '0' : ' ') + argText;
  4954. }
  4955. }
  4956. }
  4957. // Adjust case.
  4958. if (next < 97) argText = argText.toUpperCase();
  4959. // Insert the result into the buffer.
  4960. argText.split('').forEach(function(chr) {
  4961. ret.push(chr.charCodeAt(0));
  4962. });
  4963. break;
  4964. }
  4965. case 's': {
  4966. // String.
  4967. var arg = getNextArg('i8*');
  4968. var argLength = arg ? _strlen(arg) : '(null)'.length;
  4969. if (precisionSet) argLength = Math.min(argLength, precision);
  4970. if (!flagLeftAlign) {
  4971. while (argLength < width--) {
  4972. ret.push(32);
  4973. }
  4974. }
  4975. if (arg) {
  4976. for (var i = 0; i < argLength; i++) {
  4977. ret.push(HEAPU8[((arg++)|0)]);
  4978. }
  4979. } else {
  4980. ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true));
  4981. }
  4982. if (flagLeftAlign) {
  4983. while (argLength < width--) {
  4984. ret.push(32);
  4985. }
  4986. }
  4987. break;
  4988. }
  4989. case 'c': {
  4990. // Character.
  4991. if (flagLeftAlign) ret.push(getNextArg('i8'));
  4992. while (--width > 0) {
  4993. ret.push(32);
  4994. }
  4995. if (!flagLeftAlign) ret.push(getNextArg('i8'));
  4996. break;
  4997. }
  4998. case 'n': {
  4999. // Write the length written so far to the next parameter.
  5000. var ptr = getNextArg('i32*');
  5001. HEAP32[((ptr)>>2)]=ret.length;
  5002. break;
  5003. }
  5004. case '%': {
  5005. // Literal percent sign.
  5006. ret.push(curr);
  5007. break;
  5008. }
  5009. default: {
  5010. // Unknown specifiers remain untouched.
  5011. for (var i = startTextIndex; i < textIndex + 2; i++) {
  5012. ret.push(HEAP8[(i)]);
  5013. }
  5014. }
  5015. }
  5016. textIndex += 2;
  5017. // TODO: Support a/A (hex float) and m (last error) specifiers.
  5018. // TODO: Support %1${specifier} for arg selection.
  5019. } else {
  5020. ret.push(curr);
  5021. textIndex += 1;
  5022. }
  5023. }
  5024. return ret;
  5025. }function _fprintf(stream, format, varargs) {
  5026. // int fprintf(FILE *restrict stream, const char *restrict format, ...);
  5027. // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
  5028. var result = __formatString(format, varargs);
  5029. var stack = Runtime.stackSave();
  5030. var ret = _fwrite(allocate(result, 'i8', ALLOC_STACK), 1, result.length, stream);
  5031. Runtime.stackRestore(stack);
  5032. return ret;
  5033. }function _printf(format, varargs) {
  5034. // int printf(const char *restrict format, ...);
  5035. // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
  5036. var stdout = HEAP32[((_stdout)>>2)];
  5037. return _fprintf(stdout, format, varargs);
  5038. }
  5039. Module["_memset"] = _memset;
  5040. function _emscripten_memcpy_big(dest, src, num) {
  5041. HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
  5042. return dest;
  5043. }
  5044. Module["_memcpy"] = _memcpy;
  5045. function _free() {
  5046. }
  5047. Module["_free"] = _free;
  5048. Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, resizeCanvas) { Browser.requestFullScreen(lockPointer, resizeCanvas) };
  5049. Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
  5050. Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };
  5051. Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };
  5052. Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };
  5053. Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }
  5054. 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;
  5055. ___errno_state = Runtime.staticAlloc(4); HEAP32[((___errno_state)>>2)]=0;
  5056. __ATINIT__.unshift({ func: function() { TTY.init() } });__ATEXIT__.push({ func: function() { TTY.shutdown() } });TTY.utf8 = new Runtime.UTF8Processor();
  5057. if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); NODEFS.staticInit(); }
  5058. __ATINIT__.push({ func: function() { SOCKFS.root = FS.mount(SOCKFS, {}, null); } });
  5059. STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
  5060. staticSealed = true; // seal the static portion of memory
  5061. STACK_MAX = STACK_BASE + 5242880;
  5062. DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
  5063. assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
  5064. var Math_min = Math.min;
  5065. function asmPrintInt(x, y) {
  5066. Module.print('int ' + x + ',' + y);// + ' ' + new Error().stack);
  5067. }
  5068. function asmPrintFloat(x, y) {
  5069. Module.print('float ' + x + ',' + y);// + ' ' + new Error().stack);
  5070. }
  5071. // EMSCRIPTEN_START_ASM
  5072. var asm = (function(global, env, buffer) {
  5073. 'use asm';
  5074. var HEAP8 = new global.Int8Array(buffer);
  5075. var HEAP16 = new global.Int16Array(buffer);
  5076. var HEAP32 = new global.Int32Array(buffer);
  5077. var HEAPU8 = new global.Uint8Array(buffer);
  5078. var HEAPU16 = new global.Uint16Array(buffer);
  5079. var HEAPU32 = new global.Uint32Array(buffer);
  5080. var HEAPF32 = new global.Float32Array(buffer);
  5081. var HEAPF64 = new global.Float64Array(buffer);
  5082. var STACKTOP=env.STACKTOP|0;
  5083. var STACK_MAX=env.STACK_MAX|0;
  5084. var tempDoublePtr=env.tempDoublePtr|0;
  5085. var ABORT=env.ABORT|0;
  5086. var __THREW__ = 0;
  5087. var threwValue = 0;
  5088. var setjmpId = 0;
  5089. var undef = 0;
  5090. var nan = +env.NaN, inf = +env.Infinity;
  5091. var tempInt = 0, tempBigInt = 0, tempBigIntP = 0, tempBigIntS = 0, tempBigIntR = 0.0, tempBigIntI = 0, tempBigIntD = 0, tempValue = 0, tempDouble = 0.0;
  5092. var tempRet0 = 0;
  5093. var tempRet1 = 0;
  5094. var tempRet2 = 0;
  5095. var tempRet3 = 0;
  5096. var tempRet4 = 0;
  5097. var tempRet5 = 0;
  5098. var tempRet6 = 0;
  5099. var tempRet7 = 0;
  5100. var tempRet8 = 0;
  5101. var tempRet9 = 0;
  5102. var Math_floor=global.Math.floor;
  5103. var Math_abs=global.Math.abs;
  5104. var Math_sqrt=global.Math.sqrt;
  5105. var Math_pow=global.Math.pow;
  5106. var Math_cos=global.Math.cos;
  5107. var Math_sin=global.Math.sin;
  5108. var Math_tan=global.Math.tan;
  5109. var Math_acos=global.Math.acos;
  5110. var Math_asin=global.Math.asin;
  5111. var Math_atan=global.Math.atan;
  5112. var Math_atan2=global.Math.atan2;
  5113. var Math_exp=global.Math.exp;
  5114. var Math_log=global.Math.log;
  5115. var Math_ceil=global.Math.ceil;
  5116. var Math_imul=global.Math.imul;
  5117. var abort=env.abort;
  5118. var assert=env.assert;
  5119. var asmPrintInt=env.asmPrintInt;
  5120. var asmPrintFloat=env.asmPrintFloat;
  5121. var Math_min=env.min;
  5122. var _free=env._free;
  5123. var _emscripten_memcpy_big=env._emscripten_memcpy_big;
  5124. var _printf=env._printf;
  5125. var _send=env._send;
  5126. var _pwrite=env._pwrite;
  5127. var __reallyNegative=env.__reallyNegative;
  5128. var _fwrite=env._fwrite;
  5129. var _malloc=env._malloc;
  5130. var _mkport=env._mkport;
  5131. var _fprintf=env._fprintf;
  5132. var ___setErrNo=env.___setErrNo;
  5133. var __formatString=env.__formatString;
  5134. var _fileno=env._fileno;
  5135. var _fflush=env._fflush;
  5136. var _write=env._write;
  5137. var tempFloat = 0.0;
  5138. // EMSCRIPTEN_START_FUNCS
  5139. function _main(i3, i5) {
  5140. i3 = i3 | 0;
  5141. i5 = i5 | 0;
  5142. var i1 = 0, i2 = 0, i4 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0, i10 = 0, i11 = 0, i12 = 0, i13 = 0, i14 = 0, i15 = 0, i16 = 0, i17 = 0, i18 = 0, i19 = 0;
  5143. i1 = STACKTOP;
  5144. STACKTOP = STACKTOP + 16 | 0;
  5145. i2 = i1;
  5146. L1 : do {
  5147. if ((i3 | 0) > 1) {
  5148. i3 = HEAP8[HEAP32[i5 + 4 >> 2] | 0] | 0;
  5149. switch (i3 | 0) {
  5150. case 50:
  5151. {
  5152. i3 = 625;
  5153. break L1;
  5154. }
  5155. case 51:
  5156. {
  5157. i4 = 4;
  5158. break L1;
  5159. }
  5160. case 52:
  5161. {
  5162. i3 = 6250;
  5163. break L1;
  5164. }
  5165. case 53:
  5166. {
  5167. i3 = 12500;
  5168. break L1;
  5169. }
  5170. case 49:
  5171. {
  5172. i3 = 75;
  5173. break L1;
  5174. }
  5175. case 48:
  5176. {
  5177. i12 = 0;
  5178. STACKTOP = i1;
  5179. return i12 | 0;
  5180. }
  5181. default:
  5182. {
  5183. HEAP32[i2 >> 2] = i3 + -48;
  5184. _printf(8, i2 | 0) | 0;
  5185. i12 = -1;
  5186. STACKTOP = i1;
  5187. return i12 | 0;
  5188. }
  5189. }
  5190. } else {
  5191. i4 = 4;
  5192. }
  5193. } while (0);
  5194. if ((i4 | 0) == 4) {
  5195. i3 = 1250;
  5196. }
  5197. i4 = 0;
  5198. i12 = 0;
  5199. do {
  5200. i9 = (i4 | 0) % 10 | 0;
  5201. i5 = i9 + i4 | 0;
  5202. i6 = (i4 | 0) % 255 | 0;
  5203. i8 = (i4 | 0) % 15 | 0;
  5204. i10 = ((i4 | 0) % 120 | 0 | 0) % 1024 | 0;
  5205. i11 = ((i4 | 0) % 1024 | 0) + i4 | 0;
  5206. i5 = ((i5 | 0) % 1024 | 0) + i5 | 0;
  5207. i8 = ((i8 | 0) % 1024 | 0) + i8 | 0;
  5208. i6 = (((i6 | 0) % 1024 | 0) + i6 + i10 | 0) % 1024 | 0;
  5209. i7 = 0;
  5210. do {
  5211. i17 = i7 << 1;
  5212. i14 = (i7 | 0) % 120 | 0;
  5213. i18 = (i17 | 0) % 1024 | 0;
  5214. i19 = (i9 + i7 | 0) % 1024 | 0;
  5215. i16 = ((i7 | 0) % 255 | 0 | 0) % 1024 | 0;
  5216. i15 = (i7 | 0) % 1024 | 0;
  5217. i13 = ((i7 | 0) % 15 | 0 | 0) % 1024 | 0;
  5218. i12 = (((i19 + i18 + i16 + i10 + i15 + i13 + ((i11 + i19 | 0) % 1024 | 0) + ((i5 + i18 | 0) % 1024 | 0) + ((i18 + i17 + i16 | 0) % 1024 | 0) + i6 + ((i8 + i15 | 0) % 1024 | 0) + ((((i14 | 0) % 1024 | 0) + i14 + i13 | 0) % 1024 | 0) | 0) % 100 | 0) + i12 | 0) % 10240 | 0;
  5219. i7 = i7 + 1 | 0;
  5220. } while ((i7 | 0) != 5e4);
  5221. i4 = i4 + 1 | 0;
  5222. } while ((i4 | 0) < (i3 | 0));
  5223. HEAP32[i2 >> 2] = i12;
  5224. _printf(24, i2 | 0) | 0;
  5225. i19 = 0;
  5226. STACKTOP = i1;
  5227. return i19 | 0;
  5228. }
  5229. function _memcpy(i3, i2, i1) {
  5230. i3 = i3 | 0;
  5231. i2 = i2 | 0;
  5232. i1 = i1 | 0;
  5233. var i4 = 0;
  5234. if ((i1 | 0) >= 4096) return _emscripten_memcpy_big(i3 | 0, i2 | 0, i1 | 0) | 0;
  5235. i4 = i3 | 0;
  5236. if ((i3 & 3) == (i2 & 3)) {
  5237. while (i3 & 3) {
  5238. if ((i1 | 0) == 0) return i4 | 0;
  5239. HEAP8[i3] = HEAP8[i2] | 0;
  5240. i3 = i3 + 1 | 0;
  5241. i2 = i2 + 1 | 0;
  5242. i1 = i1 - 1 | 0;
  5243. }
  5244. while ((i1 | 0) >= 4) {
  5245. HEAP32[i3 >> 2] = HEAP32[i2 >> 2];
  5246. i3 = i3 + 4 | 0;
  5247. i2 = i2 + 4 | 0;
  5248. i1 = i1 - 4 | 0;
  5249. }
  5250. }
  5251. while ((i1 | 0) > 0) {
  5252. HEAP8[i3] = HEAP8[i2] | 0;
  5253. i3 = i3 + 1 | 0;
  5254. i2 = i2 + 1 | 0;
  5255. i1 = i1 - 1 | 0;
  5256. }
  5257. return i4 | 0;
  5258. }
  5259. function _memset(i1, i4, i3) {
  5260. i1 = i1 | 0;
  5261. i4 = i4 | 0;
  5262. i3 = i3 | 0;
  5263. var i2 = 0, i5 = 0, i6 = 0, i7 = 0;
  5264. i2 = i1 + i3 | 0;
  5265. if ((i3 | 0) >= 20) {
  5266. i4 = i4 & 255;
  5267. i7 = i1 & 3;
  5268. i6 = i4 | i4 << 8 | i4 << 16 | i4 << 24;
  5269. i5 = i2 & ~3;
  5270. if (i7) {
  5271. i7 = i1 + 4 - i7 | 0;
  5272. while ((i1 | 0) < (i7 | 0)) {
  5273. HEAP8[i1] = i4;
  5274. i1 = i1 + 1 | 0;
  5275. }
  5276. }
  5277. while ((i1 | 0) < (i5 | 0)) {
  5278. HEAP32[i1 >> 2] = i6;
  5279. i1 = i1 + 4 | 0;
  5280. }
  5281. }
  5282. while ((i1 | 0) < (i2 | 0)) {
  5283. HEAP8[i1] = i4;
  5284. i1 = i1 + 1 | 0;
  5285. }
  5286. return i1 - i3 | 0;
  5287. }
  5288. function copyTempDouble(i1) {
  5289. i1 = i1 | 0;
  5290. HEAP8[tempDoublePtr] = HEAP8[i1];
  5291. HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
  5292. HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
  5293. HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
  5294. HEAP8[tempDoublePtr + 4 | 0] = HEAP8[i1 + 4 | 0];
  5295. HEAP8[tempDoublePtr + 5 | 0] = HEAP8[i1 + 5 | 0];
  5296. HEAP8[tempDoublePtr + 6 | 0] = HEAP8[i1 + 6 | 0];
  5297. HEAP8[tempDoublePtr + 7 | 0] = HEAP8[i1 + 7 | 0];
  5298. }
  5299. function copyTempFloat(i1) {
  5300. i1 = i1 | 0;
  5301. HEAP8[tempDoublePtr] = HEAP8[i1];
  5302. HEAP8[tempDoublePtr + 1 | 0] = HEAP8[i1 + 1 | 0];
  5303. HEAP8[tempDoublePtr + 2 | 0] = HEAP8[i1 + 2 | 0];
  5304. HEAP8[tempDoublePtr + 3 | 0] = HEAP8[i1 + 3 | 0];
  5305. }
  5306. function runPostSets() {}
  5307. function _strlen(i1) {
  5308. i1 = i1 | 0;
  5309. var i2 = 0;
  5310. i2 = i1;
  5311. while (HEAP8[i2] | 0) {
  5312. i2 = i2 + 1 | 0;
  5313. }
  5314. return i2 - i1 | 0;
  5315. }
  5316. function stackAlloc(i1) {
  5317. i1 = i1 | 0;
  5318. var i2 = 0;
  5319. i2 = STACKTOP;
  5320. STACKTOP = STACKTOP + i1 | 0;
  5321. STACKTOP = STACKTOP + 7 & -8;
  5322. return i2 | 0;
  5323. }
  5324. function setThrew(i1, i2) {
  5325. i1 = i1 | 0;
  5326. i2 = i2 | 0;
  5327. if ((__THREW__ | 0) == 0) {
  5328. __THREW__ = i1;
  5329. threwValue = i2;
  5330. }
  5331. }
  5332. function stackRestore(i1) {
  5333. i1 = i1 | 0;
  5334. STACKTOP = i1;
  5335. }
  5336. function setTempRet9(i1) {
  5337. i1 = i1 | 0;
  5338. tempRet9 = i1;
  5339. }
  5340. function setTempRet8(i1) {
  5341. i1 = i1 | 0;
  5342. tempRet8 = i1;
  5343. }
  5344. function setTempRet7(i1) {
  5345. i1 = i1 | 0;
  5346. tempRet7 = i1;
  5347. }
  5348. function setTempRet6(i1) {
  5349. i1 = i1 | 0;
  5350. tempRet6 = i1;
  5351. }
  5352. function setTempRet5(i1) {
  5353. i1 = i1 | 0;
  5354. tempRet5 = i1;
  5355. }
  5356. function setTempRet4(i1) {
  5357. i1 = i1 | 0;
  5358. tempRet4 = i1;
  5359. }
  5360. function setTempRet3(i1) {
  5361. i1 = i1 | 0;
  5362. tempRet3 = i1;
  5363. }
  5364. function setTempRet2(i1) {
  5365. i1 = i1 | 0;
  5366. tempRet2 = i1;
  5367. }
  5368. function setTempRet1(i1) {
  5369. i1 = i1 | 0;
  5370. tempRet1 = i1;
  5371. }
  5372. function setTempRet0(i1) {
  5373. i1 = i1 | 0;
  5374. tempRet0 = i1;
  5375. }
  5376. function stackSave() {
  5377. return STACKTOP | 0;
  5378. }
  5379. // EMSCRIPTEN_END_FUNCS
  5380. 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 };
  5381. })
  5382. // EMSCRIPTEN_END_ASM
  5383. ({ "Math": Math, "Int8Array": Int8Array, "Int16Array": Int16Array, "Int32Array": Int32Array, "Uint8Array": Uint8Array, "Uint16Array": Uint16Array, "Uint32Array": Uint32Array, "Float32Array": Float32Array, "Float64Array": Float64Array }, { "abort": abort, "assert": assert, "asmPrintInt": asmPrintInt, "asmPrintFloat": asmPrintFloat, "min": Math_min, "_free": _free, "_emscripten_memcpy_big": _emscripten_memcpy_big, "_printf": _printf, "_send": _send, "_pwrite": _pwrite, "__reallyNegative": __reallyNegative, "_fwrite": _fwrite, "_malloc": _malloc, "_mkport": _mkport, "_fprintf": _fprintf, "___setErrNo": ___setErrNo, "__formatString": __formatString, "_fileno": _fileno, "_fflush": _fflush, "_write": _write, "STACKTOP": STACKTOP, "STACK_MAX": STACK_MAX, "tempDoublePtr": tempDoublePtr, "ABORT": ABORT, "NaN": NaN, "Infinity": Infinity }, buffer);
  5384. var _strlen = Module["_strlen"] = asm["_strlen"];
  5385. var _memcpy = Module["_memcpy"] = asm["_memcpy"];
  5386. var _main = Module["_main"] = asm["_main"];
  5387. var _memset = Module["_memset"] = asm["_memset"];
  5388. var runPostSets = Module["runPostSets"] = asm["runPostSets"];
  5389. Runtime.stackAlloc = function(size) { return asm['stackAlloc'](size) };
  5390. Runtime.stackSave = function() { return asm['stackSave']() };
  5391. Runtime.stackRestore = function(top) { asm['stackRestore'](top) };
  5392. // Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
  5393. var i64Math = null;
  5394. // === Auto-generated postamble setup entry stuff ===
  5395. if (memoryInitializer) {
  5396. if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
  5397. var data = Module['readBinary'](memoryInitializer);
  5398. HEAPU8.set(data, STATIC_BASE);
  5399. } else {
  5400. addRunDependency('memory initializer');
  5401. Browser.asyncLoad(memoryInitializer, function(data) {
  5402. HEAPU8.set(data, STATIC_BASE);
  5403. removeRunDependency('memory initializer');
  5404. }, function(data) {
  5405. throw 'could not load memory initializer ' + memoryInitializer;
  5406. });
  5407. }
  5408. }
  5409. function ExitStatus(status) {
  5410. this.name = "ExitStatus";
  5411. this.message = "Program terminated with exit(" + status + ")";
  5412. this.status = status;
  5413. };
  5414. ExitStatus.prototype = new Error();
  5415. ExitStatus.prototype.constructor = ExitStatus;
  5416. var initialStackTop;
  5417. var preloadStartTime = null;
  5418. var calledMain = false;
  5419. dependenciesFulfilled = function runCaller() {
  5420. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  5421. if (!Module['calledRun'] && shouldRunNow) run([].concat(Module["arguments"]));
  5422. if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  5423. }
  5424. Module['callMain'] = Module.callMain = function callMain(args) {
  5425. assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on __ATMAIN__)');
  5426. assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
  5427. args = args || [];
  5428. ensureInitRuntime();
  5429. var argc = args.length+1;
  5430. function pad() {
  5431. for (var i = 0; i < 4-1; i++) {
  5432. argv.push(0);
  5433. }
  5434. }
  5435. var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORMAL) ];
  5436. pad();
  5437. for (var i = 0; i < argc-1; i = i + 1) {
  5438. argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
  5439. pad();
  5440. }
  5441. argv.push(0);
  5442. argv = allocate(argv, 'i32', ALLOC_NORMAL);
  5443. initialStackTop = STACKTOP;
  5444. try {
  5445. var ret = Module['_main'](argc, argv, 0);
  5446. // if we're not running an evented main loop, it's time to exit
  5447. if (!Module['noExitRuntime']) {
  5448. exit(ret);
  5449. }
  5450. }
  5451. catch(e) {
  5452. if (e instanceof ExitStatus) {
  5453. // exit() throws this once it's done to make sure execution
  5454. // has been stopped completely
  5455. return;
  5456. } else if (e == 'SimulateInfiniteLoop') {
  5457. // running an evented main loop, don't immediately exit
  5458. Module['noExitRuntime'] = true;
  5459. return;
  5460. } else {
  5461. if (e && typeof e === 'object' && e.stack) Module.printErr('exception thrown: ' + [e, e.stack]);
  5462. throw e;
  5463. }
  5464. } finally {
  5465. calledMain = true;
  5466. }
  5467. }
  5468. function run(args) {
  5469. args = args || Module['arguments'];
  5470. if (preloadStartTime === null) preloadStartTime = Date.now();
  5471. if (runDependencies > 0) {
  5472. Module.printErr('run() called, but dependencies remain, so not running');
  5473. return;
  5474. }
  5475. preRun();
  5476. if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
  5477. if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
  5478. function doRun() {
  5479. if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
  5480. Module['calledRun'] = true;
  5481. ensureInitRuntime();
  5482. preMain();
  5483. if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
  5484. Module.printErr('pre-main prep time: ' + (Date.now() - preloadStartTime) + ' ms');
  5485. }
  5486. if (Module['_main'] && shouldRunNow) {
  5487. Module['callMain'](args);
  5488. }
  5489. postRun();
  5490. }
  5491. if (Module['setStatus']) {
  5492. Module['setStatus']('Running...');
  5493. setTimeout(function() {
  5494. setTimeout(function() {
  5495. Module['setStatus']('');
  5496. }, 1);
  5497. if (!ABORT) doRun();
  5498. }, 1);
  5499. } else {
  5500. doRun();
  5501. }
  5502. }
  5503. Module['run'] = Module.run = run;
  5504. function exit(status) {
  5505. ABORT = true;
  5506. EXITSTATUS = status;
  5507. STACKTOP = initialStackTop;
  5508. // exit the runtime
  5509. exitRuntime();
  5510. // TODO We should handle this differently based on environment.
  5511. // In the browser, the best we can do is throw an exception
  5512. // to halt execution, but in node we could process.exit and
  5513. // I'd imagine SM shell would have something equivalent.
  5514. // This would let us set a proper exit status (which
  5515. // would be great for checking test exit statuses).
  5516. // https://github.com/kripken/emscripten/issues/1371
  5517. // throw an exception to halt the current execution
  5518. throw new ExitStatus(status);
  5519. }
  5520. Module['exit'] = Module.exit = exit;
  5521. function abort(text) {
  5522. if (text) {
  5523. Module.print(text);
  5524. Module.printErr(text);
  5525. }
  5526. ABORT = true;
  5527. EXITSTATUS = 1;
  5528. var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
  5529. throw 'abort() at ' + stackTrace() + extra;
  5530. }
  5531. Module['abort'] = Module.abort = abort;
  5532. // {{PRE_RUN_ADDITIONS}}
  5533. if (Module['preInit']) {
  5534. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  5535. while (Module['preInit'].length > 0) {
  5536. Module['preInit'].pop()();
  5537. }
  5538. }
  5539. // shouldRunNow refers to calling main(), not run().
  5540. var shouldRunNow = true;
  5541. if (Module['noInitialRun']) {
  5542. shouldRunNow = false;
  5543. }
  5544. run([].concat(Module["arguments"]));