PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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ā€¦

Large files files are truncated, but you can click here to view the full file