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

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

Powered by Google App Engine
This is Rietveld 408576698