Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(4)

Side by Side Diff: test/mjsunit/asm/embenchen/primes.js

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

Powered by Google App Engine
This is Rietveld 408576698