hunspell.mjs 125 KB

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