hunspell.mjs 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780
  1. var Module = (() => {
  2. var _scriptName = import.meta.url;
  3. return (
  4. function(moduleArg = {}) {
  5. var moduleRtn;
  6. // include: shell.js
  7. // The Module object: Our interface to the outside world. We import
  8. // and export values on it. There are various ways Module can be used:
  9. // 1. Not defined. We create it here
  10. // 2. A function parameter, function(moduleArg) => Promise<Module>
  11. // 3. pre-run appended it, var Module = {}; ..generated code..
  12. // 4. External script tag defines var Module.
  13. // We need to check if Module already exists (e.g. case 3 above).
  14. // Substitution will be replaced with actual code on later stage of the build,
  15. // this way Closure Compiler will not mangle it (e.g. case 4. above).
  16. // Note that if you want to run closure, and also to use Module
  17. // after the generated code, you will need to define var Module = {};
  18. // before the code. Then that object will be used in the code, and you
  19. // can continue to use Module afterwards as well.
  20. var Module = moduleArg;
  21. // Set up the promise that indicates the Module is initialized
  22. var readyPromiseResolve, readyPromiseReject;
  23. var readyPromise = new Promise((resolve, reject) => {
  24. readyPromiseResolve = resolve;
  25. readyPromiseReject = reject;
  26. });
  27. // Determine the runtime environment we are in. You can customize this by
  28. // setting the ENVIRONMENT setting at compile time (see settings.js).
  29. var ENVIRONMENT_IS_WEB = false;
  30. var ENVIRONMENT_IS_WORKER = true;
  31. // --pre-jses are emitted after the Module integration code, so that they can
  32. // refer to Module (if they choose; they can also define Module)
  33. // Sometimes an existing Module object exists with properties
  34. // meant to overwrite the default module functionality. Here
  35. // we collect those properties and reapply _after_ we configure
  36. // the current environment's defaults to avoid having to be so
  37. // defensive during initialization.
  38. var moduleOverrides = Object.assign({}, Module);
  39. var arguments_ = [];
  40. var thisProgram = "./this.program";
  41. // `/` should be present at the end if `scriptDirectory` is not empty
  42. var scriptDirectory = "";
  43. function locateFile(path) {
  44. if (Module["locateFile"]) {
  45. return Module["locateFile"](path, scriptDirectory);
  46. }
  47. return scriptDirectory + path;
  48. }
  49. // Hooks that are implemented differently in different runtime environments.
  50. var readAsync, readBinary;
  51. // Note that this includes Node.js workers when relevant (pthreads is enabled).
  52. // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
  53. // ENVIRONMENT_IS_NODE.
  54. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  55. if (ENVIRONMENT_IS_WORKER) {
  56. // Check worker, not web, since window could be polyfilled
  57. scriptDirectory = self.location.href;
  58. } else if (typeof document != "undefined" && document.currentScript) {
  59. // web
  60. scriptDirectory = document.currentScript.src;
  61. }
  62. // When MODULARIZE, this JS may be executed later, after document.currentScript
  63. // is gone, so we saved it, and we use it here instead of any other info.
  64. if (_scriptName) {
  65. scriptDirectory = _scriptName;
  66. }
  67. // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
  68. // otherwise, slice off the final part of the url to find the script directory.
  69. // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
  70. // and scriptDirectory will correctly be replaced with an empty string.
  71. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),
  72. // they are removed because they could contain a slash.
  73. if (scriptDirectory.startsWith("blob:")) {
  74. scriptDirectory = "";
  75. } else {
  76. scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
  77. }
  78. {
  79. // include: web_or_worker_shell_read.js
  80. if (ENVIRONMENT_IS_WORKER) {
  81. readBinary = url => {
  82. var xhr = new XMLHttpRequest;
  83. xhr.open("GET", url, false);
  84. xhr.responseType = "arraybuffer";
  85. xhr.send(null);
  86. return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));
  87. };
  88. }
  89. readAsync = url => fetch(url, {
  90. credentials: "same-origin"
  91. }).then(response => {
  92. if (response.ok) {
  93. return response.arrayBuffer();
  94. }
  95. return Promise.reject(new Error(response.status + " : " + response.url));
  96. });
  97. }
  98. } else // end include: web_or_worker_shell_read.js
  99. {}
  100. var out = Module["print"] || console.log.bind(console);
  101. var err = Module["printErr"] || console.error.bind(console);
  102. // Merge back in the overrides
  103. Object.assign(Module, moduleOverrides);
  104. // Free the object hierarchy contained in the overrides, this lets the GC
  105. // reclaim data used.
  106. moduleOverrides = null;
  107. // Emit code to handle expected values on the Module object. This applies Module.x
  108. // to the proper local x. This has two benefits: first, we only emit it if it is
  109. // expected to arrive, and second, by using a local everywhere else that can be
  110. // minified.
  111. if (Module["arguments"]) arguments_ = Module["arguments"];
  112. if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
  113. // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
  114. // end include: shell.js
  115. // include: preamble.js
  116. // === Preamble library stuff ===
  117. // Documentation for the public APIs defined in this file must be updated in:
  118. // site/source/docs/api_reference/preamble.js.rst
  119. // A prebuilt local version of the documentation is available at:
  120. // site/build/text/docs/api_reference/preamble.js.txt
  121. // You can also build docs locally as HTML or other formats in site/
  122. // An online HTML version (which may be of a different version of Emscripten)
  123. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  124. var wasmBinary = Module["wasmBinary"];
  125. // Wasm globals
  126. var wasmMemory;
  127. //========================================
  128. // Runtime essentials
  129. //========================================
  130. // whether we are quitting the application. no code should run after this.
  131. // set in exit() and abort()
  132. var ABORT = false;
  133. // Memory management
  134. var /** @type {!Int8Array} */ HEAP8, /** @type {!Uint8Array} */ HEAPU8, /** @type {!Int16Array} */ HEAP16, /** @type {!Uint16Array} */ HEAPU16, /** @type {!Int32Array} */ HEAP32, /** @type {!Uint32Array} */ HEAPU32, /** @type {!Float32Array} */ HEAPF32, /** @type {!Float64Array} */ HEAPF64;
  135. // include: runtime_shared.js
  136. function updateMemoryViews() {
  137. var b = wasmMemory.buffer;
  138. Module["HEAP8"] = HEAP8 = new Int8Array(b);
  139. Module["HEAP16"] = HEAP16 = new Int16Array(b);
  140. Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
  141. Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
  142. Module["HEAP32"] = HEAP32 = new Int32Array(b);
  143. Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
  144. Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
  145. Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
  146. }
  147. // end include: runtime_shared.js
  148. // include: runtime_stack_check.js
  149. // end include: runtime_stack_check.js
  150. var __ATPRERUN__ = [];
  151. // functions called before the runtime is initialized
  152. var __ATINIT__ = [];
  153. // functions called during shutdown
  154. var __ATPOSTRUN__ = [];
  155. // functions called after the main() is called
  156. var runtimeInitialized = false;
  157. function preRun() {
  158. if (Module["preRun"]) {
  159. if (typeof Module["preRun"] == "function") Module["preRun"] = [ Module["preRun"] ];
  160. while (Module["preRun"].length) {
  161. addOnPreRun(Module["preRun"].shift());
  162. }
  163. }
  164. callRuntimeCallbacks(__ATPRERUN__);
  165. }
  166. function initRuntime() {
  167. runtimeInitialized = true;
  168. if (!Module["noFSInit"] && !FS.initialized) FS.init();
  169. FS.ignorePermissions = false;
  170. TTY.init();
  171. callRuntimeCallbacks(__ATINIT__);
  172. }
  173. function postRun() {
  174. if (Module["postRun"]) {
  175. if (typeof Module["postRun"] == "function") Module["postRun"] = [ Module["postRun"] ];
  176. while (Module["postRun"].length) {
  177. addOnPostRun(Module["postRun"].shift());
  178. }
  179. }
  180. callRuntimeCallbacks(__ATPOSTRUN__);
  181. }
  182. function addOnPreRun(cb) {
  183. __ATPRERUN__.unshift(cb);
  184. }
  185. function addOnInit(cb) {
  186. __ATINIT__.unshift(cb);
  187. }
  188. function addOnPostRun(cb) {
  189. __ATPOSTRUN__.unshift(cb);
  190. }
  191. // include: runtime_math.js
  192. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  193. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
  194. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
  195. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  196. // end include: runtime_math.js
  197. // A counter of dependencies for calling run(). If we need to
  198. // do asynchronous work before running, increment this and
  199. // decrement it. Incrementing must happen in a place like
  200. // Module.preRun (used by emcc to add file preloading).
  201. // Note that you can add dependencies in preRun, even though
  202. // it happens right before run - run will be postponed until
  203. // the dependencies are met.
  204. var runDependencies = 0;
  205. var runDependencyWatcher = null;
  206. var dependenciesFulfilled = null;
  207. // overridden to take different actions when all run dependencies are fulfilled
  208. function getUniqueRunDependency(id) {
  209. return id;
  210. }
  211. function addRunDependency(id) {
  212. runDependencies++;
  213. Module["monitorRunDependencies"]?.(runDependencies);
  214. }
  215. function removeRunDependency(id) {
  216. runDependencies--;
  217. Module["monitorRunDependencies"]?.(runDependencies);
  218. if (runDependencies == 0) {
  219. if (runDependencyWatcher !== null) {
  220. clearInterval(runDependencyWatcher);
  221. runDependencyWatcher = null;
  222. }
  223. if (dependenciesFulfilled) {
  224. var callback = dependenciesFulfilled;
  225. dependenciesFulfilled = null;
  226. callback();
  227. }
  228. }
  229. }
  230. /** @param {string|number=} what */ function abort(what) {
  231. Module["onAbort"]?.(what);
  232. what = "Aborted(" + what + ")";
  233. // TODO(sbc): Should we remove printing and leave it up to whoever
  234. // catches the exception?
  235. err(what);
  236. ABORT = true;
  237. what += ". Build with -sASSERTIONS for more info.";
  238. // Use a wasm runtime error, because a JS error might be seen as a foreign
  239. // exception, which means we'd run destructors on it. We need the error to
  240. // simply make the program stop.
  241. // FIXME This approach does not work in Wasm EH because it currently does not assume
  242. // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
  243. // a trap or not based on a hidden field within the object. So at the moment
  244. // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
  245. // allows this in the wasm spec.
  246. // Suppress closure compiler warning here. Closure compiler's builtin extern
  247. // definition for WebAssembly.RuntimeError claims it takes no arguments even
  248. // though it can.
  249. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
  250. /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);
  251. readyPromiseReject(e);
  252. // Throw the error whether or not MODULARIZE is set because abort is used
  253. // in code paths apart from instantiation where an exception is expected
  254. // to be thrown when abort is called.
  255. throw e;
  256. }
  257. // include: memoryprofiler.js
  258. // end include: memoryprofiler.js
  259. // include: URIUtils.js
  260. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  261. var dataURIPrefix = "data:application/octet-stream;base64,";
  262. /**
  263. * Indicates whether filename is a base64 data URI.
  264. * @noinline
  265. */ var isDataURI = filename => filename.startsWith(dataURIPrefix);
  266. // end include: URIUtils.js
  267. // include: runtime_exceptions.js
  268. // end include: runtime_exceptions.js
  269. function findWasmBinary() {
  270. if (Module["locateFile"]) {
  271. var f = "hunspell.wasm";
  272. if (!isDataURI(f)) {
  273. return locateFile(f);
  274. }
  275. return f;
  276. }
  277. // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too.
  278. return new URL("hunspell.wasm", import.meta.url).href;
  279. }
  280. var wasmBinaryFile;
  281. function getBinarySync(file) {
  282. if (file == wasmBinaryFile && wasmBinary) {
  283. return new Uint8Array(wasmBinary);
  284. }
  285. if (readBinary) {
  286. return readBinary(file);
  287. }
  288. throw "both async and sync fetching of the wasm failed";
  289. }
  290. function getBinaryPromise(binaryFile) {
  291. // If we don't have the binary yet, load it asynchronously using readAsync.
  292. if (!wasmBinary) {
  293. // Fetch the binary using readAsync
  294. return readAsync(binaryFile).then(response => new Uint8Array(/** @type{!ArrayBuffer} */ (response)), // Fall back to getBinarySync if readAsync fails
  295. () => getBinarySync(binaryFile));
  296. }
  297. // Otherwise, getBinarySync should be able to get it synchronously
  298. return Promise.resolve().then(() => getBinarySync(binaryFile));
  299. }
  300. function instantiateArrayBuffer(binaryFile, imports, receiver) {
  301. return getBinaryPromise(binaryFile).then(binary => WebAssembly.instantiate(binary, imports)).then(receiver, reason => {
  302. err(`failed to asynchronously prepare wasm: ${reason}`);
  303. abort(reason);
  304. });
  305. }
  306. function instantiateAsync(binary, binaryFile, imports, callback) {
  307. if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && typeof fetch == "function") {
  308. return fetch(binaryFile, {
  309. credentials: "same-origin"
  310. }).then(response => {
  311. // Suppress closure warning here since the upstream definition for
  312. // instantiateStreaming only allows Promise<Repsponse> rather than
  313. // an actual Response.
  314. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
  315. /** @suppress {checkTypes} */ var result = WebAssembly.instantiateStreaming(response, imports);
  316. return result.then(callback, function(reason) {
  317. // We expect the most common failure cause to be a bad MIME type for the binary,
  318. // in which case falling back to ArrayBuffer instantiation should work.
  319. err(`wasm streaming compile failed: ${reason}`);
  320. err("falling back to ArrayBuffer instantiation");
  321. return instantiateArrayBuffer(binaryFile, imports, callback);
  322. });
  323. });
  324. }
  325. return instantiateArrayBuffer(binaryFile, imports, callback);
  326. }
  327. function getWasmImports() {
  328. // prepare imports
  329. return {
  330. "env": wasmImports,
  331. "wasi_snapshot_preview1": wasmImports
  332. };
  333. }
  334. // Create the wasm instance.
  335. // Receives the wasm imports, returns the exports.
  336. function createWasm() {
  337. var info = getWasmImports();
  338. // Load the wasm module and create an instance of using native support in the JS engine.
  339. // handle a generated wasm instance, receiving its exports and
  340. // performing other necessary setup
  341. /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) {
  342. wasmExports = instance.exports;
  343. wasmMemory = wasmExports["memory"];
  344. updateMemoryViews();
  345. addOnInit(wasmExports["__wasm_call_ctors"]);
  346. removeRunDependency("wasm-instantiate");
  347. return wasmExports;
  348. }
  349. // wait for the pthread pool (if any)
  350. addRunDependency("wasm-instantiate");
  351. // Prefer streaming instantiation if available.
  352. function receiveInstantiationResult(result) {
  353. // 'result' is a ResultObject object which has both the module and instance.
  354. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  355. // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.
  356. // When the regression is fixed, can restore the above PTHREADS-enabled path.
  357. receiveInstance(result["instance"]);
  358. }
  359. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  360. // to manually instantiate the Wasm module themselves. This allows pages to
  361. // run the instantiation parallel to any other async startup actions they are
  362. // performing.
  363. // Also pthreads and wasm workers initialize the wasm instance through this
  364. // path.
  365. if (Module["instantiateWasm"]) {
  366. try {
  367. return Module["instantiateWasm"](info, receiveInstance);
  368. } catch (e) {
  369. err(`Module.instantiateWasm callback failed with error: ${e}`);
  370. // If instantiation fails, reject the module ready promise.
  371. readyPromiseReject(e);
  372. }
  373. }
  374. if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary();
  375. // If instantiation fails, reject the module ready promise.
  376. instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(readyPromiseReject);
  377. return {};
  378. }
  379. // Globals used by JS i64 conversions (see makeSetValue)
  380. var tempDouble;
  381. var tempI64;
  382. var callRuntimeCallbacks = callbacks => {
  383. while (callbacks.length > 0) {
  384. // Pass the module as the first argument.
  385. callbacks.shift()(Module);
  386. }
  387. };
  388. /**
  389. * @param {number} ptr
  390. * @param {string} type
  391. */ function getValue(ptr, type = "i8") {
  392. if (type.endsWith("*")) type = "*";
  393. switch (type) {
  394. case "i1":
  395. return HEAP8[ptr];
  396. case "i8":
  397. return HEAP8[ptr];
  398. case "i16":
  399. return HEAP16[((ptr) >> 1)];
  400. case "i32":
  401. return HEAP32[((ptr) >> 2)];
  402. case "i64":
  403. abort("to do getValue(i64) use WASM_BIGINT");
  404. case "float":
  405. return HEAPF32[((ptr) >> 2)];
  406. case "double":
  407. return HEAPF64[((ptr) >> 3)];
  408. case "*":
  409. return HEAPU32[((ptr) >> 2)];
  410. default:
  411. abort(`invalid type for getValue: ${type}`);
  412. }
  413. }
  414. var noExitRuntime = Module["noExitRuntime"] || true;
  415. var stackRestore = val => __emscripten_stack_restore(val);
  416. var stackSave = () => _emscripten_stack_get_current();
  417. var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder : undefined;
  418. /**
  419. * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given
  420. * array that contains uint8 values, returns a copy of that string as a
  421. * Javascript String object.
  422. * heapOrArray is either a regular array, or a JavaScript typed array view.
  423. * @param {number} idx
  424. * @param {number=} maxBytesToRead
  425. * @return {string}
  426. */ var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => {
  427. var endIdx = idx + maxBytesToRead;
  428. var endPtr = idx;
  429. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  430. // null terminator by itself. Also, use the length info to avoid running tiny
  431. // strings through TextDecoder, since .subarray() allocates garbage.
  432. // (As a tiny code save trick, compare endPtr against endIdx using a negation,
  433. // so that undefined means Infinity)
  434. while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
  435. if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
  436. return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
  437. }
  438. var str = "";
  439. // If building with TextDecoder, we have already computed the string length
  440. // above, so test loop end condition against that
  441. while (idx < endPtr) {
  442. // For UTF8 byte structure, see:
  443. // http://en.wikipedia.org/wiki/UTF-8#Description
  444. // https://www.ietf.org/rfc/rfc2279.txt
  445. // https://tools.ietf.org/html/rfc3629
  446. var u0 = heapOrArray[idx++];
  447. if (!(u0 & 128)) {
  448. str += String.fromCharCode(u0);
  449. continue;
  450. }
  451. var u1 = heapOrArray[idx++] & 63;
  452. if ((u0 & 224) == 192) {
  453. str += String.fromCharCode(((u0 & 31) << 6) | u1);
  454. continue;
  455. }
  456. var u2 = heapOrArray[idx++] & 63;
  457. if ((u0 & 240) == 224) {
  458. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  459. } else {
  460. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
  461. }
  462. if (u0 < 65536) {
  463. str += String.fromCharCode(u0);
  464. } else {
  465. var ch = u0 - 65536;
  466. str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023));
  467. }
  468. }
  469. return str;
  470. };
  471. /**
  472. * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the
  473. * emscripten HEAP, returns a copy of that string as a Javascript String object.
  474. *
  475. * @param {number} ptr
  476. * @param {number=} maxBytesToRead - An optional length that specifies the
  477. * maximum number of bytes to read. You can omit this parameter to scan the
  478. * string until the first 0 byte. If maxBytesToRead is passed, and the string
  479. * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the
  480. * string will cut short at that byte index (i.e. maxBytesToRead will not
  481. * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing
  482. * frequent uses of UTF8ToString() with and without maxBytesToRead may throw
  483. * JS JIT optimizations off, so it is worth to consider consistently using one
  484. * @return {string}
  485. */ var UTF8ToString = (ptr, maxBytesToRead) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
  486. var ___assert_fail = (condition, filename, line, func) => {
  487. abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [ filename ? UTF8ToString(filename) : "unknown filename", line, func ? UTF8ToString(func) : "unknown function" ]);
  488. };
  489. class ExceptionInfo {
  490. // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.
  491. constructor(excPtr) {
  492. this.excPtr = excPtr;
  493. this.ptr = excPtr - 24;
  494. }
  495. set_type(type) {
  496. HEAPU32[(((this.ptr) + (4)) >> 2)] = type;
  497. }
  498. get_type() {
  499. return HEAPU32[(((this.ptr) + (4)) >> 2)];
  500. }
  501. set_destructor(destructor) {
  502. HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor;
  503. }
  504. get_destructor() {
  505. return HEAPU32[(((this.ptr) + (8)) >> 2)];
  506. }
  507. set_caught(caught) {
  508. caught = caught ? 1 : 0;
  509. HEAP8[(this.ptr) + (12)] = caught;
  510. }
  511. get_caught() {
  512. return HEAP8[(this.ptr) + (12)] != 0;
  513. }
  514. set_rethrown(rethrown) {
  515. rethrown = rethrown ? 1 : 0;
  516. HEAP8[(this.ptr) + (13)] = rethrown;
  517. }
  518. get_rethrown() {
  519. return HEAP8[(this.ptr) + (13)] != 0;
  520. }
  521. // Initialize native structure fields. Should be called once after allocated.
  522. init(type, destructor) {
  523. this.set_adjusted_ptr(0);
  524. this.set_type(type);
  525. this.set_destructor(destructor);
  526. }
  527. set_adjusted_ptr(adjustedPtr) {
  528. HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr;
  529. }
  530. get_adjusted_ptr() {
  531. return HEAPU32[(((this.ptr) + (16)) >> 2)];
  532. }
  533. }
  534. var exceptionLast = 0;
  535. var uncaughtExceptionCount = 0;
  536. var ___cxa_throw = (ptr, type, destructor) => {
  537. var info = new ExceptionInfo(ptr);
  538. // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.
  539. info.init(type, destructor);
  540. exceptionLast = ptr;
  541. uncaughtExceptionCount++;
  542. throw exceptionLast;
  543. };
  544. /** @suppress {duplicate } */ function syscallGetVarargI() {
  545. // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.
  546. var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];
  547. SYSCALLS.varargs += 4;
  548. return ret;
  549. }
  550. var syscallGetVarargP = syscallGetVarargI;
  551. var PATH = {
  552. isAbs: path => path.charAt(0) === "/",
  553. splitPath: filename => {
  554. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  555. return splitPathRe.exec(filename).slice(1);
  556. },
  557. normalizeArray: (parts, allowAboveRoot) => {
  558. // if the path tries to go above the root, `up` ends up > 0
  559. var up = 0;
  560. for (var i = parts.length - 1; i >= 0; i--) {
  561. var last = parts[i];
  562. if (last === ".") {
  563. parts.splice(i, 1);
  564. } else if (last === "..") {
  565. parts.splice(i, 1);
  566. up++;
  567. } else if (up) {
  568. parts.splice(i, 1);
  569. up--;
  570. }
  571. }
  572. // if the path is allowed to go above the root, restore leading ..s
  573. if (allowAboveRoot) {
  574. for (;up; up--) {
  575. parts.unshift("..");
  576. }
  577. }
  578. return parts;
  579. },
  580. normalize: path => {
  581. var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === "/";
  582. // Normalize the path
  583. path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");
  584. if (!path && !isAbsolute) {
  585. path = ".";
  586. }
  587. if (path && trailingSlash) {
  588. path += "/";
  589. }
  590. return (isAbsolute ? "/" : "") + path;
  591. },
  592. dirname: path => {
  593. var result = PATH.splitPath(path), root = result[0], dir = result[1];
  594. if (!root && !dir) {
  595. // No dirname whatsoever
  596. return ".";
  597. }
  598. if (dir) {
  599. // It has a dirname, strip trailing slash
  600. dir = dir.substr(0, dir.length - 1);
  601. }
  602. return root + dir;
  603. },
  604. basename: path => {
  605. // EMSCRIPTEN return '/'' for '/', not an empty string
  606. if (path === "/") return "/";
  607. path = PATH.normalize(path);
  608. path = path.replace(/\/$/, "");
  609. var lastSlash = path.lastIndexOf("/");
  610. if (lastSlash === -1) return path;
  611. return path.substr(lastSlash + 1);
  612. },
  613. join: (...paths) => PATH.normalize(paths.join("/")),
  614. join2: (l, r) => PATH.normalize(l + "/" + r)
  615. };
  616. var initRandomFill = () => {
  617. if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {
  618. // for modern web browsers
  619. return view => crypto.getRandomValues(view);
  620. } else // we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096
  621. abort("initRandomDevice");
  622. };
  623. var randomFill = view => (randomFill = initRandomFill())(view);
  624. var PATH_FS = {
  625. resolve: (...args) => {
  626. var resolvedPath = "", resolvedAbsolute = false;
  627. for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  628. var path = (i >= 0) ? args[i] : FS.cwd();
  629. // Skip empty and invalid entries
  630. if (typeof path != "string") {
  631. throw new TypeError("Arguments to path.resolve must be strings");
  632. } else if (!path) {
  633. return "";
  634. }
  635. // an invalid portion invalidates the whole thing
  636. resolvedPath = path + "/" + resolvedPath;
  637. resolvedAbsolute = PATH.isAbs(path);
  638. }
  639. // At this point the path should be resolved to a full absolute path, but
  640. // handle relative paths to be safe (might happen when process.cwd() fails)
  641. resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");
  642. return ((resolvedAbsolute ? "/" : "") + resolvedPath) || ".";
  643. },
  644. relative: (from, to) => {
  645. from = PATH_FS.resolve(from).substr(1);
  646. to = PATH_FS.resolve(to).substr(1);
  647. function trim(arr) {
  648. var start = 0;
  649. for (;start < arr.length; start++) {
  650. if (arr[start] !== "") break;
  651. }
  652. var end = arr.length - 1;
  653. for (;end >= 0; end--) {
  654. if (arr[end] !== "") break;
  655. }
  656. if (start > end) return [];
  657. return arr.slice(start, end - start + 1);
  658. }
  659. var fromParts = trim(from.split("/"));
  660. var toParts = trim(to.split("/"));
  661. var length = Math.min(fromParts.length, toParts.length);
  662. var samePartsLength = length;
  663. for (var i = 0; i < length; i++) {
  664. if (fromParts[i] !== toParts[i]) {
  665. samePartsLength = i;
  666. break;
  667. }
  668. }
  669. var outputParts = [];
  670. for (var i = samePartsLength; i < fromParts.length; i++) {
  671. outputParts.push("..");
  672. }
  673. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  674. return outputParts.join("/");
  675. }
  676. };
  677. var FS_stdin_getChar_buffer = [];
  678. var lengthBytesUTF8 = str => {
  679. var len = 0;
  680. for (var i = 0; i < str.length; ++i) {
  681. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  682. // unit, not a Unicode code point of the character! So decode
  683. // UTF16->UTF32->UTF8.
  684. // See http://unicode.org/faq/utf_bom.html#utf16-3
  685. var c = str.charCodeAt(i);
  686. // possibly a lead surrogate
  687. if (c <= 127) {
  688. len++;
  689. } else if (c <= 2047) {
  690. len += 2;
  691. } else if (c >= 55296 && c <= 57343) {
  692. len += 4;
  693. ++i;
  694. } else {
  695. len += 3;
  696. }
  697. }
  698. return len;
  699. };
  700. var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
  701. // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
  702. // undefined and false each don't write out any bytes.
  703. if (!(maxBytesToWrite > 0)) return 0;
  704. var startIdx = outIdx;
  705. var endIdx = outIdx + maxBytesToWrite - 1;
  706. // -1 for string null terminator.
  707. for (var i = 0; i < str.length; ++i) {
  708. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  709. // unit, not a Unicode code point of the character! So decode
  710. // UTF16->UTF32->UTF8.
  711. // See http://unicode.org/faq/utf_bom.html#utf16-3
  712. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
  713. // and https://www.ietf.org/rfc/rfc2279.txt
  714. // and https://tools.ietf.org/html/rfc3629
  715. var u = str.charCodeAt(i);
  716. // possibly a lead surrogate
  717. if (u >= 55296 && u <= 57343) {
  718. var u1 = str.charCodeAt(++i);
  719. u = 65536 + ((u & 1023) << 10) | (u1 & 1023);
  720. }
  721. if (u <= 127) {
  722. if (outIdx >= endIdx) break;
  723. heap[outIdx++] = u;
  724. } else if (u <= 2047) {
  725. if (outIdx + 1 >= endIdx) break;
  726. heap[outIdx++] = 192 | (u >> 6);
  727. heap[outIdx++] = 128 | (u & 63);
  728. } else if (u <= 65535) {
  729. if (outIdx + 2 >= endIdx) break;
  730. heap[outIdx++] = 224 | (u >> 12);
  731. heap[outIdx++] = 128 | ((u >> 6) & 63);
  732. heap[outIdx++] = 128 | (u & 63);
  733. } else {
  734. if (outIdx + 3 >= endIdx) break;
  735. heap[outIdx++] = 240 | (u >> 18);
  736. heap[outIdx++] = 128 | ((u >> 12) & 63);
  737. heap[outIdx++] = 128 | ((u >> 6) & 63);
  738. heap[outIdx++] = 128 | (u & 63);
  739. }
  740. }
  741. // Null-terminate the pointer to the buffer.
  742. heap[outIdx] = 0;
  743. return outIdx - startIdx;
  744. };
  745. /** @type {function(string, boolean=, number=)} */ function intArrayFromString(stringy, dontAddNull, length) {
  746. var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
  747. var u8array = new Array(len);
  748. var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
  749. if (dontAddNull) u8array.length = numBytesWritten;
  750. return u8array;
  751. }
  752. var FS_stdin_getChar = () => {
  753. if (!FS_stdin_getChar_buffer.length) {
  754. var result = null;
  755. {}
  756. if (!result) {
  757. return null;
  758. }
  759. FS_stdin_getChar_buffer = intArrayFromString(result, true);
  760. }
  761. return FS_stdin_getChar_buffer.shift();
  762. };
  763. var TTY = {
  764. ttys: [],
  765. init() {},
  766. // https://github.com/emscripten-core/emscripten/pull/1555
  767. // if (ENVIRONMENT_IS_NODE) {
  768. // // currently, FS.init does not distinguish if process.stdin is a file or TTY
  769. // // device, it always assumes it's a TTY device. because of this, we're forcing
  770. // // process.stdin to UTF8 encoding to at least make stdin reading compatible
  771. // // with text files until FS.init can be refactored.
  772. // process.stdin.setEncoding('utf8');
  773. // }
  774. shutdown() {},
  775. // https://github.com/emscripten-core/emscripten/pull/1555
  776. // if (ENVIRONMENT_IS_NODE) {
  777. // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
  778. // // isaacs: because now it's reading from the stream, you've expressed interest in it, so that read() kicks off a _read() which creates a ReadReq operation
  779. // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
  780. // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
  781. // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
  782. // process.stdin.pause();
  783. // }
  784. register(dev, ops) {
  785. TTY.ttys[dev] = {
  786. input: [],
  787. output: [],
  788. ops
  789. };
  790. FS.registerDevice(dev, TTY.stream_ops);
  791. },
  792. stream_ops: {
  793. open(stream) {
  794. var tty = TTY.ttys[stream.node.rdev];
  795. if (!tty) {
  796. throw new FS.ErrnoError(43);
  797. }
  798. stream.tty = tty;
  799. stream.seekable = false;
  800. },
  801. close(stream) {
  802. // flush any pending line data
  803. stream.tty.ops.fsync(stream.tty);
  804. },
  805. fsync(stream) {
  806. stream.tty.ops.fsync(stream.tty);
  807. },
  808. read(stream, buffer, offset, length, pos) {
  809. /* ignored */ if (!stream.tty || !stream.tty.ops.get_char) {
  810. throw new FS.ErrnoError(60);
  811. }
  812. var bytesRead = 0;
  813. for (var i = 0; i < length; i++) {
  814. var result;
  815. try {
  816. result = stream.tty.ops.get_char(stream.tty);
  817. } catch (e) {
  818. throw new FS.ErrnoError(29);
  819. }
  820. if (result === undefined && bytesRead === 0) {
  821. throw new FS.ErrnoError(6);
  822. }
  823. if (result === null || result === undefined) break;
  824. bytesRead++;
  825. buffer[offset + i] = result;
  826. }
  827. if (bytesRead) {
  828. stream.node.timestamp = Date.now();
  829. }
  830. return bytesRead;
  831. },
  832. write(stream, buffer, offset, length, pos) {
  833. if (!stream.tty || !stream.tty.ops.put_char) {
  834. throw new FS.ErrnoError(60);
  835. }
  836. try {
  837. for (var i = 0; i < length; i++) {
  838. stream.tty.ops.put_char(stream.tty, buffer[offset + i]);
  839. }
  840. } catch (e) {
  841. throw new FS.ErrnoError(29);
  842. }
  843. if (length) {
  844. stream.node.timestamp = Date.now();
  845. }
  846. return i;
  847. }
  848. },
  849. default_tty_ops: {
  850. get_char(tty) {
  851. return FS_stdin_getChar();
  852. },
  853. put_char(tty, val) {
  854. if (val === null || val === 10) {
  855. out(UTF8ArrayToString(tty.output, 0));
  856. tty.output = [];
  857. } else {
  858. if (val != 0) tty.output.push(val);
  859. }
  860. },
  861. // val == 0 would cut text output off in the middle.
  862. fsync(tty) {
  863. if (tty.output && tty.output.length > 0) {
  864. out(UTF8ArrayToString(tty.output, 0));
  865. tty.output = [];
  866. }
  867. },
  868. ioctl_tcgets(tty) {
  869. // typical setting
  870. return {
  871. c_iflag: 25856,
  872. c_oflag: 5,
  873. c_cflag: 191,
  874. c_lflag: 35387,
  875. c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  876. };
  877. },
  878. ioctl_tcsets(tty, optional_actions, data) {
  879. // currently just ignore
  880. return 0;
  881. },
  882. ioctl_tiocgwinsz(tty) {
  883. return [ 24, 80 ];
  884. }
  885. },
  886. default_tty1_ops: {
  887. put_char(tty, val) {
  888. if (val === null || val === 10) {
  889. err(UTF8ArrayToString(tty.output, 0));
  890. tty.output = [];
  891. } else {
  892. if (val != 0) tty.output.push(val);
  893. }
  894. },
  895. fsync(tty) {
  896. if (tty.output && tty.output.length > 0) {
  897. err(UTF8ArrayToString(tty.output, 0));
  898. tty.output = [];
  899. }
  900. }
  901. }
  902. };
  903. var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;
  904. var mmapAlloc = size => {
  905. abort();
  906. };
  907. var MEMFS = {
  908. ops_table: null,
  909. mount(mount) {
  910. return MEMFS.createNode(null, "/", 16384 | 511, /* 0777 */ 0);
  911. },
  912. createNode(parent, name, mode, dev) {
  913. if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
  914. // no supported
  915. throw new FS.ErrnoError(63);
  916. }
  917. MEMFS.ops_table ||= {
  918. dir: {
  919. node: {
  920. getattr: MEMFS.node_ops.getattr,
  921. setattr: MEMFS.node_ops.setattr,
  922. lookup: MEMFS.node_ops.lookup,
  923. mknod: MEMFS.node_ops.mknod,
  924. rename: MEMFS.node_ops.rename,
  925. unlink: MEMFS.node_ops.unlink,
  926. rmdir: MEMFS.node_ops.rmdir,
  927. readdir: MEMFS.node_ops.readdir,
  928. symlink: MEMFS.node_ops.symlink
  929. },
  930. stream: {
  931. llseek: MEMFS.stream_ops.llseek
  932. }
  933. },
  934. file: {
  935. node: {
  936. getattr: MEMFS.node_ops.getattr,
  937. setattr: MEMFS.node_ops.setattr
  938. },
  939. stream: {
  940. llseek: MEMFS.stream_ops.llseek,
  941. read: MEMFS.stream_ops.read,
  942. write: MEMFS.stream_ops.write,
  943. allocate: MEMFS.stream_ops.allocate,
  944. mmap: MEMFS.stream_ops.mmap,
  945. msync: MEMFS.stream_ops.msync
  946. }
  947. },
  948. link: {
  949. node: {
  950. getattr: MEMFS.node_ops.getattr,
  951. setattr: MEMFS.node_ops.setattr,
  952. readlink: MEMFS.node_ops.readlink
  953. },
  954. stream: {}
  955. },
  956. chrdev: {
  957. node: {
  958. getattr: MEMFS.node_ops.getattr,
  959. setattr: MEMFS.node_ops.setattr
  960. },
  961. stream: FS.chrdev_stream_ops
  962. }
  963. };
  964. var node = FS.createNode(parent, name, mode, dev);
  965. if (FS.isDir(node.mode)) {
  966. node.node_ops = MEMFS.ops_table.dir.node;
  967. node.stream_ops = MEMFS.ops_table.dir.stream;
  968. node.contents = {};
  969. } else if (FS.isFile(node.mode)) {
  970. node.node_ops = MEMFS.ops_table.file.node;
  971. node.stream_ops = MEMFS.ops_table.file.stream;
  972. node.usedBytes = 0;
  973. // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
  974. // When the byte data of the file is populated, this will point to either a typed array, or a normal JS array. Typed arrays are preferred
  975. // for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
  976. // penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
  977. node.contents = null;
  978. } else if (FS.isLink(node.mode)) {
  979. node.node_ops = MEMFS.ops_table.link.node;
  980. node.stream_ops = MEMFS.ops_table.link.stream;
  981. } else if (FS.isChrdev(node.mode)) {
  982. node.node_ops = MEMFS.ops_table.chrdev.node;
  983. node.stream_ops = MEMFS.ops_table.chrdev.stream;
  984. }
  985. node.timestamp = Date.now();
  986. // add the new node to the parent
  987. if (parent) {
  988. parent.contents[name] = node;
  989. parent.timestamp = node.timestamp;
  990. }
  991. return node;
  992. },
  993. getFileDataAsTypedArray(node) {
  994. if (!node.contents) return new Uint8Array(0);
  995. if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
  996. // Make sure to not return excess unused bytes.
  997. return new Uint8Array(node.contents);
  998. },
  999. expandFileStorage(node, newCapacity) {
  1000. var prevCapacity = node.contents ? node.contents.length : 0;
  1001. if (prevCapacity >= newCapacity) return;
  1002. // No need to expand, the storage was already large enough.
  1003. // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
  1004. // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
  1005. // avoid overshooting the allocation cap by a very large margin.
  1006. var CAPACITY_DOUBLING_MAX = 1024 * 1024;
  1007. newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0);
  1008. if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
  1009. // At minimum allocate 256b for each file when expanding.
  1010. var oldContents = node.contents;
  1011. node.contents = new Uint8Array(newCapacity);
  1012. // Allocate new storage.
  1013. if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
  1014. },
  1015. // Copy old data over to the new storage.
  1016. resizeFileStorage(node, newSize) {
  1017. if (node.usedBytes == newSize) return;
  1018. if (newSize == 0) {
  1019. node.contents = null;
  1020. // Fully decommit when requesting a resize to zero.
  1021. node.usedBytes = 0;
  1022. } else {
  1023. var oldContents = node.contents;
  1024. node.contents = new Uint8Array(newSize);
  1025. // Allocate new storage.
  1026. if (oldContents) {
  1027. node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));
  1028. }
  1029. // Copy old data over to the new storage.
  1030. node.usedBytes = newSize;
  1031. }
  1032. },
  1033. node_ops: {
  1034. getattr(node) {
  1035. var attr = {};
  1036. // device numbers reuse inode numbers.
  1037. attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
  1038. attr.ino = node.id;
  1039. attr.mode = node.mode;
  1040. attr.nlink = 1;
  1041. attr.uid = 0;
  1042. attr.gid = 0;
  1043. attr.rdev = node.rdev;
  1044. if (FS.isDir(node.mode)) {
  1045. attr.size = 4096;
  1046. } else if (FS.isFile(node.mode)) {
  1047. attr.size = node.usedBytes;
  1048. } else if (FS.isLink(node.mode)) {
  1049. attr.size = node.link.length;
  1050. } else {
  1051. attr.size = 0;
  1052. }
  1053. attr.atime = new Date(node.timestamp);
  1054. attr.mtime = new Date(node.timestamp);
  1055. attr.ctime = new Date(node.timestamp);
  1056. // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
  1057. // but this is not required by the standard.
  1058. attr.blksize = 4096;
  1059. attr.blocks = Math.ceil(attr.size / attr.blksize);
  1060. return attr;
  1061. },
  1062. setattr(node, attr) {
  1063. if (attr.mode !== undefined) {
  1064. node.mode = attr.mode;
  1065. }
  1066. if (attr.timestamp !== undefined) {
  1067. node.timestamp = attr.timestamp;
  1068. }
  1069. if (attr.size !== undefined) {
  1070. MEMFS.resizeFileStorage(node, attr.size);
  1071. }
  1072. },
  1073. lookup(parent, name) {
  1074. throw FS.genericErrors[44];
  1075. },
  1076. mknod(parent, name, mode, dev) {
  1077. return MEMFS.createNode(parent, name, mode, dev);
  1078. },
  1079. rename(old_node, new_dir, new_name) {
  1080. // if we're overwriting a directory at new_name, make sure it's empty.
  1081. if (FS.isDir(old_node.mode)) {
  1082. var new_node;
  1083. try {
  1084. new_node = FS.lookupNode(new_dir, new_name);
  1085. } catch (e) {}
  1086. if (new_node) {
  1087. for (var i in new_node.contents) {
  1088. throw new FS.ErrnoError(55);
  1089. }
  1090. }
  1091. }
  1092. // do the internal rewiring
  1093. delete old_node.parent.contents[old_node.name];
  1094. old_node.parent.timestamp = Date.now();
  1095. old_node.name = new_name;
  1096. new_dir.contents[new_name] = old_node;
  1097. new_dir.timestamp = old_node.parent.timestamp;
  1098. },
  1099. unlink(parent, name) {
  1100. delete parent.contents[name];
  1101. parent.timestamp = Date.now();
  1102. },
  1103. rmdir(parent, name) {
  1104. var node = FS.lookupNode(parent, name);
  1105. for (var i in node.contents) {
  1106. throw new FS.ErrnoError(55);
  1107. }
  1108. delete parent.contents[name];
  1109. parent.timestamp = Date.now();
  1110. },
  1111. readdir(node) {
  1112. var entries = [ ".", ".." ];
  1113. for (var key of Object.keys(node.contents)) {
  1114. entries.push(key);
  1115. }
  1116. return entries;
  1117. },
  1118. symlink(parent, newname, oldpath) {
  1119. var node = MEMFS.createNode(parent, newname, 511 | /* 0777 */ 40960, 0);
  1120. node.link = oldpath;
  1121. return node;
  1122. },
  1123. readlink(node) {
  1124. if (!FS.isLink(node.mode)) {
  1125. throw new FS.ErrnoError(28);
  1126. }
  1127. return node.link;
  1128. }
  1129. },
  1130. stream_ops: {
  1131. read(stream, buffer, offset, length, position) {
  1132. var contents = stream.node.contents;
  1133. if (position >= stream.node.usedBytes) return 0;
  1134. var size = Math.min(stream.node.usedBytes - position, length);
  1135. if (size > 8 && contents.subarray) {
  1136. // non-trivial, and typed array
  1137. buffer.set(contents.subarray(position, position + size), offset);
  1138. } else {
  1139. for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
  1140. }
  1141. return size;
  1142. },
  1143. write(stream, buffer, offset, length, position, canOwn) {
  1144. // If the buffer is located in main memory (HEAP), and if
  1145. // memory can grow, we can't hold on to references of the
  1146. // memory buffer, as they may get invalidated. That means we
  1147. // need to do copy its contents.
  1148. if (buffer.buffer === HEAP8.buffer) {
  1149. canOwn = false;
  1150. }
  1151. if (!length) return 0;
  1152. var node = stream.node;
  1153. node.timestamp = Date.now();
  1154. if (buffer.subarray && (!node.contents || node.contents.subarray)) {
  1155. // This write is from a typed array to a typed array?
  1156. if (canOwn) {
  1157. node.contents = buffer.subarray(offset, offset + length);
  1158. node.usedBytes = length;
  1159. return length;
  1160. } else if (node.usedBytes === 0 && position === 0) {
  1161. // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
  1162. node.contents = buffer.slice(offset, offset + length);
  1163. node.usedBytes = length;
  1164. return length;
  1165. } else if (position + length <= node.usedBytes) {
  1166. // Writing to an already allocated and used subrange of the file?
  1167. node.contents.set(buffer.subarray(offset, offset + length), position);
  1168. return length;
  1169. }
  1170. }
  1171. // Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
  1172. MEMFS.expandFileStorage(node, position + length);
  1173. if (node.contents.subarray && buffer.subarray) {
  1174. // Use typed array write which is available.
  1175. node.contents.set(buffer.subarray(offset, offset + length), position);
  1176. } else {
  1177. for (var i = 0; i < length; i++) {
  1178. node.contents[position + i] = buffer[offset + i];
  1179. }
  1180. }
  1181. node.usedBytes = Math.max(node.usedBytes, position + length);
  1182. return length;
  1183. },
  1184. llseek(stream, offset, whence) {
  1185. var position = offset;
  1186. if (whence === 1) {
  1187. position += stream.position;
  1188. } else if (whence === 2) {
  1189. if (FS.isFile(stream.node.mode)) {
  1190. position += stream.node.usedBytes;
  1191. }
  1192. }
  1193. if (position < 0) {
  1194. throw new FS.ErrnoError(28);
  1195. }
  1196. return position;
  1197. },
  1198. allocate(stream, offset, length) {
  1199. MEMFS.expandFileStorage(stream.node, offset + length);
  1200. stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
  1201. },
  1202. mmap(stream, length, position, prot, flags) {
  1203. if (!FS.isFile(stream.node.mode)) {
  1204. throw new FS.ErrnoError(43);
  1205. }
  1206. var ptr;
  1207. var allocated;
  1208. var contents = stream.node.contents;
  1209. // Only make a new copy when MAP_PRIVATE is specified.
  1210. if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
  1211. // We can't emulate MAP_SHARED when the file is not backed by the
  1212. // buffer we're mapping to (e.g. the HEAP buffer).
  1213. allocated = false;
  1214. ptr = contents.byteOffset;
  1215. } else {
  1216. allocated = true;
  1217. ptr = mmapAlloc(length);
  1218. if (!ptr) {
  1219. throw new FS.ErrnoError(48);
  1220. }
  1221. if (contents) {
  1222. // Try to avoid unnecessary slices.
  1223. if (position > 0 || position + length < contents.length) {
  1224. if (contents.subarray) {
  1225. contents = contents.subarray(position, position + length);
  1226. } else {
  1227. contents = Array.prototype.slice.call(contents, position, position + length);
  1228. }
  1229. }
  1230. HEAP8.set(contents, ptr);
  1231. }
  1232. }
  1233. return {
  1234. ptr,
  1235. allocated
  1236. };
  1237. },
  1238. msync(stream, buffer, offset, length, mmapFlags) {
  1239. MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
  1240. // should we check if bytesWritten and length are the same?
  1241. return 0;
  1242. }
  1243. }
  1244. };
  1245. /** @param {boolean=} noRunDep */ var asyncLoad = (url, onload, onerror, noRunDep) => {
  1246. var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : "";
  1247. readAsync(url).then(arrayBuffer => {
  1248. onload(new Uint8Array(arrayBuffer));
  1249. if (dep) removeRunDependency(dep);
  1250. }, err => {
  1251. if (onerror) {
  1252. onerror();
  1253. } else {
  1254. throw `Loading data file "${url}" failed.`;
  1255. }
  1256. });
  1257. if (dep) addRunDependency(dep);
  1258. };
  1259. var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
  1260. FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);
  1261. };
  1262. var preloadPlugins = Module["preloadPlugins"] || [];
  1263. var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
  1264. // Ensure plugins are ready.
  1265. if (typeof Browser != "undefined") Browser.init();
  1266. var handled = false;
  1267. preloadPlugins.forEach(plugin => {
  1268. if (handled) return;
  1269. if (plugin["canHandle"](fullname)) {
  1270. plugin["handle"](byteArray, fullname, finish, onerror);
  1271. handled = true;
  1272. }
  1273. });
  1274. return handled;
  1275. };
  1276. var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
  1277. // TODO we should allow people to just pass in a complete filename instead
  1278. // of parent and name being that we just join them anyways
  1279. var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
  1280. var dep = getUniqueRunDependency(`cp ${fullname}`);
  1281. // might have several active requests for the same fullname
  1282. function processData(byteArray) {
  1283. function finish(byteArray) {
  1284. preFinish?.();
  1285. if (!dontCreateFile) {
  1286. FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
  1287. }
  1288. onload?.();
  1289. removeRunDependency(dep);
  1290. }
  1291. if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
  1292. onerror?.();
  1293. removeRunDependency(dep);
  1294. })) {
  1295. return;
  1296. }
  1297. finish(byteArray);
  1298. }
  1299. addRunDependency(dep);
  1300. if (typeof url == "string") {
  1301. asyncLoad(url, processData, onerror);
  1302. } else {
  1303. processData(url);
  1304. }
  1305. };
  1306. var FS_modeStringToFlags = str => {
  1307. var flagModes = {
  1308. "r": 0,
  1309. "r+": 2,
  1310. "w": 512 | 64 | 1,
  1311. "w+": 512 | 64 | 2,
  1312. "a": 1024 | 64 | 1,
  1313. "a+": 1024 | 64 | 2
  1314. };
  1315. var flags = flagModes[str];
  1316. if (typeof flags == "undefined") {
  1317. throw new Error(`Unknown file open mode: ${str}`);
  1318. }
  1319. return flags;
  1320. };
  1321. var FS_getMode = (canRead, canWrite) => {
  1322. var mode = 0;
  1323. if (canRead) mode |= 292 | 73;
  1324. if (canWrite) mode |= 146;
  1325. return mode;
  1326. };
  1327. var FS = {
  1328. root: null,
  1329. mounts: [],
  1330. devices: {},
  1331. streams: [],
  1332. nextInode: 1,
  1333. nameTable: null,
  1334. currentPath: "/",
  1335. initialized: false,
  1336. ignorePermissions: true,
  1337. ErrnoError: class {
  1338. // We set the `name` property to be able to identify `FS.ErrnoError`
  1339. // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.
  1340. // - when using PROXYFS, an error can come from an underlying FS
  1341. // as different FS objects have their own FS.ErrnoError each,
  1342. // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.
  1343. // we'll use the reliable test `err.name == "ErrnoError"` instead
  1344. constructor(errno) {
  1345. // TODO(sbc): Use the inline member declaration syntax once we
  1346. // support it in acorn and closure.
  1347. this.name = "ErrnoError";
  1348. this.errno = errno;
  1349. }
  1350. },
  1351. genericErrors: {},
  1352. filesystems: null,
  1353. syncFSRequests: 0,
  1354. FSStream: class {
  1355. constructor() {
  1356. // TODO(https://github.com/emscripten-core/emscripten/issues/21414):
  1357. // Use inline field declarations.
  1358. this.shared = {};
  1359. }
  1360. get object() {
  1361. return this.node;
  1362. }
  1363. set object(val) {
  1364. this.node = val;
  1365. }
  1366. get isRead() {
  1367. return (this.flags & 2097155) !== 1;
  1368. }
  1369. get isWrite() {
  1370. return (this.flags & 2097155) !== 0;
  1371. }
  1372. get isAppend() {
  1373. return (this.flags & 1024);
  1374. }
  1375. get flags() {
  1376. return this.shared.flags;
  1377. }
  1378. set flags(val) {
  1379. this.shared.flags = val;
  1380. }
  1381. get position() {
  1382. return this.shared.position;
  1383. }
  1384. set position(val) {
  1385. this.shared.position = val;
  1386. }
  1387. },
  1388. FSNode: class {
  1389. constructor(parent, name, mode, rdev) {
  1390. if (!parent) {
  1391. parent = this;
  1392. }
  1393. // root node sets parent to itself
  1394. this.parent = parent;
  1395. this.mount = parent.mount;
  1396. this.mounted = null;
  1397. this.id = FS.nextInode++;
  1398. this.name = name;
  1399. this.mode = mode;
  1400. this.node_ops = {};
  1401. this.stream_ops = {};
  1402. this.rdev = rdev;
  1403. this.readMode = 292 | 73;
  1404. this.writeMode = 146;
  1405. }
  1406. get read() {
  1407. return (this.mode & this.readMode) === this.readMode;
  1408. }
  1409. set read(val) {
  1410. val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
  1411. }
  1412. get write() {
  1413. return (this.mode & this.writeMode) === this.writeMode;
  1414. }
  1415. set write(val) {
  1416. val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
  1417. }
  1418. get isFolder() {
  1419. return FS.isDir(this.mode);
  1420. }
  1421. get isDevice() {
  1422. return FS.isChrdev(this.mode);
  1423. }
  1424. },
  1425. lookupPath(path, opts = {}) {
  1426. path = PATH_FS.resolve(path);
  1427. if (!path) return {
  1428. path: "",
  1429. node: null
  1430. };
  1431. var defaults = {
  1432. follow_mount: true,
  1433. recurse_count: 0
  1434. };
  1435. opts = Object.assign(defaults, opts);
  1436. if (opts.recurse_count > 8) {
  1437. // max recursive lookup of 8
  1438. throw new FS.ErrnoError(32);
  1439. }
  1440. // split the absolute path
  1441. var parts = path.split("/").filter(p => !!p);
  1442. // start at the root
  1443. var current = FS.root;
  1444. var current_path = "/";
  1445. for (var i = 0; i < parts.length; i++) {
  1446. var islast = (i === parts.length - 1);
  1447. if (islast && opts.parent) {
  1448. // stop resolving
  1449. break;
  1450. }
  1451. current = FS.lookupNode(current, parts[i]);
  1452. current_path = PATH.join2(current_path, parts[i]);
  1453. // jump to the mount's root node if this is a mountpoint
  1454. if (FS.isMountpoint(current)) {
  1455. if (!islast || (islast && opts.follow_mount)) {
  1456. current = current.mounted.root;
  1457. }
  1458. }
  1459. // by default, lookupPath will not follow a symlink if it is the final path component.
  1460. // setting opts.follow = true will override this behavior.
  1461. if (!islast || opts.follow) {
  1462. var count = 0;
  1463. while (FS.isLink(current.mode)) {
  1464. var link = FS.readlink(current_path);
  1465. current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
  1466. var lookup = FS.lookupPath(current_path, {
  1467. recurse_count: opts.recurse_count + 1
  1468. });
  1469. current = lookup.node;
  1470. if (count++ > 40) {
  1471. // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
  1472. throw new FS.ErrnoError(32);
  1473. }
  1474. }
  1475. }
  1476. }
  1477. return {
  1478. path: current_path,
  1479. node: current
  1480. };
  1481. },
  1482. getPath(node) {
  1483. var path;
  1484. while (true) {
  1485. if (FS.isRoot(node)) {
  1486. var mount = node.mount.mountpoint;
  1487. if (!path) return mount;
  1488. return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;
  1489. }
  1490. path = path ? `${node.name}/${path}` : node.name;
  1491. node = node.parent;
  1492. }
  1493. },
  1494. hashName(parentid, name) {
  1495. var hash = 0;
  1496. for (var i = 0; i < name.length; i++) {
  1497. hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
  1498. }
  1499. return ((parentid + hash) >>> 0) % FS.nameTable.length;
  1500. },
  1501. hashAddNode(node) {
  1502. var hash = FS.hashName(node.parent.id, node.name);
  1503. node.name_next = FS.nameTable[hash];
  1504. FS.nameTable[hash] = node;
  1505. },
  1506. hashRemoveNode(node) {
  1507. var hash = FS.hashName(node.parent.id, node.name);
  1508. if (FS.nameTable[hash] === node) {
  1509. FS.nameTable[hash] = node.name_next;
  1510. } else {
  1511. var current = FS.nameTable[hash];
  1512. while (current) {
  1513. if (current.name_next === node) {
  1514. current.name_next = node.name_next;
  1515. break;
  1516. }
  1517. current = current.name_next;
  1518. }
  1519. }
  1520. },
  1521. lookupNode(parent, name) {
  1522. var errCode = FS.mayLookup(parent);
  1523. if (errCode) {
  1524. throw new FS.ErrnoError(errCode);
  1525. }
  1526. var hash = FS.hashName(parent.id, name);
  1527. for (var node = FS.nameTable[hash]; node; node = node.name_next) {
  1528. var nodeName = node.name;
  1529. if (node.parent.id === parent.id && nodeName === name) {
  1530. return node;
  1531. }
  1532. }
  1533. // if we failed to find it in the cache, call into the VFS
  1534. return FS.lookup(parent, name);
  1535. },
  1536. createNode(parent, name, mode, rdev) {
  1537. var node = new FS.FSNode(parent, name, mode, rdev);
  1538. FS.hashAddNode(node);
  1539. return node;
  1540. },
  1541. destroyNode(node) {
  1542. FS.hashRemoveNode(node);
  1543. },
  1544. isRoot(node) {
  1545. return node === node.parent;
  1546. },
  1547. isMountpoint(node) {
  1548. return !!node.mounted;
  1549. },
  1550. isFile(mode) {
  1551. return (mode & 61440) === 32768;
  1552. },
  1553. isDir(mode) {
  1554. return (mode & 61440) === 16384;
  1555. },
  1556. isLink(mode) {
  1557. return (mode & 61440) === 40960;
  1558. },
  1559. isChrdev(mode) {
  1560. return (mode & 61440) === 8192;
  1561. },
  1562. isBlkdev(mode) {
  1563. return (mode & 61440) === 24576;
  1564. },
  1565. isFIFO(mode) {
  1566. return (mode & 61440) === 4096;
  1567. },
  1568. isSocket(mode) {
  1569. return (mode & 49152) === 49152;
  1570. },
  1571. flagsToPermissionString(flag) {
  1572. var perms = [ "r", "w", "rw" ][flag & 3];
  1573. if ((flag & 512)) {
  1574. perms += "w";
  1575. }
  1576. return perms;
  1577. },
  1578. nodePermissions(node, perms) {
  1579. if (FS.ignorePermissions) {
  1580. return 0;
  1581. }
  1582. // return 0 if any user, group or owner bits are set.
  1583. if (perms.includes("r") && !(node.mode & 292)) {
  1584. return 2;
  1585. } else if (perms.includes("w") && !(node.mode & 146)) {
  1586. return 2;
  1587. } else if (perms.includes("x") && !(node.mode & 73)) {
  1588. return 2;
  1589. }
  1590. return 0;
  1591. },
  1592. mayLookup(dir) {
  1593. if (!FS.isDir(dir.mode)) return 54;
  1594. var errCode = FS.nodePermissions(dir, "x");
  1595. if (errCode) return errCode;
  1596. if (!dir.node_ops.lookup) return 2;
  1597. return 0;
  1598. },
  1599. mayCreate(dir, name) {
  1600. try {
  1601. var node = FS.lookupNode(dir, name);
  1602. return 20;
  1603. } catch (e) {}
  1604. return FS.nodePermissions(dir, "wx");
  1605. },
  1606. mayDelete(dir, name, isdir) {
  1607. var node;
  1608. try {
  1609. node = FS.lookupNode(dir, name);
  1610. } catch (e) {
  1611. return e.errno;
  1612. }
  1613. var errCode = FS.nodePermissions(dir, "wx");
  1614. if (errCode) {
  1615. return errCode;
  1616. }
  1617. if (isdir) {
  1618. if (!FS.isDir(node.mode)) {
  1619. return 54;
  1620. }
  1621. if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
  1622. return 10;
  1623. }
  1624. } else {
  1625. if (FS.isDir(node.mode)) {
  1626. return 31;
  1627. }
  1628. }
  1629. return 0;
  1630. },
  1631. mayOpen(node, flags) {
  1632. if (!node) {
  1633. return 44;
  1634. }
  1635. if (FS.isLink(node.mode)) {
  1636. return 32;
  1637. } else if (FS.isDir(node.mode)) {
  1638. if (FS.flagsToPermissionString(flags) !== "r" || // opening for write
  1639. (flags & 512)) {
  1640. // TODO: check for O_SEARCH? (== search for dir only)
  1641. return 31;
  1642. }
  1643. }
  1644. return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
  1645. },
  1646. MAX_OPEN_FDS: 4096,
  1647. nextfd() {
  1648. for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
  1649. if (!FS.streams[fd]) {
  1650. return fd;
  1651. }
  1652. }
  1653. throw new FS.ErrnoError(33);
  1654. },
  1655. getStreamChecked(fd) {
  1656. var stream = FS.getStream(fd);
  1657. if (!stream) {
  1658. throw new FS.ErrnoError(8);
  1659. }
  1660. return stream;
  1661. },
  1662. getStream: fd => FS.streams[fd],
  1663. createStream(stream, fd = -1) {
  1664. // clone it, so we can return an instance of FSStream
  1665. stream = Object.assign(new FS.FSStream, stream);
  1666. if (fd == -1) {
  1667. fd = FS.nextfd();
  1668. }
  1669. stream.fd = fd;
  1670. FS.streams[fd] = stream;
  1671. return stream;
  1672. },
  1673. closeStream(fd) {
  1674. FS.streams[fd] = null;
  1675. },
  1676. dupStream(origStream, fd = -1) {
  1677. var stream = FS.createStream(origStream, fd);
  1678. stream.stream_ops?.dup?.(stream);
  1679. return stream;
  1680. },
  1681. chrdev_stream_ops: {
  1682. open(stream) {
  1683. var device = FS.getDevice(stream.node.rdev);
  1684. // override node's stream ops with the device's
  1685. stream.stream_ops = device.stream_ops;
  1686. // forward the open call
  1687. stream.stream_ops.open?.(stream);
  1688. },
  1689. llseek() {
  1690. throw new FS.ErrnoError(70);
  1691. }
  1692. },
  1693. major: dev => ((dev) >> 8),
  1694. minor: dev => ((dev) & 255),
  1695. makedev: (ma, mi) => ((ma) << 8 | (mi)),
  1696. registerDevice(dev, ops) {
  1697. FS.devices[dev] = {
  1698. stream_ops: ops
  1699. };
  1700. },
  1701. getDevice: dev => FS.devices[dev],
  1702. getMounts(mount) {
  1703. var mounts = [];
  1704. var check = [ mount ];
  1705. while (check.length) {
  1706. var m = check.pop();
  1707. mounts.push(m);
  1708. check.push(...m.mounts);
  1709. }
  1710. return mounts;
  1711. },
  1712. syncfs(populate, callback) {
  1713. if (typeof populate == "function") {
  1714. callback = populate;
  1715. populate = false;
  1716. }
  1717. FS.syncFSRequests++;
  1718. if (FS.syncFSRequests > 1) {
  1719. err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);
  1720. }
  1721. var mounts = FS.getMounts(FS.root.mount);
  1722. var completed = 0;
  1723. function doCallback(errCode) {
  1724. FS.syncFSRequests--;
  1725. return callback(errCode);
  1726. }
  1727. function done(errCode) {
  1728. if (errCode) {
  1729. if (!done.errored) {
  1730. done.errored = true;
  1731. return doCallback(errCode);
  1732. }
  1733. return;
  1734. }
  1735. if (++completed >= mounts.length) {
  1736. doCallback(null);
  1737. }
  1738. }
  1739. // sync all mounts
  1740. mounts.forEach(mount => {
  1741. if (!mount.type.syncfs) {
  1742. return done(null);
  1743. }
  1744. mount.type.syncfs(mount, populate, done);
  1745. });
  1746. },
  1747. mount(type, opts, mountpoint) {
  1748. var root = mountpoint === "/";
  1749. var pseudo = !mountpoint;
  1750. var node;
  1751. if (root && FS.root) {
  1752. throw new FS.ErrnoError(10);
  1753. } else if (!root && !pseudo) {
  1754. var lookup = FS.lookupPath(mountpoint, {
  1755. follow_mount: false
  1756. });
  1757. mountpoint = lookup.path;
  1758. // use the absolute path
  1759. node = lookup.node;
  1760. if (FS.isMountpoint(node)) {
  1761. throw new FS.ErrnoError(10);
  1762. }
  1763. if (!FS.isDir(node.mode)) {
  1764. throw new FS.ErrnoError(54);
  1765. }
  1766. }
  1767. var mount = {
  1768. type,
  1769. opts,
  1770. mountpoint,
  1771. mounts: []
  1772. };
  1773. // create a root node for the fs
  1774. var mountRoot = type.mount(mount);
  1775. mountRoot.mount = mount;
  1776. mount.root = mountRoot;
  1777. if (root) {
  1778. FS.root = mountRoot;
  1779. } else if (node) {
  1780. // set as a mountpoint
  1781. node.mounted = mount;
  1782. // add the new mount to the current mount's children
  1783. if (node.mount) {
  1784. node.mount.mounts.push(mount);
  1785. }
  1786. }
  1787. return mountRoot;
  1788. },
  1789. unmount(mountpoint) {
  1790. var lookup = FS.lookupPath(mountpoint, {
  1791. follow_mount: false
  1792. });
  1793. if (!FS.isMountpoint(lookup.node)) {
  1794. throw new FS.ErrnoError(28);
  1795. }
  1796. // destroy the nodes for this mount, and all its child mounts
  1797. var node = lookup.node;
  1798. var mount = node.mounted;
  1799. var mounts = FS.getMounts(mount);
  1800. Object.keys(FS.nameTable).forEach(hash => {
  1801. var current = FS.nameTable[hash];
  1802. while (current) {
  1803. var next = current.name_next;
  1804. if (mounts.includes(current.mount)) {
  1805. FS.destroyNode(current);
  1806. }
  1807. current = next;
  1808. }
  1809. });
  1810. // no longer a mountpoint
  1811. node.mounted = null;
  1812. // remove this mount from the child mounts
  1813. var idx = node.mount.mounts.indexOf(mount);
  1814. node.mount.mounts.splice(idx, 1);
  1815. },
  1816. lookup(parent, name) {
  1817. return parent.node_ops.lookup(parent, name);
  1818. },
  1819. mknod(path, mode, dev) {
  1820. var lookup = FS.lookupPath(path, {
  1821. parent: true
  1822. });
  1823. var parent = lookup.node;
  1824. var name = PATH.basename(path);
  1825. if (!name || name === "." || name === "..") {
  1826. throw new FS.ErrnoError(28);
  1827. }
  1828. var errCode = FS.mayCreate(parent, name);
  1829. if (errCode) {
  1830. throw new FS.ErrnoError(errCode);
  1831. }
  1832. if (!parent.node_ops.mknod) {
  1833. throw new FS.ErrnoError(63);
  1834. }
  1835. return parent.node_ops.mknod(parent, name, mode, dev);
  1836. },
  1837. create(path, mode) {
  1838. mode = mode !== undefined ? mode : 438;
  1839. /* 0666 */ mode &= 4095;
  1840. mode |= 32768;
  1841. return FS.mknod(path, mode, 0);
  1842. },
  1843. mkdir(path, mode) {
  1844. mode = mode !== undefined ? mode : 511;
  1845. /* 0777 */ mode &= 511 | 512;
  1846. mode |= 16384;
  1847. return FS.mknod(path, mode, 0);
  1848. },
  1849. mkdirTree(path, mode) {
  1850. var dirs = path.split("/");
  1851. var d = "";
  1852. for (var i = 0; i < dirs.length; ++i) {
  1853. if (!dirs[i]) continue;
  1854. d += "/" + dirs[i];
  1855. try {
  1856. FS.mkdir(d, mode);
  1857. } catch (e) {
  1858. if (e.errno != 20) throw e;
  1859. }
  1860. }
  1861. },
  1862. mkdev(path, mode, dev) {
  1863. if (typeof dev == "undefined") {
  1864. dev = mode;
  1865. mode = 438;
  1866. }
  1867. /* 0666 */ mode |= 8192;
  1868. return FS.mknod(path, mode, dev);
  1869. },
  1870. symlink(oldpath, newpath) {
  1871. if (!PATH_FS.resolve(oldpath)) {
  1872. throw new FS.ErrnoError(44);
  1873. }
  1874. var lookup = FS.lookupPath(newpath, {
  1875. parent: true
  1876. });
  1877. var parent = lookup.node;
  1878. if (!parent) {
  1879. throw new FS.ErrnoError(44);
  1880. }
  1881. var newname = PATH.basename(newpath);
  1882. var errCode = FS.mayCreate(parent, newname);
  1883. if (errCode) {
  1884. throw new FS.ErrnoError(errCode);
  1885. }
  1886. if (!parent.node_ops.symlink) {
  1887. throw new FS.ErrnoError(63);
  1888. }
  1889. return parent.node_ops.symlink(parent, newname, oldpath);
  1890. },
  1891. rename(old_path, new_path) {
  1892. var old_dirname = PATH.dirname(old_path);
  1893. var new_dirname = PATH.dirname(new_path);
  1894. var old_name = PATH.basename(old_path);
  1895. var new_name = PATH.basename(new_path);
  1896. // parents must exist
  1897. var lookup, old_dir, new_dir;
  1898. // let the errors from non existent directories percolate up
  1899. lookup = FS.lookupPath(old_path, {
  1900. parent: true
  1901. });
  1902. old_dir = lookup.node;
  1903. lookup = FS.lookupPath(new_path, {
  1904. parent: true
  1905. });
  1906. new_dir = lookup.node;
  1907. if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
  1908. // need to be part of the same mount
  1909. if (old_dir.mount !== new_dir.mount) {
  1910. throw new FS.ErrnoError(75);
  1911. }
  1912. // source must exist
  1913. var old_node = FS.lookupNode(old_dir, old_name);
  1914. // old path should not be an ancestor of the new path
  1915. var relative = PATH_FS.relative(old_path, new_dirname);
  1916. if (relative.charAt(0) !== ".") {
  1917. throw new FS.ErrnoError(28);
  1918. }
  1919. // new path should not be an ancestor of the old path
  1920. relative = PATH_FS.relative(new_path, old_dirname);
  1921. if (relative.charAt(0) !== ".") {
  1922. throw new FS.ErrnoError(55);
  1923. }
  1924. // see if the new path already exists
  1925. var new_node;
  1926. try {
  1927. new_node = FS.lookupNode(new_dir, new_name);
  1928. } catch (e) {}
  1929. // early out if nothing needs to change
  1930. if (old_node === new_node) {
  1931. return;
  1932. }
  1933. // we'll need to delete the old entry
  1934. var isdir = FS.isDir(old_node.mode);
  1935. var errCode = FS.mayDelete(old_dir, old_name, isdir);
  1936. if (errCode) {
  1937. throw new FS.ErrnoError(errCode);
  1938. }
  1939. // need delete permissions if we'll be overwriting.
  1940. // need create permissions if new doesn't already exist.
  1941. errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
  1942. if (errCode) {
  1943. throw new FS.ErrnoError(errCode);
  1944. }
  1945. if (!old_dir.node_ops.rename) {
  1946. throw new FS.ErrnoError(63);
  1947. }
  1948. if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
  1949. throw new FS.ErrnoError(10);
  1950. }
  1951. // if we are going to change the parent, check write permissions
  1952. if (new_dir !== old_dir) {
  1953. errCode = FS.nodePermissions(old_dir, "w");
  1954. if (errCode) {
  1955. throw new FS.ErrnoError(errCode);
  1956. }
  1957. }
  1958. // remove the node from the lookup hash
  1959. FS.hashRemoveNode(old_node);
  1960. // do the underlying fs rename
  1961. try {
  1962. old_dir.node_ops.rename(old_node, new_dir, new_name);
  1963. // update old node (we do this here to avoid each backend
  1964. // needing to)
  1965. old_node.parent = new_dir;
  1966. } catch (e) {
  1967. throw e;
  1968. } finally {
  1969. // add the node back to the hash (in case node_ops.rename
  1970. // changed its name)
  1971. FS.hashAddNode(old_node);
  1972. }
  1973. },
  1974. rmdir(path) {
  1975. var lookup = FS.lookupPath(path, {
  1976. parent: true
  1977. });
  1978. var parent = lookup.node;
  1979. var name = PATH.basename(path);
  1980. var node = FS.lookupNode(parent, name);
  1981. var errCode = FS.mayDelete(parent, name, true);
  1982. if (errCode) {
  1983. throw new FS.ErrnoError(errCode);
  1984. }
  1985. if (!parent.node_ops.rmdir) {
  1986. throw new FS.ErrnoError(63);
  1987. }
  1988. if (FS.isMountpoint(node)) {
  1989. throw new FS.ErrnoError(10);
  1990. }
  1991. parent.node_ops.rmdir(parent, name);
  1992. FS.destroyNode(node);
  1993. },
  1994. readdir(path) {
  1995. var lookup = FS.lookupPath(path, {
  1996. follow: true
  1997. });
  1998. var node = lookup.node;
  1999. if (!node.node_ops.readdir) {
  2000. throw new FS.ErrnoError(54);
  2001. }
  2002. return node.node_ops.readdir(node);
  2003. },
  2004. unlink(path) {
  2005. var lookup = FS.lookupPath(path, {
  2006. parent: true
  2007. });
  2008. var parent = lookup.node;
  2009. if (!parent) {
  2010. throw new FS.ErrnoError(44);
  2011. }
  2012. var name = PATH.basename(path);
  2013. var node = FS.lookupNode(parent, name);
  2014. var errCode = FS.mayDelete(parent, name, false);
  2015. if (errCode) {
  2016. // According to POSIX, we should map EISDIR to EPERM, but
  2017. // we instead do what Linux does (and we must, as we use
  2018. // the musl linux libc).
  2019. throw new FS.ErrnoError(errCode);
  2020. }
  2021. if (!parent.node_ops.unlink) {
  2022. throw new FS.ErrnoError(63);
  2023. }
  2024. if (FS.isMountpoint(node)) {
  2025. throw new FS.ErrnoError(10);
  2026. }
  2027. parent.node_ops.unlink(parent, name);
  2028. FS.destroyNode(node);
  2029. },
  2030. readlink(path) {
  2031. var lookup = FS.lookupPath(path);
  2032. var link = lookup.node;
  2033. if (!link) {
  2034. throw new FS.ErrnoError(44);
  2035. }
  2036. if (!link.node_ops.readlink) {
  2037. throw new FS.ErrnoError(28);
  2038. }
  2039. return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
  2040. },
  2041. stat(path, dontFollow) {
  2042. var lookup = FS.lookupPath(path, {
  2043. follow: !dontFollow
  2044. });
  2045. var node = lookup.node;
  2046. if (!node) {
  2047. throw new FS.ErrnoError(44);
  2048. }
  2049. if (!node.node_ops.getattr) {
  2050. throw new FS.ErrnoError(63);
  2051. }
  2052. return node.node_ops.getattr(node);
  2053. },
  2054. lstat(path) {
  2055. return FS.stat(path, true);
  2056. },
  2057. chmod(path, mode, dontFollow) {
  2058. var node;
  2059. if (typeof path == "string") {
  2060. var lookup = FS.lookupPath(path, {
  2061. follow: !dontFollow
  2062. });
  2063. node = lookup.node;
  2064. } else {
  2065. node = path;
  2066. }
  2067. if (!node.node_ops.setattr) {
  2068. throw new FS.ErrnoError(63);
  2069. }
  2070. node.node_ops.setattr(node, {
  2071. mode: (mode & 4095) | (node.mode & ~4095),
  2072. timestamp: Date.now()
  2073. });
  2074. },
  2075. lchmod(path, mode) {
  2076. FS.chmod(path, mode, true);
  2077. },
  2078. fchmod(fd, mode) {
  2079. var stream = FS.getStreamChecked(fd);
  2080. FS.chmod(stream.node, mode);
  2081. },
  2082. chown(path, uid, gid, dontFollow) {
  2083. var node;
  2084. if (typeof path == "string") {
  2085. var lookup = FS.lookupPath(path, {
  2086. follow: !dontFollow
  2087. });
  2088. node = lookup.node;
  2089. } else {
  2090. node = path;
  2091. }
  2092. if (!node.node_ops.setattr) {
  2093. throw new FS.ErrnoError(63);
  2094. }
  2095. node.node_ops.setattr(node, {
  2096. timestamp: Date.now()
  2097. });
  2098. },
  2099. // we ignore the uid / gid for now
  2100. lchown(path, uid, gid) {
  2101. FS.chown(path, uid, gid, true);
  2102. },
  2103. fchown(fd, uid, gid) {
  2104. var stream = FS.getStreamChecked(fd);
  2105. FS.chown(stream.node, uid, gid);
  2106. },
  2107. truncate(path, len) {
  2108. if (len < 0) {
  2109. throw new FS.ErrnoError(28);
  2110. }
  2111. var node;
  2112. if (typeof path == "string") {
  2113. var lookup = FS.lookupPath(path, {
  2114. follow: true
  2115. });
  2116. node = lookup.node;
  2117. } else {
  2118. node = path;
  2119. }
  2120. if (!node.node_ops.setattr) {
  2121. throw new FS.ErrnoError(63);
  2122. }
  2123. if (FS.isDir(node.mode)) {
  2124. throw new FS.ErrnoError(31);
  2125. }
  2126. if (!FS.isFile(node.mode)) {
  2127. throw new FS.ErrnoError(28);
  2128. }
  2129. var errCode = FS.nodePermissions(node, "w");
  2130. if (errCode) {
  2131. throw new FS.ErrnoError(errCode);
  2132. }
  2133. node.node_ops.setattr(node, {
  2134. size: len,
  2135. timestamp: Date.now()
  2136. });
  2137. },
  2138. ftruncate(fd, len) {
  2139. var stream = FS.getStreamChecked(fd);
  2140. if ((stream.flags & 2097155) === 0) {
  2141. throw new FS.ErrnoError(28);
  2142. }
  2143. FS.truncate(stream.node, len);
  2144. },
  2145. utime(path, atime, mtime) {
  2146. var lookup = FS.lookupPath(path, {
  2147. follow: true
  2148. });
  2149. var node = lookup.node;
  2150. node.node_ops.setattr(node, {
  2151. timestamp: Math.max(atime, mtime)
  2152. });
  2153. },
  2154. open(path, flags, mode) {
  2155. if (path === "") {
  2156. throw new FS.ErrnoError(44);
  2157. }
  2158. flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
  2159. if ((flags & 64)) {
  2160. mode = typeof mode == "undefined" ? 438 : /* 0666 */ mode;
  2161. mode = (mode & 4095) | 32768;
  2162. } else {
  2163. mode = 0;
  2164. }
  2165. var node;
  2166. if (typeof path == "object") {
  2167. node = path;
  2168. } else {
  2169. path = PATH.normalize(path);
  2170. try {
  2171. var lookup = FS.lookupPath(path, {
  2172. follow: !(flags & 131072)
  2173. });
  2174. node = lookup.node;
  2175. } catch (e) {}
  2176. }
  2177. // perhaps we need to create the node
  2178. var created = false;
  2179. if ((flags & 64)) {
  2180. if (node) {
  2181. // if O_CREAT and O_EXCL are set, error out if the node already exists
  2182. if ((flags & 128)) {
  2183. throw new FS.ErrnoError(20);
  2184. }
  2185. } else {
  2186. // node doesn't exist, try to create it
  2187. node = FS.mknod(path, mode, 0);
  2188. created = true;
  2189. }
  2190. }
  2191. if (!node) {
  2192. throw new FS.ErrnoError(44);
  2193. }
  2194. // can't truncate a device
  2195. if (FS.isChrdev(node.mode)) {
  2196. flags &= ~512;
  2197. }
  2198. // if asked only for a directory, then this must be one
  2199. if ((flags & 65536) && !FS.isDir(node.mode)) {
  2200. throw new FS.ErrnoError(54);
  2201. }
  2202. // check permissions, if this is not a file we just created now (it is ok to
  2203. // create and write to a file with read-only permissions; it is read-only
  2204. // for later use)
  2205. if (!created) {
  2206. var errCode = FS.mayOpen(node, flags);
  2207. if (errCode) {
  2208. throw new FS.ErrnoError(errCode);
  2209. }
  2210. }
  2211. // do truncation if necessary
  2212. if ((flags & 512) && !created) {
  2213. FS.truncate(node, 0);
  2214. }
  2215. // we've already handled these, don't pass down to the underlying vfs
  2216. flags &= ~(128 | 512 | 131072);
  2217. // register the stream with the filesystem
  2218. var stream = FS.createStream({
  2219. node,
  2220. path: FS.getPath(node),
  2221. // we want the absolute path to the node
  2222. flags,
  2223. seekable: true,
  2224. position: 0,
  2225. stream_ops: node.stream_ops,
  2226. // used by the file family libc calls (fopen, fwrite, ferror, etc.)
  2227. ungotten: [],
  2228. error: false
  2229. });
  2230. // call the new stream's open function
  2231. if (stream.stream_ops.open) {
  2232. stream.stream_ops.open(stream);
  2233. }
  2234. if (Module["logReadFiles"] && !(flags & 1)) {
  2235. if (!FS.readFiles) FS.readFiles = {};
  2236. if (!(path in FS.readFiles)) {
  2237. FS.readFiles[path] = 1;
  2238. }
  2239. }
  2240. return stream;
  2241. },
  2242. close(stream) {
  2243. if (FS.isClosed(stream)) {
  2244. throw new FS.ErrnoError(8);
  2245. }
  2246. if (stream.getdents) stream.getdents = null;
  2247. // free readdir state
  2248. try {
  2249. if (stream.stream_ops.close) {
  2250. stream.stream_ops.close(stream);
  2251. }
  2252. } catch (e) {
  2253. throw e;
  2254. } finally {
  2255. FS.closeStream(stream.fd);
  2256. }
  2257. stream.fd = null;
  2258. },
  2259. isClosed(stream) {
  2260. return stream.fd === null;
  2261. },
  2262. llseek(stream, offset, whence) {
  2263. if (FS.isClosed(stream)) {
  2264. throw new FS.ErrnoError(8);
  2265. }
  2266. if (!stream.seekable || !stream.stream_ops.llseek) {
  2267. throw new FS.ErrnoError(70);
  2268. }
  2269. if (whence != 0 && whence != 1 && whence != 2) {
  2270. throw new FS.ErrnoError(28);
  2271. }
  2272. stream.position = stream.stream_ops.llseek(stream, offset, whence);
  2273. stream.ungotten = [];
  2274. return stream.position;
  2275. },
  2276. read(stream, buffer, offset, length, position) {
  2277. if (length < 0 || position < 0) {
  2278. throw new FS.ErrnoError(28);
  2279. }
  2280. if (FS.isClosed(stream)) {
  2281. throw new FS.ErrnoError(8);
  2282. }
  2283. if ((stream.flags & 2097155) === 1) {
  2284. throw new FS.ErrnoError(8);
  2285. }
  2286. if (FS.isDir(stream.node.mode)) {
  2287. throw new FS.ErrnoError(31);
  2288. }
  2289. if (!stream.stream_ops.read) {
  2290. throw new FS.ErrnoError(28);
  2291. }
  2292. var seeking = typeof position != "undefined";
  2293. if (!seeking) {
  2294. position = stream.position;
  2295. } else if (!stream.seekable) {
  2296. throw new FS.ErrnoError(70);
  2297. }
  2298. var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
  2299. if (!seeking) stream.position += bytesRead;
  2300. return bytesRead;
  2301. },
  2302. write(stream, buffer, offset, length, position, canOwn) {
  2303. if (length < 0 || position < 0) {
  2304. throw new FS.ErrnoError(28);
  2305. }
  2306. if (FS.isClosed(stream)) {
  2307. throw new FS.ErrnoError(8);
  2308. }
  2309. if ((stream.flags & 2097155) === 0) {
  2310. throw new FS.ErrnoError(8);
  2311. }
  2312. if (FS.isDir(stream.node.mode)) {
  2313. throw new FS.ErrnoError(31);
  2314. }
  2315. if (!stream.stream_ops.write) {
  2316. throw new FS.ErrnoError(28);
  2317. }
  2318. if (stream.seekable && stream.flags & 1024) {
  2319. // seek to the end before writing in append mode
  2320. FS.llseek(stream, 0, 2);
  2321. }
  2322. var seeking = typeof position != "undefined";
  2323. if (!seeking) {
  2324. position = stream.position;
  2325. } else if (!stream.seekable) {
  2326. throw new FS.ErrnoError(70);
  2327. }
  2328. var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
  2329. if (!seeking) stream.position += bytesWritten;
  2330. return bytesWritten;
  2331. },
  2332. allocate(stream, offset, length) {
  2333. if (FS.isClosed(stream)) {
  2334. throw new FS.ErrnoError(8);
  2335. }
  2336. if (offset < 0 || length <= 0) {
  2337. throw new FS.ErrnoError(28);
  2338. }
  2339. if ((stream.flags & 2097155) === 0) {
  2340. throw new FS.ErrnoError(8);
  2341. }
  2342. if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
  2343. throw new FS.ErrnoError(43);
  2344. }
  2345. if (!stream.stream_ops.allocate) {
  2346. throw new FS.ErrnoError(138);
  2347. }
  2348. stream.stream_ops.allocate(stream, offset, length);
  2349. },
  2350. mmap(stream, length, position, prot, flags) {
  2351. // User requests writing to file (prot & PROT_WRITE != 0).
  2352. // Checking if we have permissions to write to the file unless
  2353. // MAP_PRIVATE flag is set. According to POSIX spec it is possible
  2354. // to write to file opened in read-only mode with MAP_PRIVATE flag,
  2355. // as all modifications will be visible only in the memory of
  2356. // the current process.
  2357. if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
  2358. throw new FS.ErrnoError(2);
  2359. }
  2360. if ((stream.flags & 2097155) === 1) {
  2361. throw new FS.ErrnoError(2);
  2362. }
  2363. if (!stream.stream_ops.mmap) {
  2364. throw new FS.ErrnoError(43);
  2365. }
  2366. if (!length) {
  2367. throw new FS.ErrnoError(28);
  2368. }
  2369. return stream.stream_ops.mmap(stream, length, position, prot, flags);
  2370. },
  2371. msync(stream, buffer, offset, length, mmapFlags) {
  2372. if (!stream.stream_ops.msync) {
  2373. return 0;
  2374. }
  2375. return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
  2376. },
  2377. ioctl(stream, cmd, arg) {
  2378. if (!stream.stream_ops.ioctl) {
  2379. throw new FS.ErrnoError(59);
  2380. }
  2381. return stream.stream_ops.ioctl(stream, cmd, arg);
  2382. },
  2383. readFile(path, opts = {}) {
  2384. opts.flags = opts.flags || 0;
  2385. opts.encoding = opts.encoding || "binary";
  2386. if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
  2387. throw new Error(`Invalid encoding type "${opts.encoding}"`);
  2388. }
  2389. var ret;
  2390. var stream = FS.open(path, opts.flags);
  2391. var stat = FS.stat(path);
  2392. var length = stat.size;
  2393. var buf = new Uint8Array(length);
  2394. FS.read(stream, buf, 0, length, 0);
  2395. if (opts.encoding === "utf8") {
  2396. ret = UTF8ArrayToString(buf, 0);
  2397. } else if (opts.encoding === "binary") {
  2398. ret = buf;
  2399. }
  2400. FS.close(stream);
  2401. return ret;
  2402. },
  2403. writeFile(path, data, opts = {}) {
  2404. opts.flags = opts.flags || 577;
  2405. var stream = FS.open(path, opts.flags, opts.mode);
  2406. if (typeof data == "string") {
  2407. var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
  2408. var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
  2409. FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
  2410. } else if (ArrayBuffer.isView(data)) {
  2411. FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
  2412. } else {
  2413. throw new Error("Unsupported data type");
  2414. }
  2415. FS.close(stream);
  2416. },
  2417. cwd: () => FS.currentPath,
  2418. chdir(path) {
  2419. var lookup = FS.lookupPath(path, {
  2420. follow: true
  2421. });
  2422. if (lookup.node === null) {
  2423. throw new FS.ErrnoError(44);
  2424. }
  2425. if (!FS.isDir(lookup.node.mode)) {
  2426. throw new FS.ErrnoError(54);
  2427. }
  2428. var errCode = FS.nodePermissions(lookup.node, "x");
  2429. if (errCode) {
  2430. throw new FS.ErrnoError(errCode);
  2431. }
  2432. FS.currentPath = lookup.path;
  2433. },
  2434. createDefaultDirectories() {
  2435. FS.mkdir("/tmp");
  2436. FS.mkdir("/home");
  2437. FS.mkdir("/home/web_user");
  2438. },
  2439. createDefaultDevices() {
  2440. // create /dev
  2441. FS.mkdir("/dev");
  2442. // setup /dev/null
  2443. FS.registerDevice(FS.makedev(1, 3), {
  2444. read: () => 0,
  2445. write: (stream, buffer, offset, length, pos) => length
  2446. });
  2447. FS.mkdev("/dev/null", FS.makedev(1, 3));
  2448. // setup /dev/tty and /dev/tty1
  2449. // stderr needs to print output using err() rather than out()
  2450. // so we register a second tty just for it.
  2451. TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
  2452. TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
  2453. FS.mkdev("/dev/tty", FS.makedev(5, 0));
  2454. FS.mkdev("/dev/tty1", FS.makedev(6, 0));
  2455. // setup /dev/[u]random
  2456. // use a buffer to avoid overhead of individual crypto calls per byte
  2457. var randomBuffer = new Uint8Array(1024), randomLeft = 0;
  2458. var randomByte = () => {
  2459. if (randomLeft === 0) {
  2460. randomLeft = randomFill(randomBuffer).byteLength;
  2461. }
  2462. return randomBuffer[--randomLeft];
  2463. };
  2464. FS.createDevice("/dev", "random", randomByte);
  2465. FS.createDevice("/dev", "urandom", randomByte);
  2466. // we're not going to emulate the actual shm device,
  2467. // just create the tmp dirs that reside in it commonly
  2468. FS.mkdir("/dev/shm");
  2469. FS.mkdir("/dev/shm/tmp");
  2470. },
  2471. createSpecialDirectories() {
  2472. // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the
  2473. // name of the stream for fd 6 (see test_unistd_ttyname)
  2474. FS.mkdir("/proc");
  2475. var proc_self = FS.mkdir("/proc/self");
  2476. FS.mkdir("/proc/self/fd");
  2477. FS.mount({
  2478. mount() {
  2479. var node = FS.createNode(proc_self, "fd", 16384 | 511, /* 0777 */ 73);
  2480. node.node_ops = {
  2481. lookup(parent, name) {
  2482. var fd = +name;
  2483. var stream = FS.getStreamChecked(fd);
  2484. var ret = {
  2485. parent: null,
  2486. mount: {
  2487. mountpoint: "fake"
  2488. },
  2489. node_ops: {
  2490. readlink: () => stream.path
  2491. }
  2492. };
  2493. ret.parent = ret;
  2494. // make it look like a simple root node
  2495. return ret;
  2496. }
  2497. };
  2498. return node;
  2499. }
  2500. }, {}, "/proc/self/fd");
  2501. },
  2502. createStandardStreams(input, output, error) {
  2503. // TODO deprecate the old functionality of a single
  2504. // input / output callback and that utilizes FS.createDevice
  2505. // and instead require a unique set of stream ops
  2506. // by default, we symlink the standard streams to the
  2507. // default tty devices. however, if the standard streams
  2508. // have been overwritten we create a unique device for
  2509. // them instead.
  2510. if (input) {
  2511. FS.createDevice("/dev", "stdin", input);
  2512. } else {
  2513. FS.symlink("/dev/tty", "/dev/stdin");
  2514. }
  2515. if (output) {
  2516. FS.createDevice("/dev", "stdout", null, output);
  2517. } else {
  2518. FS.symlink("/dev/tty", "/dev/stdout");
  2519. }
  2520. if (error) {
  2521. FS.createDevice("/dev", "stderr", null, error);
  2522. } else {
  2523. FS.symlink("/dev/tty1", "/dev/stderr");
  2524. }
  2525. // open default streams for the stdin, stdout and stderr devices
  2526. var stdin = FS.open("/dev/stdin", 0);
  2527. var stdout = FS.open("/dev/stdout", 1);
  2528. var stderr = FS.open("/dev/stderr", 1);
  2529. },
  2530. staticInit() {
  2531. // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
  2532. [ 44 ].forEach(code => {
  2533. FS.genericErrors[code] = new FS.ErrnoError(code);
  2534. FS.genericErrors[code].stack = "<generic error, no stack>";
  2535. });
  2536. FS.nameTable = new Array(4096);
  2537. FS.mount(MEMFS, {}, "/");
  2538. FS.createDefaultDirectories();
  2539. FS.createDefaultDevices();
  2540. FS.createSpecialDirectories();
  2541. FS.filesystems = {
  2542. "MEMFS": MEMFS
  2543. };
  2544. },
  2545. init(input, output, error) {
  2546. FS.initialized = true;
  2547. // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
  2548. input ??= Module["stdin"];
  2549. output ??= Module["stdout"];
  2550. error ??= Module["stderr"];
  2551. FS.createStandardStreams(input, output, error);
  2552. },
  2553. quit() {
  2554. FS.initialized = false;
  2555. // force-flush all streams, so we get musl std streams printed out
  2556. // close all of our streams
  2557. for (var i = 0; i < FS.streams.length; i++) {
  2558. var stream = FS.streams[i];
  2559. if (!stream) {
  2560. continue;
  2561. }
  2562. FS.close(stream);
  2563. }
  2564. },
  2565. findObject(path, dontResolveLastLink) {
  2566. var ret = FS.analyzePath(path, dontResolveLastLink);
  2567. if (!ret.exists) {
  2568. return null;
  2569. }
  2570. return ret.object;
  2571. },
  2572. analyzePath(path, dontResolveLastLink) {
  2573. // operate from within the context of the symlink's target
  2574. try {
  2575. var lookup = FS.lookupPath(path, {
  2576. follow: !dontResolveLastLink
  2577. });
  2578. path = lookup.path;
  2579. } catch (e) {}
  2580. var ret = {
  2581. isRoot: false,
  2582. exists: false,
  2583. error: 0,
  2584. name: null,
  2585. path: null,
  2586. object: null,
  2587. parentExists: false,
  2588. parentPath: null,
  2589. parentObject: null
  2590. };
  2591. try {
  2592. var lookup = FS.lookupPath(path, {
  2593. parent: true
  2594. });
  2595. ret.parentExists = true;
  2596. ret.parentPath = lookup.path;
  2597. ret.parentObject = lookup.node;
  2598. ret.name = PATH.basename(path);
  2599. lookup = FS.lookupPath(path, {
  2600. follow: !dontResolveLastLink
  2601. });
  2602. ret.exists = true;
  2603. ret.path = lookup.path;
  2604. ret.object = lookup.node;
  2605. ret.name = lookup.node.name;
  2606. ret.isRoot = lookup.path === "/";
  2607. } catch (e) {
  2608. ret.error = e.errno;
  2609. }
  2610. return ret;
  2611. },
  2612. createPath(parent, path, canRead, canWrite) {
  2613. parent = typeof parent == "string" ? parent : FS.getPath(parent);
  2614. var parts = path.split("/").reverse();
  2615. while (parts.length) {
  2616. var part = parts.pop();
  2617. if (!part) continue;
  2618. var current = PATH.join2(parent, part);
  2619. try {
  2620. FS.mkdir(current);
  2621. } catch (e) {}
  2622. // ignore EEXIST
  2623. parent = current;
  2624. }
  2625. return current;
  2626. },
  2627. createFile(parent, name, properties, canRead, canWrite) {
  2628. var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
  2629. var mode = FS_getMode(canRead, canWrite);
  2630. return FS.create(path, mode);
  2631. },
  2632. createDataFile(parent, name, data, canRead, canWrite, canOwn) {
  2633. var path = name;
  2634. if (parent) {
  2635. parent = typeof parent == "string" ? parent : FS.getPath(parent);
  2636. path = name ? PATH.join2(parent, name) : parent;
  2637. }
  2638. var mode = FS_getMode(canRead, canWrite);
  2639. var node = FS.create(path, mode);
  2640. if (data) {
  2641. if (typeof data == "string") {
  2642. var arr = new Array(data.length);
  2643. for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
  2644. data = arr;
  2645. }
  2646. // make sure we can write to the file
  2647. FS.chmod(node, mode | 146);
  2648. var stream = FS.open(node, 577);
  2649. FS.write(stream, data, 0, data.length, 0, canOwn);
  2650. FS.close(stream);
  2651. FS.chmod(node, mode);
  2652. }
  2653. },
  2654. createDevice(parent, name, input, output) {
  2655. var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
  2656. var mode = FS_getMode(!!input, !!output);
  2657. if (!FS.createDevice.major) FS.createDevice.major = 64;
  2658. var dev = FS.makedev(FS.createDevice.major++, 0);
  2659. // Create a fake device that a set of stream ops to emulate
  2660. // the old behavior.
  2661. FS.registerDevice(dev, {
  2662. open(stream) {
  2663. stream.seekable = false;
  2664. },
  2665. close(stream) {
  2666. // flush any pending line data
  2667. if (output?.buffer?.length) {
  2668. output(10);
  2669. }
  2670. },
  2671. read(stream, buffer, offset, length, pos) {
  2672. /* ignored */ var bytesRead = 0;
  2673. for (var i = 0; i < length; i++) {
  2674. var result;
  2675. try {
  2676. result = input();
  2677. } catch (e) {
  2678. throw new FS.ErrnoError(29);
  2679. }
  2680. if (result === undefined && bytesRead === 0) {
  2681. throw new FS.ErrnoError(6);
  2682. }
  2683. if (result === null || result === undefined) break;
  2684. bytesRead++;
  2685. buffer[offset + i] = result;
  2686. }
  2687. if (bytesRead) {
  2688. stream.node.timestamp = Date.now();
  2689. }
  2690. return bytesRead;
  2691. },
  2692. write(stream, buffer, offset, length, pos) {
  2693. for (var i = 0; i < length; i++) {
  2694. try {
  2695. output(buffer[offset + i]);
  2696. } catch (e) {
  2697. throw new FS.ErrnoError(29);
  2698. }
  2699. }
  2700. if (length) {
  2701. stream.node.timestamp = Date.now();
  2702. }
  2703. return i;
  2704. }
  2705. });
  2706. return FS.mkdev(path, mode, dev);
  2707. },
  2708. forceLoadFile(obj) {
  2709. if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
  2710. if (typeof XMLHttpRequest != "undefined") {
  2711. 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.");
  2712. } else {
  2713. // Command-line.
  2714. try {
  2715. obj.contents = readBinary(obj.url);
  2716. obj.usedBytes = obj.contents.length;
  2717. } catch (e) {
  2718. throw new FS.ErrnoError(29);
  2719. }
  2720. }
  2721. },
  2722. createLazyFile(parent, name, url, canRead, canWrite) {
  2723. // Lazy chunked Uint8Array (implements get and length from Uint8Array).
  2724. // Actual getting is abstracted away for eventual reuse.
  2725. class LazyUint8Array {
  2726. constructor() {
  2727. this.lengthKnown = false;
  2728. this.chunks = [];
  2729. }
  2730. // Loaded chunks. Index is the chunk number
  2731. get(idx) {
  2732. if (idx > this.length - 1 || idx < 0) {
  2733. return undefined;
  2734. }
  2735. var chunkOffset = idx % this.chunkSize;
  2736. var chunkNum = (idx / this.chunkSize) | 0;
  2737. return this.getter(chunkNum)[chunkOffset];
  2738. }
  2739. setDataGetter(getter) {
  2740. this.getter = getter;
  2741. }
  2742. cacheLength() {
  2743. // Find length
  2744. var xhr = new XMLHttpRequest;
  2745. xhr.open("HEAD", url, false);
  2746. xhr.send(null);
  2747. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  2748. var datalength = Number(xhr.getResponseHeader("Content-length"));
  2749. var header;
  2750. var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
  2751. var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
  2752. var chunkSize = 1024 * 1024;
  2753. // Chunk size in bytes
  2754. if (!hasByteServing) chunkSize = datalength;
  2755. // Function to get a range from the remote URL.
  2756. var doXHR = (from, to) => {
  2757. if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
  2758. if (to > datalength - 1) throw new Error("only " + datalength + " bytes available! programmer error!");
  2759. // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
  2760. var xhr = new XMLHttpRequest;
  2761. xhr.open("GET", url, false);
  2762. if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
  2763. // Some hints to the browser that we want binary data.
  2764. xhr.responseType = "arraybuffer";
  2765. if (xhr.overrideMimeType) {
  2766. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  2767. }
  2768. xhr.send(null);
  2769. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  2770. if (xhr.response !== undefined) {
  2771. return new Uint8Array(/** @type{Array<number>} */ (xhr.response || []));
  2772. }
  2773. return intArrayFromString(xhr.responseText || "", true);
  2774. };
  2775. var lazyArray = this;
  2776. lazyArray.setDataGetter(chunkNum => {
  2777. var start = chunkNum * chunkSize;
  2778. var end = (chunkNum + 1) * chunkSize - 1;
  2779. // including this byte
  2780. end = Math.min(end, datalength - 1);
  2781. // if datalength-1 is selected, this is the last block
  2782. if (typeof lazyArray.chunks[chunkNum] == "undefined") {
  2783. lazyArray.chunks[chunkNum] = doXHR(start, end);
  2784. }
  2785. if (typeof lazyArray.chunks[chunkNum] == "undefined") throw new Error("doXHR failed!");
  2786. return lazyArray.chunks[chunkNum];
  2787. });
  2788. if (usesGzip || !datalength) {
  2789. // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
  2790. chunkSize = datalength = 1;
  2791. // this will force getter(0)/doXHR do download the whole file
  2792. datalength = this.getter(0).length;
  2793. chunkSize = datalength;
  2794. out("LazyFiles on gzip forces download of the whole file when length is accessed");
  2795. }
  2796. this._length = datalength;
  2797. this._chunkSize = chunkSize;
  2798. this.lengthKnown = true;
  2799. }
  2800. get length() {
  2801. if (!this.lengthKnown) {
  2802. this.cacheLength();
  2803. }
  2804. return this._length;
  2805. }
  2806. get chunkSize() {
  2807. if (!this.lengthKnown) {
  2808. this.cacheLength();
  2809. }
  2810. return this._chunkSize;
  2811. }
  2812. }
  2813. if (typeof XMLHttpRequest != "undefined") {
  2814. if (!ENVIRONMENT_IS_WORKER) throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
  2815. var lazyArray = new LazyUint8Array;
  2816. var properties = {
  2817. isDevice: false,
  2818. contents: lazyArray
  2819. };
  2820. } else {
  2821. var properties = {
  2822. isDevice: false,
  2823. url
  2824. };
  2825. }
  2826. var node = FS.createFile(parent, name, properties, canRead, canWrite);
  2827. // This is a total hack, but I want to get this lazy file code out of the
  2828. // core of MEMFS. If we want to keep this lazy file concept I feel it should
  2829. // be its own thin LAZYFS proxying calls to MEMFS.
  2830. if (properties.contents) {
  2831. node.contents = properties.contents;
  2832. } else if (properties.url) {
  2833. node.contents = null;
  2834. node.url = properties.url;
  2835. }
  2836. // Add a function that defers querying the file size until it is asked the first time.
  2837. Object.defineProperties(node, {
  2838. usedBytes: {
  2839. get: function() {
  2840. return this.contents.length;
  2841. }
  2842. }
  2843. });
  2844. // override each stream op with one that tries to force load the lazy file first
  2845. var stream_ops = {};
  2846. var keys = Object.keys(node.stream_ops);
  2847. keys.forEach(key => {
  2848. var fn = node.stream_ops[key];
  2849. stream_ops[key] = (...args) => {
  2850. FS.forceLoadFile(node);
  2851. return fn(...args);
  2852. };
  2853. });
  2854. function writeChunks(stream, buffer, offset, length, position) {
  2855. var contents = stream.node.contents;
  2856. if (position >= contents.length) return 0;
  2857. var size = Math.min(contents.length - position, length);
  2858. if (contents.slice) {
  2859. // normal array
  2860. for (var i = 0; i < size; i++) {
  2861. buffer[offset + i] = contents[position + i];
  2862. }
  2863. } else {
  2864. for (var i = 0; i < size; i++) {
  2865. // LazyUint8Array from sync binary XHR
  2866. buffer[offset + i] = contents.get(position + i);
  2867. }
  2868. }
  2869. return size;
  2870. }
  2871. // use a custom read function
  2872. stream_ops.read = (stream, buffer, offset, length, position) => {
  2873. FS.forceLoadFile(node);
  2874. return writeChunks(stream, buffer, offset, length, position);
  2875. };
  2876. // use a custom mmap function
  2877. stream_ops.mmap = (stream, length, position, prot, flags) => {
  2878. FS.forceLoadFile(node);
  2879. var ptr = mmapAlloc(length);
  2880. if (!ptr) {
  2881. throw new FS.ErrnoError(48);
  2882. }
  2883. writeChunks(stream, HEAP8, ptr, length, position);
  2884. return {
  2885. ptr,
  2886. allocated: true
  2887. };
  2888. };
  2889. node.stream_ops = stream_ops;
  2890. return node;
  2891. }
  2892. };
  2893. Module["FS"] = FS;
  2894. var SYSCALLS = {
  2895. DEFAULT_POLLMASK: 5,
  2896. calculateAt(dirfd, path, allowEmpty) {
  2897. if (PATH.isAbs(path)) {
  2898. return path;
  2899. }
  2900. // relative path
  2901. var dir;
  2902. if (dirfd === -100) {
  2903. dir = FS.cwd();
  2904. } else {
  2905. var dirstream = SYSCALLS.getStreamFromFD(dirfd);
  2906. dir = dirstream.path;
  2907. }
  2908. if (path.length == 0) {
  2909. if (!allowEmpty) {
  2910. throw new FS.ErrnoError(44);
  2911. }
  2912. return dir;
  2913. }
  2914. return PATH.join2(dir, path);
  2915. },
  2916. doStat(func, path, buf) {
  2917. var stat = func(path);
  2918. HEAP32[((buf) >> 2)] = stat.dev;
  2919. HEAP32[(((buf) + (4)) >> 2)] = stat.mode;
  2920. HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink;
  2921. HEAP32[(((buf) + (12)) >> 2)] = stat.uid;
  2922. HEAP32[(((buf) + (16)) >> 2)] = stat.gid;
  2923. HEAP32[(((buf) + (20)) >> 2)] = stat.rdev;
  2924. (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  2925. HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);
  2926. HEAP32[(((buf) + (32)) >> 2)] = 4096;
  2927. HEAP32[(((buf) + (36)) >> 2)] = stat.blocks;
  2928. var atime = stat.atime.getTime();
  2929. var mtime = stat.mtime.getTime();
  2930. var ctime = stat.ctime.getTime();
  2931. (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3),
  2932. (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  2933. HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);
  2934. HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3;
  2935. (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3),
  2936. (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  2937. HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]);
  2938. HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3;
  2939. (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3),
  2940. (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  2941. HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]);
  2942. HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3;
  2943. (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  2944. HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]);
  2945. return 0;
  2946. },
  2947. doMsync(addr, stream, len, flags, offset) {
  2948. if (!FS.isFile(stream.node.mode)) {
  2949. throw new FS.ErrnoError(43);
  2950. }
  2951. if (flags & 2) {
  2952. // MAP_PRIVATE calls need not to be synced back to underlying fs
  2953. return 0;
  2954. }
  2955. var buffer = HEAPU8.slice(addr, addr + len);
  2956. FS.msync(stream, buffer, offset, len, flags);
  2957. },
  2958. getStreamFromFD(fd) {
  2959. var stream = FS.getStreamChecked(fd);
  2960. return stream;
  2961. },
  2962. varargs: undefined,
  2963. getStr(ptr) {
  2964. var ret = UTF8ToString(ptr);
  2965. return ret;
  2966. }
  2967. };
  2968. function ___syscall_fcntl64(fd, cmd, varargs) {
  2969. SYSCALLS.varargs = varargs;
  2970. try {
  2971. var stream = SYSCALLS.getStreamFromFD(fd);
  2972. switch (cmd) {
  2973. case 0:
  2974. {
  2975. var arg = syscallGetVarargI();
  2976. if (arg < 0) {
  2977. return -28;
  2978. }
  2979. while (FS.streams[arg]) {
  2980. arg++;
  2981. }
  2982. var newStream;
  2983. newStream = FS.dupStream(stream, arg);
  2984. return newStream.fd;
  2985. }
  2986. case 1:
  2987. case 2:
  2988. return 0;
  2989. // FD_CLOEXEC makes no sense for a single process.
  2990. case 3:
  2991. return stream.flags;
  2992. case 4:
  2993. {
  2994. var arg = syscallGetVarargI();
  2995. stream.flags |= arg;
  2996. return 0;
  2997. }
  2998. case 12:
  2999. {
  3000. var arg = syscallGetVarargP();
  3001. var offset = 0;
  3002. // We're always unlocked.
  3003. HEAP16[(((arg) + (offset)) >> 1)] = 2;
  3004. return 0;
  3005. }
  3006. case 13:
  3007. case 14:
  3008. return 0;
  3009. }
  3010. // Pretend that the locking is successful.
  3011. return -28;
  3012. } catch (e) {
  3013. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3014. return -e.errno;
  3015. }
  3016. }
  3017. function ___syscall_ioctl(fd, op, varargs) {
  3018. SYSCALLS.varargs = varargs;
  3019. try {
  3020. var stream = SYSCALLS.getStreamFromFD(fd);
  3021. switch (op) {
  3022. case 21509:
  3023. {
  3024. if (!stream.tty) return -59;
  3025. return 0;
  3026. }
  3027. case 21505:
  3028. {
  3029. if (!stream.tty) return -59;
  3030. if (stream.tty.ops.ioctl_tcgets) {
  3031. var termios = stream.tty.ops.ioctl_tcgets(stream);
  3032. var argp = syscallGetVarargP();
  3033. HEAP32[((argp) >> 2)] = termios.c_iflag || 0;
  3034. HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0;
  3035. HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0;
  3036. HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0;
  3037. for (var i = 0; i < 32; i++) {
  3038. HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0;
  3039. }
  3040. return 0;
  3041. }
  3042. return 0;
  3043. }
  3044. case 21510:
  3045. case 21511:
  3046. case 21512:
  3047. {
  3048. if (!stream.tty) return -59;
  3049. return 0;
  3050. }
  3051. // no-op, not actually adjusting terminal settings
  3052. case 21506:
  3053. case 21507:
  3054. case 21508:
  3055. {
  3056. if (!stream.tty) return -59;
  3057. if (stream.tty.ops.ioctl_tcsets) {
  3058. var argp = syscallGetVarargP();
  3059. var c_iflag = HEAP32[((argp) >> 2)];
  3060. var c_oflag = HEAP32[(((argp) + (4)) >> 2)];
  3061. var c_cflag = HEAP32[(((argp) + (8)) >> 2)];
  3062. var c_lflag = HEAP32[(((argp) + (12)) >> 2)];
  3063. var c_cc = [];
  3064. for (var i = 0; i < 32; i++) {
  3065. c_cc.push(HEAP8[(argp + i) + (17)]);
  3066. }
  3067. return stream.tty.ops.ioctl_tcsets(stream.tty, op, {
  3068. c_iflag,
  3069. c_oflag,
  3070. c_cflag,
  3071. c_lflag,
  3072. c_cc
  3073. });
  3074. }
  3075. return 0;
  3076. }
  3077. // no-op, not actually adjusting terminal settings
  3078. case 21519:
  3079. {
  3080. if (!stream.tty) return -59;
  3081. var argp = syscallGetVarargP();
  3082. HEAP32[((argp) >> 2)] = 0;
  3083. return 0;
  3084. }
  3085. case 21520:
  3086. {
  3087. if (!stream.tty) return -59;
  3088. return -28;
  3089. }
  3090. // not supported
  3091. case 21531:
  3092. {
  3093. var argp = syscallGetVarargP();
  3094. return FS.ioctl(stream, op, argp);
  3095. }
  3096. case 21523:
  3097. {
  3098. // TODO: in theory we should write to the winsize struct that gets
  3099. // passed in, but for now musl doesn't read anything on it
  3100. if (!stream.tty) return -59;
  3101. if (stream.tty.ops.ioctl_tiocgwinsz) {
  3102. var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
  3103. var argp = syscallGetVarargP();
  3104. HEAP16[((argp) >> 1)] = winsize[0];
  3105. HEAP16[(((argp) + (2)) >> 1)] = winsize[1];
  3106. }
  3107. return 0;
  3108. }
  3109. case 21524:
  3110. {
  3111. // TODO: technically, this ioctl call should change the window size.
  3112. // but, since emscripten doesn't have any concept of a terminal window
  3113. // yet, we'll just silently throw it away as we do TIOCGWINSZ
  3114. if (!stream.tty) return -59;
  3115. return 0;
  3116. }
  3117. case 21515:
  3118. {
  3119. if (!stream.tty) return -59;
  3120. return 0;
  3121. }
  3122. default:
  3123. return -28;
  3124. }
  3125. } // not supported
  3126. catch (e) {
  3127. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3128. return -e.errno;
  3129. }
  3130. }
  3131. function ___syscall_openat(dirfd, path, flags, varargs) {
  3132. SYSCALLS.varargs = varargs;
  3133. try {
  3134. path = SYSCALLS.getStr(path);
  3135. path = SYSCALLS.calculateAt(dirfd, path);
  3136. var mode = varargs ? syscallGetVarargI() : 0;
  3137. return FS.open(path, flags, mode).fd;
  3138. } catch (e) {
  3139. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3140. return -e.errno;
  3141. }
  3142. }
  3143. var __abort_js = () => {
  3144. abort("");
  3145. };
  3146. var nowIsMonotonic = 1;
  3147. var __emscripten_get_now_is_monotonic = () => nowIsMonotonic;
  3148. var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
  3149. var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
  3150. var __tzset_js = (timezone, daylight, std_name, dst_name) => {
  3151. // TODO: Use (malleable) environment variables instead of system settings.
  3152. var currentYear = (new Date).getFullYear();
  3153. var winter = new Date(currentYear, 0, 1);
  3154. var summer = new Date(currentYear, 6, 1);
  3155. var winterOffset = winter.getTimezoneOffset();
  3156. var summerOffset = summer.getTimezoneOffset();
  3157. // Local standard timezone offset. Local standard time is not adjusted for
  3158. // daylight savings. This code uses the fact that getTimezoneOffset returns
  3159. // a greater value during Standard Time versus Daylight Saving Time (DST).
  3160. // Thus it determines the expected output during Standard Time, and it
  3161. // compares whether the output of the given date the same (Standard) or less
  3162. // (DST).
  3163. var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
  3164. // timezone is specified as seconds west of UTC ("The external variable
  3165. // `timezone` shall be set to the difference, in seconds, between
  3166. // Coordinated Universal Time (UTC) and local standard time."), the same
  3167. // as returned by stdTimezoneOffset.
  3168. // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html
  3169. HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60;
  3170. HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset);
  3171. var extractZone = timezoneOffset => {
  3172. // Why inverse sign?
  3173. // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
  3174. var sign = timezoneOffset >= 0 ? "-" : "+";
  3175. var absOffset = Math.abs(timezoneOffset);
  3176. var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
  3177. var minutes = String(absOffset % 60).padStart(2, "0");
  3178. return `UTC${sign}${hours}${minutes}`;
  3179. };
  3180. var winterName = extractZone(winterOffset);
  3181. var summerName = extractZone(summerOffset);
  3182. if (summerOffset < winterOffset) {
  3183. // Northern hemisphere
  3184. stringToUTF8(winterName, std_name, 17);
  3185. stringToUTF8(summerName, dst_name, 17);
  3186. } else {
  3187. stringToUTF8(winterName, dst_name, 17);
  3188. stringToUTF8(summerName, std_name, 17);
  3189. }
  3190. };
  3191. var _emscripten_date_now = () => Date.now();
  3192. var _emscripten_get_now;
  3193. // Modern environment where performance.now() is supported:
  3194. // N.B. a shorter form "_emscripten_get_now = performance.now;" is
  3195. // unfortunately not allowed even in current browsers (e.g. FF Nightly 75).
  3196. _emscripten_get_now = () => performance.now();
  3197. var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
  3198. // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
  3199. // for any code that deals with heap sizes, which would require special
  3200. // casing all heap size related code to treat 0 specially.
  3201. 2147483648;
  3202. var growMemory = size => {
  3203. var b = wasmMemory.buffer;
  3204. var pages = (size - b.byteLength + 65535) / 65536;
  3205. try {
  3206. // round size grow request up to wasm page size (fixed 64KB per spec)
  3207. wasmMemory.grow(pages);
  3208. // .grow() takes a delta compared to the previous size
  3209. updateMemoryViews();
  3210. return 1;
  3211. } /*success*/ catch (e) {}
  3212. };
  3213. // implicit 0 return to save code size (caller will cast "undefined" into 0
  3214. // anyhow)
  3215. var _emscripten_resize_heap = requestedSize => {
  3216. var oldSize = HEAPU8.length;
  3217. // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
  3218. requestedSize >>>= 0;
  3219. // With multithreaded builds, races can happen (another thread might increase the size
  3220. // in between), so return a failure, and let the caller retry.
  3221. // Memory resize rules:
  3222. // 1. Always increase heap size to at least the requested size, rounded up
  3223. // to next page multiple.
  3224. // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap
  3225. // geometrically: increase the heap size according to
  3226. // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most
  3227. // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
  3228. // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap
  3229. // linearly: increase the heap size by at least
  3230. // MEMORY_GROWTH_LINEAR_STEP bytes.
  3231. // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by
  3232. // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
  3233. // 4. If we were unable to allocate as much memory, it may be due to
  3234. // over-eager decision to excessively reserve due to (3) above.
  3235. // Hence if an allocation fails, cut down on the amount of excess
  3236. // growth, in an attempt to succeed to perform a smaller allocation.
  3237. // A limit is set for how much we can grow. We should not exceed that
  3238. // (the wasm binary specifies it, so if we tried, we'd fail anyhow).
  3239. var maxHeapSize = getHeapMax();
  3240. if (requestedSize > maxHeapSize) {
  3241. return false;
  3242. }
  3243. // Loop through potential heap size increases. If we attempt a too eager
  3244. // reservation that fails, cut down on the attempted size and reserve a
  3245. // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
  3246. for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
  3247. var overGrownHeapSize = oldSize * (1 + .2 / cutDown);
  3248. // ensure geometric growth
  3249. // but limit overreserving (default to capping at +96MB overgrowth at most)
  3250. overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
  3251. var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
  3252. var replacement = growMemory(newSize);
  3253. if (replacement) {
  3254. return true;
  3255. }
  3256. }
  3257. return false;
  3258. };
  3259. var ENV = {};
  3260. var getExecutableName = () => thisProgram || "./this.program";
  3261. var getEnvStrings = () => {
  3262. if (!getEnvStrings.strings) {
  3263. // Default values.
  3264. // Browser language detection #8751
  3265. var lang = ((typeof navigator == "object" && navigator.languages && navigator.languages[0]) || "C").replace("-", "_") + ".UTF-8";
  3266. var env = {
  3267. "USER": "web_user",
  3268. "LOGNAME": "web_user",
  3269. "PATH": "/",
  3270. "PWD": "/",
  3271. "HOME": "/home/web_user",
  3272. "LANG": lang,
  3273. "_": getExecutableName()
  3274. };
  3275. // Apply the user-provided values, if any.
  3276. for (var x in ENV) {
  3277. // x is a key in ENV; if ENV[x] is undefined, that means it was
  3278. // explicitly set to be so. We allow user code to do that to
  3279. // force variables with default values to remain unset.
  3280. if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x];
  3281. }
  3282. var strings = [];
  3283. for (var x in env) {
  3284. strings.push(`${x}=${env[x]}`);
  3285. }
  3286. getEnvStrings.strings = strings;
  3287. }
  3288. return getEnvStrings.strings;
  3289. };
  3290. var stringToAscii = (str, buffer) => {
  3291. for (var i = 0; i < str.length; ++i) {
  3292. HEAP8[buffer++] = str.charCodeAt(i);
  3293. }
  3294. // Null-terminate the string
  3295. HEAP8[buffer] = 0;
  3296. };
  3297. var _environ_get = (__environ, environ_buf) => {
  3298. var bufSize = 0;
  3299. getEnvStrings().forEach((string, i) => {
  3300. var ptr = environ_buf + bufSize;
  3301. HEAPU32[(((__environ) + (i * 4)) >> 2)] = ptr;
  3302. stringToAscii(string, ptr);
  3303. bufSize += string.length + 1;
  3304. });
  3305. return 0;
  3306. };
  3307. var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
  3308. var strings = getEnvStrings();
  3309. HEAPU32[((penviron_count) >> 2)] = strings.length;
  3310. var bufSize = 0;
  3311. strings.forEach(string => bufSize += string.length + 1);
  3312. HEAPU32[((penviron_buf_size) >> 2)] = bufSize;
  3313. return 0;
  3314. };
  3315. function _fd_close(fd) {
  3316. try {
  3317. var stream = SYSCALLS.getStreamFromFD(fd);
  3318. FS.close(stream);
  3319. return 0;
  3320. } catch (e) {
  3321. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3322. return e.errno;
  3323. }
  3324. }
  3325. /** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => {
  3326. var ret = 0;
  3327. for (var i = 0; i < iovcnt; i++) {
  3328. var ptr = HEAPU32[((iov) >> 2)];
  3329. var len = HEAPU32[(((iov) + (4)) >> 2)];
  3330. iov += 8;
  3331. var curr = FS.read(stream, HEAP8, ptr, len, offset);
  3332. if (curr < 0) return -1;
  3333. ret += curr;
  3334. if (curr < len) break;
  3335. // nothing more to read
  3336. if (typeof offset != "undefined") {
  3337. offset += curr;
  3338. }
  3339. }
  3340. return ret;
  3341. };
  3342. function _fd_read(fd, iov, iovcnt, pnum) {
  3343. try {
  3344. var stream = SYSCALLS.getStreamFromFD(fd);
  3345. var num = doReadv(stream, iov, iovcnt);
  3346. HEAPU32[((pnum) >> 2)] = num;
  3347. return 0;
  3348. } catch (e) {
  3349. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3350. return e.errno;
  3351. }
  3352. }
  3353. var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;
  3354. function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
  3355. var offset = convertI32PairToI53Checked(offset_low, offset_high);
  3356. try {
  3357. if (isNaN(offset)) return 61;
  3358. var stream = SYSCALLS.getStreamFromFD(fd);
  3359. FS.llseek(stream, offset, whence);
  3360. (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],
  3361. HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]);
  3362. if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
  3363. // reset readdir state
  3364. return 0;
  3365. } catch (e) {
  3366. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3367. return e.errno;
  3368. }
  3369. }
  3370. /** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => {
  3371. var ret = 0;
  3372. for (var i = 0; i < iovcnt; i++) {
  3373. var ptr = HEAPU32[((iov) >> 2)];
  3374. var len = HEAPU32[(((iov) + (4)) >> 2)];
  3375. iov += 8;
  3376. var curr = FS.write(stream, HEAP8, ptr, len, offset);
  3377. if (curr < 0) return -1;
  3378. ret += curr;
  3379. if (curr < len) {
  3380. // No more space to write.
  3381. break;
  3382. }
  3383. if (typeof offset != "undefined") {
  3384. offset += curr;
  3385. }
  3386. }
  3387. return ret;
  3388. };
  3389. function _fd_write(fd, iov, iovcnt, pnum) {
  3390. try {
  3391. var stream = SYSCALLS.getStreamFromFD(fd);
  3392. var num = doWritev(stream, iov, iovcnt);
  3393. HEAPU32[((pnum) >> 2)] = num;
  3394. return 0;
  3395. } catch (e) {
  3396. if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
  3397. return e.errno;
  3398. }
  3399. }
  3400. var getCFunc = ident => {
  3401. var func = Module["_" + ident];
  3402. // closure exported function
  3403. return func;
  3404. };
  3405. var writeArrayToMemory = (array, buffer) => {
  3406. HEAP8.set(array, buffer);
  3407. };
  3408. var stackAlloc = sz => __emscripten_stack_alloc(sz);
  3409. var stringToUTF8OnStack = str => {
  3410. var size = lengthBytesUTF8(str) + 1;
  3411. var ret = stackAlloc(size);
  3412. stringToUTF8(str, ret, size);
  3413. return ret;
  3414. };
  3415. /**
  3416. * @param {string|null=} returnType
  3417. * @param {Array=} argTypes
  3418. * @param {Arguments|Array=} args
  3419. * @param {Object=} opts
  3420. */ var ccall = (ident, returnType, argTypes, args, opts) => {
  3421. // For fast lookup of conversion functions
  3422. var toC = {
  3423. "string": str => {
  3424. var ret = 0;
  3425. if (str !== null && str !== undefined && str !== 0) {
  3426. // null string
  3427. // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
  3428. ret = stringToUTF8OnStack(str);
  3429. }
  3430. return ret;
  3431. },
  3432. "array": arr => {
  3433. var ret = stackAlloc(arr.length);
  3434. writeArrayToMemory(arr, ret);
  3435. return ret;
  3436. }
  3437. };
  3438. function convertReturnValue(ret) {
  3439. if (returnType === "string") {
  3440. return UTF8ToString(ret);
  3441. }
  3442. if (returnType === "boolean") return Boolean(ret);
  3443. return ret;
  3444. }
  3445. var func = getCFunc(ident);
  3446. var cArgs = [];
  3447. var stack = 0;
  3448. if (args) {
  3449. for (var i = 0; i < args.length; i++) {
  3450. var converter = toC[argTypes[i]];
  3451. if (converter) {
  3452. if (stack === 0) stack = stackSave();
  3453. cArgs[i] = converter(args[i]);
  3454. } else {
  3455. cArgs[i] = args[i];
  3456. }
  3457. }
  3458. }
  3459. var ret = func(...cArgs);
  3460. function onDone(ret) {
  3461. if (stack !== 0) stackRestore(stack);
  3462. return convertReturnValue(ret);
  3463. }
  3464. ret = onDone(ret);
  3465. return ret;
  3466. };
  3467. /**
  3468. * @param {string=} returnType
  3469. * @param {Array=} argTypes
  3470. * @param {Object=} opts
  3471. */ var cwrap = (ident, returnType, argTypes, opts) => {
  3472. // When the function takes numbers and returns a number, we can just return
  3473. // the original function
  3474. var numericArgs = !argTypes || argTypes.every(type => type === "number" || type === "boolean");
  3475. var numericRet = returnType !== "string";
  3476. if (numericRet && numericArgs && !opts) {
  3477. return getCFunc(ident);
  3478. }
  3479. return (...args) => ccall(ident, returnType, argTypes, args, opts);
  3480. };
  3481. var stringToNewUTF8 = str => {
  3482. var size = lengthBytesUTF8(str) + 1;
  3483. var ret = _malloc(size);
  3484. if (ret) stringToUTF8(str, ret, size);
  3485. return ret;
  3486. };
  3487. FS.createPreloadedFile = FS_createPreloadedFile;
  3488. FS.staticInit();
  3489. var wasmImports = {
  3490. /** @export */ __assert_fail: ___assert_fail,
  3491. /** @export */ __cxa_throw: ___cxa_throw,
  3492. /** @export */ __syscall_fcntl64: ___syscall_fcntl64,
  3493. /** @export */ __syscall_ioctl: ___syscall_ioctl,
  3494. /** @export */ __syscall_openat: ___syscall_openat,
  3495. /** @export */ _abort_js: __abort_js,
  3496. /** @export */ _emscripten_get_now_is_monotonic: __emscripten_get_now_is_monotonic,
  3497. /** @export */ _emscripten_memcpy_js: __emscripten_memcpy_js,
  3498. /** @export */ _tzset_js: __tzset_js,
  3499. /** @export */ emscripten_date_now: _emscripten_date_now,
  3500. /** @export */ emscripten_get_now: _emscripten_get_now,
  3501. /** @export */ emscripten_resize_heap: _emscripten_resize_heap,
  3502. /** @export */ environ_get: _environ_get,
  3503. /** @export */ environ_sizes_get: _environ_sizes_get,
  3504. /** @export */ fd_close: _fd_close,
  3505. /** @export */ fd_read: _fd_read,
  3506. /** @export */ fd_seek: _fd_seek,
  3507. /** @export */ fd_write: _fd_write
  3508. };
  3509. var wasmExports = createWasm();
  3510. var ___wasm_call_ctors = () => (___wasm_call_ctors = wasmExports["__wasm_call_ctors"])();
  3511. var _Hunspell_create = Module["_Hunspell_create"] = (a0, a1) => (_Hunspell_create = Module["_Hunspell_create"] = wasmExports["Hunspell_create"])(a0, a1);
  3512. var _Hunspell_destroy = Module["_Hunspell_destroy"] = a0 => (_Hunspell_destroy = Module["_Hunspell_destroy"] = wasmExports["Hunspell_destroy"])(a0);
  3513. var _Hunspell_add_dic = Module["_Hunspell_add_dic"] = (a0, a1) => (_Hunspell_add_dic = Module["_Hunspell_add_dic"] = wasmExports["Hunspell_add_dic"])(a0, a1);
  3514. var _Hunspell_spell = Module["_Hunspell_spell"] = (a0, a1) => (_Hunspell_spell = Module["_Hunspell_spell"] = wasmExports["Hunspell_spell"])(a0, a1);
  3515. var _Hunspell_suggest = Module["_Hunspell_suggest"] = (a0, a1, a2) => (_Hunspell_suggest = Module["_Hunspell_suggest"] = wasmExports["Hunspell_suggest"])(a0, a1, a2);
  3516. var _Hunspell_add = Module["_Hunspell_add"] = (a0, a1) => (_Hunspell_add = Module["_Hunspell_add"] = wasmExports["Hunspell_add"])(a0, a1);
  3517. var _Hunspell_remove = Module["_Hunspell_remove"] = (a0, a1) => (_Hunspell_remove = Module["_Hunspell_remove"] = wasmExports["Hunspell_remove"])(a0, a1);
  3518. var _Hunspell_free_list = Module["_Hunspell_free_list"] = (a0, a1, a2) => (_Hunspell_free_list = Module["_Hunspell_free_list"] = wasmExports["Hunspell_free_list"])(a0, a1, a2);
  3519. var _malloc = Module["_malloc"] = a0 => (_malloc = Module["_malloc"] = wasmExports["malloc"])(a0);
  3520. var _free = Module["_free"] = a0 => (_free = Module["_free"] = wasmExports["free"])(a0);
  3521. var __emscripten_stack_restore = a0 => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);
  3522. var __emscripten_stack_alloc = a0 => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);
  3523. var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();
  3524. var dynCall_iiiiij = Module["dynCall_iiiiij"] = (a0, a1, a2, a3, a4, a5, a6) => (dynCall_iiiiij = Module["dynCall_iiiiij"] = wasmExports["dynCall_iiiiij"])(a0, a1, a2, a3, a4, a5, a6);
  3525. var dynCall_iiiiijj = Module["dynCall_iiiiijj"] = (a0, a1, a2, a3, a4, a5, a6, a7, a8) => (dynCall_iiiiijj = Module["dynCall_iiiiijj"] = wasmExports["dynCall_iiiiijj"])(a0, a1, a2, a3, a4, a5, a6, a7, a8);
  3526. var dynCall_iiiiiijj = Module["dynCall_iiiiiijj"] = (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) => (dynCall_iiiiiijj = Module["dynCall_iiiiiijj"] = wasmExports["dynCall_iiiiiijj"])(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
  3527. var dynCall_jiji = Module["dynCall_jiji"] = (a0, a1, a2, a3, a4) => (dynCall_jiji = Module["dynCall_jiji"] = wasmExports["dynCall_jiji"])(a0, a1, a2, a3, a4);
  3528. var dynCall_viijii = Module["dynCall_viijii"] = (a0, a1, a2, a3, a4, a5, a6) => (dynCall_viijii = Module["dynCall_viijii"] = wasmExports["dynCall_viijii"])(a0, a1, a2, a3, a4, a5, a6);
  3529. // include: postamble.js
  3530. // === Auto-generated postamble setup entry stuff ===
  3531. Module["ccall"] = ccall;
  3532. Module["cwrap"] = cwrap;
  3533. Module["getValue"] = getValue;
  3534. Module["UTF8ToString"] = UTF8ToString;
  3535. Module["stringToNewUTF8"] = stringToNewUTF8;
  3536. Module["MEMFS"] = MEMFS;
  3537. var calledRun;
  3538. dependenciesFulfilled = function runCaller() {
  3539. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  3540. if (!calledRun) run();
  3541. if (!calledRun) dependenciesFulfilled = runCaller;
  3542. };
  3543. // try this again later, after new deps are fulfilled
  3544. function run() {
  3545. if (runDependencies > 0) {
  3546. return;
  3547. }
  3548. preRun();
  3549. // a preRun added a dependency, run will be called later
  3550. if (runDependencies > 0) {
  3551. return;
  3552. }
  3553. function doRun() {
  3554. // run may have just been called through dependencies being fulfilled just in this very frame,
  3555. // or while the async setStatus time below was happening
  3556. if (calledRun) return;
  3557. calledRun = true;
  3558. Module["calledRun"] = true;
  3559. if (ABORT) return;
  3560. initRuntime();
  3561. readyPromiseResolve(Module);
  3562. Module["onRuntimeInitialized"]?.();
  3563. postRun();
  3564. }
  3565. if (Module["setStatus"]) {
  3566. Module["setStatus"]("Running...");
  3567. setTimeout(() => {
  3568. setTimeout(() => Module["setStatus"](""), 1);
  3569. doRun();
  3570. }, 1);
  3571. } else {
  3572. doRun();
  3573. }
  3574. }
  3575. if (Module["preInit"]) {
  3576. if (typeof Module["preInit"] == "function") Module["preInit"] = [ Module["preInit"] ];
  3577. while (Module["preInit"].length > 0) {
  3578. Module["preInit"].pop()();
  3579. }
  3580. }
  3581. run();
  3582. // end include: postamble.js
  3583. // include: postamble_modularize.js
  3584. // In MODULARIZE mode we wrap the generated code in a factory function
  3585. // and return either the Module itself, or a promise of the module.
  3586. // We assign to the `moduleRtn` global here and configure closure to see
  3587. // this as and extern so it won't get minified.
  3588. moduleRtn = readyPromise;
  3589. return moduleRtn;
  3590. }
  3591. );
  3592. })();
  3593. export default Module;