libopus.js 244 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555
  1. // The Module object: Our interface to the outside world. We import
  2. // and export values on it. There are various ways Module can be used:
  3. // 1. Not defined. We create it here
  4. // 2. A function parameter, function(Module) { ..generated code.. }
  5. // 3. pre-run appended it, var Module = {}; ..generated code..
  6. // 4. External script tag defines var Module.
  7. // We need to check if Module already exists (e.g. case 3 above).
  8. // Substitution will be replaced with actual code on later stage of the build,
  9. // this way Closure Compiler will not mangle it (e.g. case 4. above).
  10. // Note that if you want to run closure, and also to use Module
  11. // after the generated code, you will need to define var Module = {};
  12. // before the code. Then that object will be used in the code, and you
  13. // can continue to use Module afterwards as well.
  14. var Module = typeof Module !== 'undefined' ? Module : {};
  15. // See https://caniuse.com/mdn-javascript_builtins_object_assign
  16. var objAssign = Object.assign;
  17. // --pre-jses are emitted after the Module integration code, so that they can
  18. // refer to Module (if they choose; they can also define Module)
  19. Module["onRuntimeInitialized"] = function(){
  20. if(Module.onload)
  21. Module.onload();
  22. Module.loaded = true;
  23. }
  24. Module["locateFile"] = function(url){
  25. if(url == "libopus.wasm?v=be6f45f8" && typeof LIBOPUS_WASM_URL != "undefined")
  26. return LIBOPUS_WASM_URL;
  27. else
  28. return url;
  29. }
  30. // Sometimes an existing Module object exists with properties
  31. // meant to overwrite the default module functionality. Here
  32. // we collect those properties and reapply _after_ we configure
  33. // the current environment's defaults to avoid having to be so
  34. // defensive during initialization.
  35. var moduleOverrides = objAssign({}, Module);
  36. var arguments_ = [];
  37. var thisProgram = './this.program';
  38. var quit_ = (status, toThrow) => {
  39. throw toThrow;
  40. };
  41. // Determine the runtime environment we are in. You can customize this by
  42. // setting the ENVIRONMENT setting at compile time (see settings.js).
  43. // Attempt to auto-detect the environment
  44. var ENVIRONMENT_IS_WEB = typeof window === 'object';
  45. var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
  46. // N.b. Electron.js environment is simultaneously a NODE-environment, but
  47. // also a web environment.
  48. var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
  49. var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  50. if (Module['ENVIRONMENT']) {
  51. throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)');
  52. }
  53. // `/` should be present at the end if `scriptDirectory` is not empty
  54. var scriptDirectory = '';
  55. function locateFile(path) {
  56. if (Module['locateFile']) {
  57. return Module['locateFile'](path, scriptDirectory);
  58. }
  59. return scriptDirectory + path;
  60. }
  61. // Hooks that are implemented differently in different runtime environments.
  62. var read_,
  63. readAsync,
  64. readBinary,
  65. setWindowTitle;
  66. // Normally we don't log exceptions but instead let them bubble out the top
  67. // level where the embedding environment (e.g. the browser) can handle
  68. // them.
  69. // However under v8 and node we sometimes exit the process direcly in which case
  70. // its up to use us to log the exception before exiting.
  71. // If we fix https://github.com/emscripten-core/emscripten/issues/15080
  72. // this may no longer be needed under node.
  73. function logExceptionOnExit(e) {
  74. if (e instanceof ExitStatus) return;
  75. let toLog = e;
  76. if (e && typeof e === 'object' && e.stack) {
  77. toLog = [e, e.stack];
  78. }
  79. err('exiting due to exception: ' + toLog);
  80. }
  81. var fs;
  82. var nodePath;
  83. var requireNodeFS;
  84. if (ENVIRONMENT_IS_NODE) {
  85. if (!(typeof process === 'object' && typeof require === 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  86. if (ENVIRONMENT_IS_WORKER) {
  87. scriptDirectory = require('path').dirname(scriptDirectory) + '/';
  88. } else {
  89. scriptDirectory = __dirname + '/';
  90. }
  91. // include: node_shell_read.js
  92. requireNodeFS = () => {
  93. // Use nodePath as the indicator for these not being initialized,
  94. // since in some environments a global fs may have already been
  95. // created.
  96. if (!nodePath) {
  97. fs = require('fs');
  98. nodePath = require('path');
  99. }
  100. };
  101. read_ = function shell_read(filename, binary) {
  102. requireNodeFS();
  103. filename = nodePath['normalize'](filename);
  104. return fs.readFileSync(filename, binary ? null : 'utf8');
  105. };
  106. readBinary = (filename) => {
  107. var ret = read_(filename, true);
  108. if (!ret.buffer) {
  109. ret = new Uint8Array(ret);
  110. }
  111. assert(ret.buffer);
  112. return ret;
  113. };
  114. readAsync = (filename, onload, onerror) => {
  115. requireNodeFS();
  116. filename = nodePath['normalize'](filename);
  117. fs.readFile(filename, function(err, data) {
  118. if (err) onerror(err);
  119. else onload(data.buffer);
  120. });
  121. };
  122. // end include: node_shell_read.js
  123. if (process['argv'].length > 1) {
  124. thisProgram = process['argv'][1].replace(/\\/g, '/');
  125. }
  126. arguments_ = process['argv'].slice(2);
  127. if (typeof module !== 'undefined') {
  128. module['exports'] = Module;
  129. }
  130. process['on']('uncaughtException', function(ex) {
  131. // suppress ExitStatus exceptions from showing an error
  132. if (!(ex instanceof ExitStatus)) {
  133. throw ex;
  134. }
  135. });
  136. // Without this older versions of node (< v15) will log unhandled rejections
  137. // but return 0, which is not normally the desired behaviour. This is
  138. // not be needed with node v15 and about because it is now the default
  139. // behaviour:
  140. // See https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode
  141. process['on']('unhandledRejection', function(reason) { throw reason; });
  142. quit_ = (status, toThrow) => {
  143. if (keepRuntimeAlive()) {
  144. process['exitCode'] = status;
  145. throw toThrow;
  146. }
  147. logExceptionOnExit(toThrow);
  148. process['exit'](status);
  149. };
  150. Module['inspect'] = function () { return '[Emscripten Module object]'; };
  151. } else
  152. if (ENVIRONMENT_IS_SHELL) {
  153. if ((typeof process === 'object' && typeof require === 'function') || typeof window === 'object' || typeof importScripts === 'function') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  154. if (typeof read != 'undefined') {
  155. read_ = function shell_read(f) {
  156. return read(f);
  157. };
  158. }
  159. readBinary = function readBinary(f) {
  160. let data;
  161. if (typeof readbuffer === 'function') {
  162. return new Uint8Array(readbuffer(f));
  163. }
  164. data = read(f, 'binary');
  165. assert(typeof data === 'object');
  166. return data;
  167. };
  168. readAsync = function readAsync(f, onload, onerror) {
  169. setTimeout(() => onload(readBinary(f)), 0);
  170. };
  171. if (typeof scriptArgs != 'undefined') {
  172. arguments_ = scriptArgs;
  173. } else if (typeof arguments != 'undefined') {
  174. arguments_ = arguments;
  175. }
  176. if (typeof quit === 'function') {
  177. quit_ = (status, toThrow) => {
  178. logExceptionOnExit(toThrow);
  179. quit(status);
  180. };
  181. }
  182. if (typeof print !== 'undefined') {
  183. // Prefer to use print/printErr where they exist, as they usually work better.
  184. if (typeof console === 'undefined') console = /** @type{!Console} */({});
  185. console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
  186. console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr !== 'undefined' ? printErr : print);
  187. }
  188. } else
  189. // Note that this includes Node.js workers when relevant (pthreads is enabled).
  190. // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
  191. // ENVIRONMENT_IS_NODE.
  192. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  193. if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
  194. scriptDirectory = self.location.href;
  195. } else if (typeof document !== 'undefined' && document.currentScript) { // web
  196. scriptDirectory = document.currentScript.src;
  197. }
  198. // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
  199. // otherwise, slice off the final part of the url to find the script directory.
  200. // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
  201. // and scriptDirectory will correctly be replaced with an empty string.
  202. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),
  203. // they are removed because they could contain a slash.
  204. if (scriptDirectory.indexOf('blob:') !== 0) {
  205. scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf('/')+1);
  206. } else {
  207. scriptDirectory = '';
  208. }
  209. if (!(typeof window === 'object' || typeof importScripts === 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  210. // Differentiate the Web Worker from the Node Worker case, as reading must
  211. // be done differently.
  212. {
  213. // include: web_or_worker_shell_read.js
  214. read_ = (url) => {
  215. var xhr = new XMLHttpRequest();
  216. xhr.open('GET', url, false);
  217. xhr.send(null);
  218. return xhr.responseText;
  219. }
  220. if (ENVIRONMENT_IS_WORKER) {
  221. readBinary = (url) => {
  222. var xhr = new XMLHttpRequest();
  223. xhr.open('GET', url, false);
  224. xhr.responseType = 'arraybuffer';
  225. xhr.send(null);
  226. return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
  227. };
  228. }
  229. readAsync = (url, onload, onerror) => {
  230. var xhr = new XMLHttpRequest();
  231. xhr.open('GET', url, true);
  232. xhr.responseType = 'arraybuffer';
  233. xhr.onload = () => {
  234. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  235. onload(xhr.response);
  236. return;
  237. }
  238. onerror();
  239. };
  240. xhr.onerror = onerror;
  241. xhr.send(null);
  242. }
  243. // end include: web_or_worker_shell_read.js
  244. }
  245. setWindowTitle = (title) => document.title = title;
  246. } else
  247. {
  248. throw new Error('environment detection error');
  249. }
  250. var out = Module['print'] || console.log.bind(console);
  251. var err = Module['printErr'] || console.warn.bind(console);
  252. // Merge back in the overrides
  253. objAssign(Module, moduleOverrides);
  254. // Free the object hierarchy contained in the overrides, this lets the GC
  255. // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
  256. moduleOverrides = null;
  257. // Emit code to handle expected values on the Module object. This applies Module.x
  258. // to the proper local x. This has two benefits: first, we only emit it if it is
  259. // expected to arrive, and second, by using a local everywhere else that can be
  260. // minified.
  261. if (Module['arguments']) arguments_ = Module['arguments'];
  262. if (!Object.getOwnPropertyDescriptor(Module, 'arguments')) {
  263. Object.defineProperty(Module, 'arguments', {
  264. configurable: true,
  265. get: function() {
  266. abort('Module.arguments has been replaced with plain arguments_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  267. }
  268. });
  269. }
  270. if (Module['thisProgram']) thisProgram = Module['thisProgram'];
  271. if (!Object.getOwnPropertyDescriptor(Module, 'thisProgram')) {
  272. Object.defineProperty(Module, 'thisProgram', {
  273. configurable: true,
  274. get: function() {
  275. abort('Module.thisProgram has been replaced with plain thisProgram (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  276. }
  277. });
  278. }
  279. if (Module['quit']) quit_ = Module['quit'];
  280. if (!Object.getOwnPropertyDescriptor(Module, 'quit')) {
  281. Object.defineProperty(Module, 'quit', {
  282. configurable: true,
  283. get: function() {
  284. abort('Module.quit has been replaced with plain quit_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  285. }
  286. });
  287. }
  288. // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
  289. // Assertions on removed incoming Module JS APIs.
  290. assert(typeof Module['memoryInitializerPrefixURL'] === 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
  291. assert(typeof Module['pthreadMainPrefixURL'] === 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
  292. assert(typeof Module['cdInitializerPrefixURL'] === 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
  293. assert(typeof Module['filePackagePrefixURL'] === 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
  294. assert(typeof Module['read'] === 'undefined', 'Module.read option was removed (modify read_ in JS)');
  295. assert(typeof Module['readAsync'] === 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
  296. assert(typeof Module['readBinary'] === 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
  297. assert(typeof Module['setWindowTitle'] === 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)');
  298. assert(typeof Module['TOTAL_MEMORY'] === 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
  299. if (!Object.getOwnPropertyDescriptor(Module, 'read')) {
  300. Object.defineProperty(Module, 'read', {
  301. configurable: true,
  302. get: function() {
  303. abort('Module.read has been replaced with plain read_ (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  304. }
  305. });
  306. }
  307. if (!Object.getOwnPropertyDescriptor(Module, 'readAsync')) {
  308. Object.defineProperty(Module, 'readAsync', {
  309. configurable: true,
  310. get: function() {
  311. abort('Module.readAsync has been replaced with plain readAsync (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  312. }
  313. });
  314. }
  315. if (!Object.getOwnPropertyDescriptor(Module, 'readBinary')) {
  316. Object.defineProperty(Module, 'readBinary', {
  317. configurable: true,
  318. get: function() {
  319. abort('Module.readBinary has been replaced with plain readBinary (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  320. }
  321. });
  322. }
  323. if (!Object.getOwnPropertyDescriptor(Module, 'setWindowTitle')) {
  324. Object.defineProperty(Module, 'setWindowTitle', {
  325. configurable: true,
  326. get: function() {
  327. abort('Module.setWindowTitle has been replaced with plain setWindowTitle (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  328. }
  329. });
  330. }
  331. var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
  332. var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
  333. var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
  334. var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
  335. assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add 'shell' to `-s ENVIRONMENT` to enable.");
  336. var STACK_ALIGN = 16;
  337. var POINTER_SIZE = 4;
  338. function getNativeTypeSize(type) {
  339. switch (type) {
  340. case 'i1': case 'i8': return 1;
  341. case 'i16': return 2;
  342. case 'i32': return 4;
  343. case 'i64': return 8;
  344. case 'float': return 4;
  345. case 'double': return 8;
  346. default: {
  347. if (type[type.length - 1] === '*') {
  348. return POINTER_SIZE;
  349. } else if (type[0] === 'i') {
  350. const bits = Number(type.substr(1));
  351. assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
  352. return bits / 8;
  353. } else {
  354. return 0;
  355. }
  356. }
  357. }
  358. }
  359. function warnOnce(text) {
  360. if (!warnOnce.shown) warnOnce.shown = {};
  361. if (!warnOnce.shown[text]) {
  362. warnOnce.shown[text] = 1;
  363. err(text);
  364. }
  365. }
  366. // include: runtime_functions.js
  367. // Wraps a JS function as a wasm function with a given signature.
  368. function convertJsFunctionToWasm(func, sig) {
  369. // If the type reflection proposal is available, use the new
  370. // "WebAssembly.Function" constructor.
  371. // Otherwise, construct a minimal wasm module importing the JS function and
  372. // re-exporting it.
  373. if (typeof WebAssembly.Function === "function") {
  374. var typeNames = {
  375. 'i': 'i32',
  376. 'j': 'i64',
  377. 'f': 'f32',
  378. 'd': 'f64'
  379. };
  380. var type = {
  381. parameters: [],
  382. results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
  383. };
  384. for (var i = 1; i < sig.length; ++i) {
  385. type.parameters.push(typeNames[sig[i]]);
  386. }
  387. return new WebAssembly.Function(type, func);
  388. }
  389. // The module is static, with the exception of the type section, which is
  390. // generated based on the signature passed in.
  391. var typeSection = [
  392. 0x01, // id: section,
  393. 0x00, // length: 0 (placeholder)
  394. 0x01, // count: 1
  395. 0x60, // form: func
  396. ];
  397. var sigRet = sig.slice(0, 1);
  398. var sigParam = sig.slice(1);
  399. var typeCodes = {
  400. 'i': 0x7f, // i32
  401. 'j': 0x7e, // i64
  402. 'f': 0x7d, // f32
  403. 'd': 0x7c, // f64
  404. };
  405. // Parameters, length + signatures
  406. typeSection.push(sigParam.length);
  407. for (var i = 0; i < sigParam.length; ++i) {
  408. typeSection.push(typeCodes[sigParam[i]]);
  409. }
  410. // Return values, length + signatures
  411. // With no multi-return in MVP, either 0 (void) or 1 (anything else)
  412. if (sigRet == 'v') {
  413. typeSection.push(0x00);
  414. } else {
  415. typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
  416. }
  417. // Write the overall length of the type section back into the section header
  418. // (excepting the 2 bytes for the section id and length)
  419. typeSection[1] = typeSection.length - 2;
  420. // Rest of the module is static
  421. var bytes = new Uint8Array([
  422. 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
  423. 0x01, 0x00, 0x00, 0x00, // version: 1
  424. ].concat(typeSection, [
  425. 0x02, 0x07, // import section
  426. // (import "e" "f" (func 0 (type 0)))
  427. 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
  428. 0x07, 0x05, // export section
  429. // (export "f" (func 0 (type 0)))
  430. 0x01, 0x01, 0x66, 0x00, 0x00,
  431. ]));
  432. // We can compile this wasm module synchronously because it is very small.
  433. // This accepts an import (at "e.f"), that it reroutes to an export (at "f")
  434. var module = new WebAssembly.Module(bytes);
  435. var instance = new WebAssembly.Instance(module, {
  436. 'e': {
  437. 'f': func
  438. }
  439. });
  440. var wrappedFunc = instance.exports['f'];
  441. return wrappedFunc;
  442. }
  443. var freeTableIndexes = [];
  444. // Weak map of functions in the table to their indexes, created on first use.
  445. var functionsInTableMap;
  446. function getEmptyTableSlot() {
  447. // Reuse a free index if there is one, otherwise grow.
  448. if (freeTableIndexes.length) {
  449. return freeTableIndexes.pop();
  450. }
  451. // Grow the table
  452. try {
  453. wasmTable.grow(1);
  454. } catch (err) {
  455. if (!(err instanceof RangeError)) {
  456. throw err;
  457. }
  458. throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
  459. }
  460. return wasmTable.length - 1;
  461. }
  462. function updateTableMap(offset, count) {
  463. for (var i = offset; i < offset + count; i++) {
  464. var item = getWasmTableEntry(i);
  465. // Ignore null values.
  466. if (item) {
  467. functionsInTableMap.set(item, i);
  468. }
  469. }
  470. }
  471. // Add a function to the table.
  472. // 'sig' parameter is required if the function being added is a JS function.
  473. function addFunction(func, sig) {
  474. assert(typeof func !== 'undefined');
  475. // Check if the function is already in the table, to ensure each function
  476. // gets a unique index. First, create the map if this is the first use.
  477. if (!functionsInTableMap) {
  478. functionsInTableMap = new WeakMap();
  479. updateTableMap(0, wasmTable.length);
  480. }
  481. if (functionsInTableMap.has(func)) {
  482. return functionsInTableMap.get(func);
  483. }
  484. // It's not in the table, add it now.
  485. var ret = getEmptyTableSlot();
  486. // Set the new value.
  487. try {
  488. // Attempting to call this with JS function will cause of table.set() to fail
  489. setWasmTableEntry(ret, func);
  490. } catch (err) {
  491. if (!(err instanceof TypeError)) {
  492. throw err;
  493. }
  494. assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction: ' + func);
  495. var wrapped = convertJsFunctionToWasm(func, sig);
  496. setWasmTableEntry(ret, wrapped);
  497. }
  498. functionsInTableMap.set(func, ret);
  499. return ret;
  500. }
  501. function removeFunction(index) {
  502. functionsInTableMap.delete(getWasmTableEntry(index));
  503. freeTableIndexes.push(index);
  504. }
  505. // end include: runtime_functions.js
  506. // include: runtime_debug.js
  507. // end include: runtime_debug.js
  508. var tempRet0 = 0;
  509. var setTempRet0 = (value) => { tempRet0 = value; };
  510. var getTempRet0 = () => tempRet0;
  511. // === Preamble library stuff ===
  512. // Documentation for the public APIs defined in this file must be updated in:
  513. // site/source/docs/api_reference/preamble.js.rst
  514. // A prebuilt local version of the documentation is available at:
  515. // site/build/text/docs/api_reference/preamble.js.txt
  516. // You can also build docs locally as HTML or other formats in site/
  517. // An online HTML version (which may be of a different version of Emscripten)
  518. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  519. var wasmBinary;
  520. if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
  521. if (!Object.getOwnPropertyDescriptor(Module, 'wasmBinary')) {
  522. Object.defineProperty(Module, 'wasmBinary', {
  523. configurable: true,
  524. get: function() {
  525. abort('Module.wasmBinary has been replaced with plain wasmBinary (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  526. }
  527. });
  528. }
  529. var noExitRuntime = Module['noExitRuntime'] || true;
  530. if (!Object.getOwnPropertyDescriptor(Module, 'noExitRuntime')) {
  531. Object.defineProperty(Module, 'noExitRuntime', {
  532. configurable: true,
  533. get: function() {
  534. abort('Module.noExitRuntime has been replaced with plain noExitRuntime (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  535. }
  536. });
  537. }
  538. if (typeof WebAssembly !== 'object') {
  539. abort('no native wasm support detected');
  540. }
  541. // include: runtime_safe_heap.js
  542. // In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
  543. // In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
  544. /** @param {number} ptr
  545. @param {number} value
  546. @param {string} type
  547. @param {number|boolean=} noSafe */
  548. function setValue(ptr, value, type = 'i8', noSafe) {
  549. if (type.charAt(type.length-1) === '*') type = 'i32';
  550. switch (type) {
  551. case 'i1': HEAP8[((ptr)>>0)] = value; break;
  552. case 'i8': HEAP8[((ptr)>>0)] = value; break;
  553. case 'i16': HEAP16[((ptr)>>1)] = value; break;
  554. case 'i32': HEAP32[((ptr)>>2)] = value; break;
  555. case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)] = tempI64[0],HEAP32[(((ptr)+(4))>>2)] = tempI64[1]); break;
  556. case 'float': HEAPF32[((ptr)>>2)] = value; break;
  557. case 'double': HEAPF64[((ptr)>>3)] = value; break;
  558. default: abort('invalid type for setValue: ' + type);
  559. }
  560. }
  561. /** @param {number} ptr
  562. @param {string} type
  563. @param {number|boolean=} noSafe */
  564. function getValue(ptr, type = 'i8', noSafe) {
  565. if (type.charAt(type.length-1) === '*') type = 'i32';
  566. switch (type) {
  567. case 'i1': return HEAP8[((ptr)>>0)];
  568. case 'i8': return HEAP8[((ptr)>>0)];
  569. case 'i16': return HEAP16[((ptr)>>1)];
  570. case 'i32': return HEAP32[((ptr)>>2)];
  571. case 'i64': return HEAP32[((ptr)>>2)];
  572. case 'float': return HEAPF32[((ptr)>>2)];
  573. case 'double': return Number(HEAPF64[((ptr)>>3)]);
  574. default: abort('invalid type for getValue: ' + type);
  575. }
  576. return null;
  577. }
  578. // end include: runtime_safe_heap.js
  579. // Wasm globals
  580. var wasmMemory;
  581. //========================================
  582. // Runtime essentials
  583. //========================================
  584. // whether we are quitting the application. no code should run after this.
  585. // set in exit() and abort()
  586. var ABORT = false;
  587. // set by exit() and abort(). Passed to 'onExit' handler.
  588. // NOTE: This is also used as the process return code code in shell environments
  589. // but only when noExitRuntime is false.
  590. var EXITSTATUS;
  591. /** @type {function(*, string=)} */
  592. function assert(condition, text) {
  593. if (!condition) {
  594. abort('Assertion failed' + (text ? ': ' + text : ''));
  595. }
  596. }
  597. // Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
  598. function getCFunc(ident) {
  599. var func = Module['_' + ident]; // closure exported function
  600. assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
  601. return func;
  602. }
  603. // C calling interface.
  604. /** @param {string|null=} returnType
  605. @param {Array=} argTypes
  606. @param {Arguments|Array=} args
  607. @param {Object=} opts */
  608. function ccall(ident, returnType, argTypes, args, opts) {
  609. // For fast lookup of conversion functions
  610. var toC = {
  611. 'string': function(str) {
  612. var ret = 0;
  613. if (str !== null && str !== undefined && str !== 0) { // null string
  614. // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
  615. var len = (str.length << 2) + 1;
  616. ret = stackAlloc(len);
  617. stringToUTF8(str, ret, len);
  618. }
  619. return ret;
  620. },
  621. 'array': function(arr) {
  622. var ret = stackAlloc(arr.length);
  623. writeArrayToMemory(arr, ret);
  624. return ret;
  625. }
  626. };
  627. function convertReturnValue(ret) {
  628. if (returnType === 'string') return UTF8ToString(ret);
  629. if (returnType === 'boolean') return Boolean(ret);
  630. return ret;
  631. }
  632. var func = getCFunc(ident);
  633. var cArgs = [];
  634. var stack = 0;
  635. assert(returnType !== 'array', 'Return type should not be "array".');
  636. if (args) {
  637. for (var i = 0; i < args.length; i++) {
  638. var converter = toC[argTypes[i]];
  639. if (converter) {
  640. if (stack === 0) stack = stackSave();
  641. cArgs[i] = converter(args[i]);
  642. } else {
  643. cArgs[i] = args[i];
  644. }
  645. }
  646. }
  647. var ret = func.apply(null, cArgs);
  648. function onDone(ret) {
  649. if (stack !== 0) stackRestore(stack);
  650. return convertReturnValue(ret);
  651. }
  652. ret = onDone(ret);
  653. return ret;
  654. }
  655. /** @param {string=} returnType
  656. @param {Array=} argTypes
  657. @param {Object=} opts */
  658. function cwrap(ident, returnType, argTypes, opts) {
  659. return function() {
  660. return ccall(ident, returnType, argTypes, arguments, opts);
  661. }
  662. }
  663. // We used to include malloc/free by default in the past. Show a helpful error in
  664. // builds with assertions.
  665. var ALLOC_NORMAL = 0; // Tries to use _malloc()
  666. var ALLOC_STACK = 1; // Lives for the duration of the current function call
  667. // allocate(): This is for internal use. You can use it yourself as well, but the interface
  668. // is a little tricky (see docs right below). The reason is that it is optimized
  669. // for multiple syntaxes to save space in generated code. So you should
  670. // normally not use allocate(), and instead allocate memory using _malloc(),
  671. // initialize it with setValue(), and so forth.
  672. // @slab: An array of data.
  673. // @allocator: How to allocate memory, see ALLOC_*
  674. /** @type {function((Uint8Array|Array<number>), number)} */
  675. function allocate(slab, allocator) {
  676. var ret;
  677. assert(typeof allocator === 'number', 'allocate no longer takes a type argument')
  678. assert(typeof slab !== 'number', 'allocate no longer takes a number as arg0')
  679. if (allocator == ALLOC_STACK) {
  680. ret = stackAlloc(slab.length);
  681. } else {
  682. ret = _malloc(slab.length);
  683. }
  684. if (slab.subarray || slab.slice) {
  685. HEAPU8.set(/** @type {!Uint8Array} */(slab), ret);
  686. } else {
  687. HEAPU8.set(new Uint8Array(slab), ret);
  688. }
  689. return ret;
  690. }
  691. // include: runtime_strings.js
  692. // runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime.
  693. // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
  694. // a copy of that string as a Javascript String object.
  695. var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
  696. /**
  697. * @param {number} idx
  698. * @param {number=} maxBytesToRead
  699. * @return {string}
  700. */
  701. function UTF8ArrayToString(heap, idx, maxBytesToRead) {
  702. var endIdx = idx + maxBytesToRead;
  703. var endPtr = idx;
  704. // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
  705. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
  706. // (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
  707. while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr;
  708. if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) {
  709. return UTF8Decoder.decode(heap.subarray(idx, endPtr));
  710. } else {
  711. var str = '';
  712. // If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
  713. while (idx < endPtr) {
  714. // For UTF8 byte structure, see:
  715. // http://en.wikipedia.org/wiki/UTF-8#Description
  716. // https://www.ietf.org/rfc/rfc2279.txt
  717. // https://tools.ietf.org/html/rfc3629
  718. var u0 = heap[idx++];
  719. if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
  720. var u1 = heap[idx++] & 63;
  721. if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
  722. var u2 = heap[idx++] & 63;
  723. if ((u0 & 0xF0) == 0xE0) {
  724. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  725. } else {
  726. if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');
  727. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63);
  728. }
  729. if (u0 < 0x10000) {
  730. str += String.fromCharCode(u0);
  731. } else {
  732. var ch = u0 - 0x10000;
  733. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  734. }
  735. }
  736. }
  737. return str;
  738. }
  739. // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
  740. // copy of that string as a Javascript String object.
  741. // maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
  742. // this parameter to scan the string until the first \0 byte. If maxBytesToRead is
  743. // passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
  744. // middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
  745. // not produce a string of exact length [ptr, ptr+maxBytesToRead[)
  746. // N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
  747. // throw JS JIT optimizations off, so it is worth to consider consistently using one
  748. // style or the other.
  749. /**
  750. * @param {number} ptr
  751. * @param {number=} maxBytesToRead
  752. * @return {string}
  753. */
  754. function UTF8ToString(ptr, maxBytesToRead) {
  755. ;
  756. return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
  757. }
  758. // Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
  759. // encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
  760. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
  761. // Parameters:
  762. // str: the Javascript string to copy.
  763. // heap: the array to copy to. Each index in this array is assumed to be one 8-byte element.
  764. // outIdx: The starting offset in the array to begin the copying.
  765. // maxBytesToWrite: The maximum number of bytes this function can write to the array.
  766. // This count should include the null terminator,
  767. // i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
  768. // maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
  769. // Returns the number of bytes written, EXCLUDING the null terminator.
  770. function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
  771. if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
  772. return 0;
  773. var startIdx = outIdx;
  774. var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
  775. for (var i = 0; i < str.length; ++i) {
  776. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
  777. // See http://unicode.org/faq/utf_bom.html#utf16-3
  778. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
  779. var u = str.charCodeAt(i); // possibly a lead surrogate
  780. if (u >= 0xD800 && u <= 0xDFFF) {
  781. var u1 = str.charCodeAt(++i);
  782. u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
  783. }
  784. if (u <= 0x7F) {
  785. if (outIdx >= endIdx) break;
  786. heap[outIdx++] = u;
  787. } else if (u <= 0x7FF) {
  788. if (outIdx + 1 >= endIdx) break;
  789. heap[outIdx++] = 0xC0 | (u >> 6);
  790. heap[outIdx++] = 0x80 | (u & 63);
  791. } else if (u <= 0xFFFF) {
  792. if (outIdx + 2 >= endIdx) break;
  793. heap[outIdx++] = 0xE0 | (u >> 12);
  794. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  795. heap[outIdx++] = 0x80 | (u & 63);
  796. } else {
  797. if (outIdx + 3 >= endIdx) break;
  798. if (u > 0x10FFFF) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).');
  799. heap[outIdx++] = 0xF0 | (u >> 18);
  800. heap[outIdx++] = 0x80 | ((u >> 12) & 63);
  801. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  802. heap[outIdx++] = 0x80 | (u & 63);
  803. }
  804. }
  805. // Null-terminate the pointer to the buffer.
  806. heap[outIdx] = 0;
  807. return outIdx - startIdx;
  808. }
  809. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  810. // null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
  811. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
  812. // Returns the number of bytes written, EXCLUDING the null terminator.
  813. function stringToUTF8(str, outPtr, maxBytesToWrite) {
  814. assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  815. return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
  816. }
  817. // Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
  818. function lengthBytesUTF8(str) {
  819. var len = 0;
  820. for (var i = 0; i < str.length; ++i) {
  821. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
  822. // See http://unicode.org/faq/utf_bom.html#utf16-3
  823. var u = str.charCodeAt(i); // possibly a lead surrogate
  824. if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
  825. if (u <= 0x7F) ++len;
  826. else if (u <= 0x7FF) len += 2;
  827. else if (u <= 0xFFFF) len += 3;
  828. else len += 4;
  829. }
  830. return len;
  831. }
  832. // end include: runtime_strings.js
  833. // include: runtime_strings_extra.js
  834. // runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime.
  835. // Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
  836. // a copy of that string as a Javascript String object.
  837. function AsciiToString(ptr) {
  838. var str = '';
  839. while (1) {
  840. var ch = HEAPU8[((ptr++)>>0)];
  841. if (!ch) return str;
  842. str += String.fromCharCode(ch);
  843. }
  844. }
  845. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  846. // null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
  847. function stringToAscii(str, outPtr) {
  848. return writeAsciiToMemory(str, outPtr, false);
  849. }
  850. // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
  851. // a copy of that string as a Javascript String object.
  852. var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
  853. function UTF16ToString(ptr, maxBytesToRead) {
  854. assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
  855. var endPtr = ptr;
  856. // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
  857. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
  858. var idx = endPtr >> 1;
  859. var maxIdx = idx + maxBytesToRead / 2;
  860. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  861. // will always evaluate to true. This saves on code size.
  862. while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
  863. endPtr = idx << 1;
  864. if (endPtr - ptr > 32 && UTF16Decoder) {
  865. return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
  866. } else {
  867. var str = '';
  868. // If maxBytesToRead is not passed explicitly, it will be undefined, and the for-loop's condition
  869. // will always evaluate to true. The loop is then terminated on the first null char.
  870. for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
  871. var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
  872. if (codeUnit == 0) break;
  873. // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
  874. str += String.fromCharCode(codeUnit);
  875. }
  876. return str;
  877. }
  878. }
  879. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  880. // null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
  881. // Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
  882. // Parameters:
  883. // str: the Javascript string to copy.
  884. // outPtr: Byte address in Emscripten HEAP where to write the string to.
  885. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
  886. // terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
  887. // maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
  888. // Returns the number of bytes written, EXCLUDING the null terminator.
  889. function stringToUTF16(str, outPtr, maxBytesToWrite) {
  890. assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
  891. assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  892. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  893. if (maxBytesToWrite === undefined) {
  894. maxBytesToWrite = 0x7FFFFFFF;
  895. }
  896. if (maxBytesToWrite < 2) return 0;
  897. maxBytesToWrite -= 2; // Null terminator.
  898. var startPtr = outPtr;
  899. var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
  900. for (var i = 0; i < numCharsToWrite; ++i) {
  901. // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
  902. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  903. HEAP16[((outPtr)>>1)] = codeUnit;
  904. outPtr += 2;
  905. }
  906. // Null-terminate the pointer to the HEAP.
  907. HEAP16[((outPtr)>>1)] = 0;
  908. return outPtr - startPtr;
  909. }
  910. // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
  911. function lengthBytesUTF16(str) {
  912. return str.length*2;
  913. }
  914. function UTF32ToString(ptr, maxBytesToRead) {
  915. assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
  916. var i = 0;
  917. var str = '';
  918. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  919. // will always evaluate to true. This saves on code size.
  920. while (!(i >= maxBytesToRead / 4)) {
  921. var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
  922. if (utf32 == 0) break;
  923. ++i;
  924. // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing.
  925. // See http://unicode.org/faq/utf_bom.html#utf16-3
  926. if (utf32 >= 0x10000) {
  927. var ch = utf32 - 0x10000;
  928. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  929. } else {
  930. str += String.fromCharCode(utf32);
  931. }
  932. }
  933. return str;
  934. }
  935. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  936. // null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
  937. // Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
  938. // Parameters:
  939. // str: the Javascript string to copy.
  940. // outPtr: Byte address in Emscripten HEAP where to write the string to.
  941. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
  942. // terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
  943. // maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
  944. // Returns the number of bytes written, EXCLUDING the null terminator.
  945. function stringToUTF32(str, outPtr, maxBytesToWrite) {
  946. assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
  947. assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  948. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  949. if (maxBytesToWrite === undefined) {
  950. maxBytesToWrite = 0x7FFFFFFF;
  951. }
  952. if (maxBytesToWrite < 4) return 0;
  953. var startPtr = outPtr;
  954. var endPtr = startPtr + maxBytesToWrite - 4;
  955. for (var i = 0; i < str.length; ++i) {
  956. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
  957. // See http://unicode.org/faq/utf_bom.html#utf16-3
  958. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  959. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
  960. var trailSurrogate = str.charCodeAt(++i);
  961. codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
  962. }
  963. HEAP32[((outPtr)>>2)] = codeUnit;
  964. outPtr += 4;
  965. if (outPtr + 4 > endPtr) break;
  966. }
  967. // Null-terminate the pointer to the HEAP.
  968. HEAP32[((outPtr)>>2)] = 0;
  969. return outPtr - startPtr;
  970. }
  971. // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
  972. function lengthBytesUTF32(str) {
  973. var len = 0;
  974. for (var i = 0; i < str.length; ++i) {
  975. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
  976. // See http://unicode.org/faq/utf_bom.html#utf16-3
  977. var codeUnit = str.charCodeAt(i);
  978. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
  979. len += 4;
  980. }
  981. return len;
  982. }
  983. // Allocate heap space for a JS string, and write it there.
  984. // It is the responsibility of the caller to free() that memory.
  985. function allocateUTF8(str) {
  986. var size = lengthBytesUTF8(str) + 1;
  987. var ret = _malloc(size);
  988. if (ret) stringToUTF8Array(str, HEAP8, ret, size);
  989. return ret;
  990. }
  991. // Allocate stack space for a JS string, and write it there.
  992. function allocateUTF8OnStack(str) {
  993. var size = lengthBytesUTF8(str) + 1;
  994. var ret = stackAlloc(size);
  995. stringToUTF8Array(str, HEAP8, ret, size);
  996. return ret;
  997. }
  998. // Deprecated: This function should not be called because it is unsafe and does not provide
  999. // a maximum length limit of how many bytes it is allowed to write. Prefer calling the
  1000. // function stringToUTF8Array() instead, which takes in a maximum length that can be used
  1001. // to be secure from out of bounds writes.
  1002. /** @deprecated
  1003. @param {boolean=} dontAddNull */
  1004. function writeStringToMemory(string, buffer, dontAddNull) {
  1005. warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
  1006. var /** @type {number} */ lastChar, /** @type {number} */ end;
  1007. if (dontAddNull) {
  1008. // stringToUTF8Array always appends null. If we don't want to do that, remember the
  1009. // character that existed at the location where the null will be placed, and restore
  1010. // that after the write (below).
  1011. end = buffer + lengthBytesUTF8(string);
  1012. lastChar = HEAP8[end];
  1013. }
  1014. stringToUTF8(string, buffer, Infinity);
  1015. if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
  1016. }
  1017. function writeArrayToMemory(array, buffer) {
  1018. assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')
  1019. HEAP8.set(array, buffer);
  1020. }
  1021. /** @param {boolean=} dontAddNull */
  1022. function writeAsciiToMemory(str, buffer, dontAddNull) {
  1023. for (var i = 0; i < str.length; ++i) {
  1024. assert(str.charCodeAt(i) === (str.charCodeAt(i) & 0xff));
  1025. HEAP8[((buffer++)>>0)] = str.charCodeAt(i);
  1026. }
  1027. // Null-terminate the pointer to the HEAP.
  1028. if (!dontAddNull) HEAP8[((buffer)>>0)] = 0;
  1029. }
  1030. // end include: runtime_strings_extra.js
  1031. // Memory management
  1032. function alignUp(x, multiple) {
  1033. if (x % multiple > 0) {
  1034. x += multiple - (x % multiple);
  1035. }
  1036. return x;
  1037. }
  1038. var HEAP,
  1039. /** @type {ArrayBuffer} */
  1040. buffer,
  1041. /** @type {Int8Array} */
  1042. HEAP8,
  1043. /** @type {Uint8Array} */
  1044. HEAPU8,
  1045. /** @type {Int16Array} */
  1046. HEAP16,
  1047. /** @type {Uint16Array} */
  1048. HEAPU16,
  1049. /** @type {Int32Array} */
  1050. HEAP32,
  1051. /** @type {Uint32Array} */
  1052. HEAPU32,
  1053. /** @type {Float32Array} */
  1054. HEAPF32,
  1055. /** @type {Float64Array} */
  1056. HEAPF64;
  1057. function updateGlobalBufferAndViews(buf) {
  1058. buffer = buf;
  1059. Module['HEAP8'] = HEAP8 = new Int8Array(buf);
  1060. Module['HEAP16'] = HEAP16 = new Int16Array(buf);
  1061. Module['HEAP32'] = HEAP32 = new Int32Array(buf);
  1062. Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf);
  1063. Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf);
  1064. Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf);
  1065. Module['HEAPF32'] = HEAPF32 = new Float32Array(buf);
  1066. Module['HEAPF64'] = HEAPF64 = new Float64Array(buf);
  1067. }
  1068. var TOTAL_STACK = 5242880;
  1069. if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime')
  1070. var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;
  1071. if (!Object.getOwnPropertyDescriptor(Module, 'INITIAL_MEMORY')) {
  1072. Object.defineProperty(Module, 'INITIAL_MEMORY', {
  1073. configurable: true,
  1074. get: function() {
  1075. abort('Module.INITIAL_MEMORY has been replaced with plain INITIAL_MEMORY (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)')
  1076. }
  1077. });
  1078. }
  1079. assert(INITIAL_MEMORY >= TOTAL_STACK, 'INITIAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
  1080. // check for full engine support (use string 'subarray' to avoid closure compiler confusion)
  1081. assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined,
  1082. 'JS engine does not provide full typed array support');
  1083. // If memory is defined in wasm, the user can't provide it.
  1084. assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -s IMPORTED_MEMORY to define wasmMemory externally');
  1085. assert(INITIAL_MEMORY == 16777216, 'Detected runtime INITIAL_MEMORY setting. Use -s IMPORTED_MEMORY to define wasmMemory dynamically');
  1086. // include: runtime_init_table.js
  1087. // In regular non-RELOCATABLE mode the table is exported
  1088. // from the wasm module and this will be assigned once
  1089. // the exports are available.
  1090. var wasmTable;
  1091. // end include: runtime_init_table.js
  1092. // include: runtime_stack_check.js
  1093. // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
  1094. function writeStackCookie() {
  1095. var max = _emscripten_stack_get_end();
  1096. assert((max & 3) == 0);
  1097. // The stack grows downwards
  1098. HEAP32[((max + 4)>>2)] = 0x2135467;
  1099. HEAP32[((max + 8)>>2)] = 0x89BACDFE;
  1100. // Also test the global address 0 for integrity.
  1101. HEAP32[0] = 0x63736d65; /* 'emsc' */
  1102. }
  1103. function checkStackCookie() {
  1104. if (ABORT) return;
  1105. var max = _emscripten_stack_get_end();
  1106. var cookie1 = HEAPU32[((max + 4)>>2)];
  1107. var cookie2 = HEAPU32[((max + 8)>>2)];
  1108. if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) {
  1109. abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x' + cookie2.toString(16) + ' 0x' + cookie1.toString(16));
  1110. }
  1111. // Also test the global address 0 for integrity.
  1112. if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
  1113. }
  1114. // end include: runtime_stack_check.js
  1115. // include: runtime_assertions.js
  1116. // Endianness check
  1117. (function() {
  1118. var h16 = new Int16Array(1);
  1119. var h8 = new Int8Array(h16.buffer);
  1120. h16[0] = 0x6373;
  1121. if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -s SUPPORT_BIG_ENDIAN=1 to bypass)';
  1122. })();
  1123. // end include: runtime_assertions.js
  1124. var __ATPRERUN__ = []; // functions called before the runtime is initialized
  1125. var __ATINIT__ = []; // functions called during startup
  1126. var __ATEXIT__ = []; // functions called during shutdown
  1127. var __ATPOSTRUN__ = []; // functions called after the main() is called
  1128. var runtimeInitialized = false;
  1129. var runtimeExited = false;
  1130. var runtimeKeepaliveCounter = 0;
  1131. function keepRuntimeAlive() {
  1132. return noExitRuntime || runtimeKeepaliveCounter > 0;
  1133. }
  1134. function preRun() {
  1135. if (Module['preRun']) {
  1136. if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  1137. while (Module['preRun'].length) {
  1138. addOnPreRun(Module['preRun'].shift());
  1139. }
  1140. }
  1141. callRuntimeCallbacks(__ATPRERUN__);
  1142. }
  1143. function initRuntime() {
  1144. checkStackCookie();
  1145. assert(!runtimeInitialized);
  1146. runtimeInitialized = true;
  1147. if (!Module["noFSInit"] && !FS.init.initialized)
  1148. FS.init();
  1149. FS.ignorePermissions = false;
  1150. TTY.init();
  1151. callRuntimeCallbacks(__ATINIT__);
  1152. }
  1153. function exitRuntime() {
  1154. checkStackCookie();
  1155. runtimeExited = true;
  1156. }
  1157. function postRun() {
  1158. checkStackCookie();
  1159. if (Module['postRun']) {
  1160. if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  1161. while (Module['postRun'].length) {
  1162. addOnPostRun(Module['postRun'].shift());
  1163. }
  1164. }
  1165. callRuntimeCallbacks(__ATPOSTRUN__);
  1166. }
  1167. function addOnPreRun(cb) {
  1168. __ATPRERUN__.unshift(cb);
  1169. }
  1170. function addOnInit(cb) {
  1171. __ATINIT__.unshift(cb);
  1172. }
  1173. function addOnExit(cb) {
  1174. }
  1175. function addOnPostRun(cb) {
  1176. __ATPOSTRUN__.unshift(cb);
  1177. }
  1178. // include: runtime_math.js
  1179. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  1180. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
  1181. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
  1182. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  1183. assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  1184. assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  1185. assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  1186. assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  1187. // end include: runtime_math.js
  1188. // A counter of dependencies for calling run(). If we need to
  1189. // do asynchronous work before running, increment this and
  1190. // decrement it. Incrementing must happen in a place like
  1191. // Module.preRun (used by emcc to add file preloading).
  1192. // Note that you can add dependencies in preRun, even though
  1193. // it happens right before run - run will be postponed until
  1194. // the dependencies are met.
  1195. var runDependencies = 0;
  1196. var runDependencyWatcher = null;
  1197. var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
  1198. var runDependencyTracking = {};
  1199. function getUniqueRunDependency(id) {
  1200. var orig = id;
  1201. while (1) {
  1202. if (!runDependencyTracking[id]) return id;
  1203. id = orig + Math.random();
  1204. }
  1205. }
  1206. function addRunDependency(id) {
  1207. runDependencies++;
  1208. if (Module['monitorRunDependencies']) {
  1209. Module['monitorRunDependencies'](runDependencies);
  1210. }
  1211. if (id) {
  1212. assert(!runDependencyTracking[id]);
  1213. runDependencyTracking[id] = 1;
  1214. if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
  1215. // Check for missing dependencies every few seconds
  1216. runDependencyWatcher = setInterval(function() {
  1217. if (ABORT) {
  1218. clearInterval(runDependencyWatcher);
  1219. runDependencyWatcher = null;
  1220. return;
  1221. }
  1222. var shown = false;
  1223. for (var dep in runDependencyTracking) {
  1224. if (!shown) {
  1225. shown = true;
  1226. err('still waiting on run dependencies:');
  1227. }
  1228. err('dependency: ' + dep);
  1229. }
  1230. if (shown) {
  1231. err('(end of list)');
  1232. }
  1233. }, 10000);
  1234. }
  1235. } else {
  1236. err('warning: run dependency added without ID');
  1237. }
  1238. }
  1239. function removeRunDependency(id) {
  1240. runDependencies--;
  1241. if (Module['monitorRunDependencies']) {
  1242. Module['monitorRunDependencies'](runDependencies);
  1243. }
  1244. if (id) {
  1245. assert(runDependencyTracking[id]);
  1246. delete runDependencyTracking[id];
  1247. } else {
  1248. err('warning: run dependency removed without ID');
  1249. }
  1250. if (runDependencies == 0) {
  1251. if (runDependencyWatcher !== null) {
  1252. clearInterval(runDependencyWatcher);
  1253. runDependencyWatcher = null;
  1254. }
  1255. if (dependenciesFulfilled) {
  1256. var callback = dependenciesFulfilled;
  1257. dependenciesFulfilled = null;
  1258. callback(); // can add another dependenciesFulfilled
  1259. }
  1260. }
  1261. }
  1262. Module["preloadedImages"] = {}; // maps url to image data
  1263. Module["preloadedAudios"] = {}; // maps url to audio data
  1264. /** @param {string|number=} what */
  1265. function abort(what) {
  1266. {
  1267. if (Module['onAbort']) {
  1268. Module['onAbort'](what);
  1269. }
  1270. }
  1271. what = 'Aborted(' + what + ')';
  1272. // TODO(sbc): Should we remove printing and leave it up to whoever
  1273. // catches the exception?
  1274. err(what);
  1275. ABORT = true;
  1276. EXITSTATUS = 1;
  1277. // Use a wasm runtime error, because a JS error might be seen as a foreign
  1278. // exception, which means we'd run destructors on it. We need the error to
  1279. // simply make the program stop.
  1280. var e = new WebAssembly.RuntimeError(what);
  1281. // Throw the error whether or not MODULARIZE is set because abort is used
  1282. // in code paths apart from instantiation where an exception is expected
  1283. // to be thrown when abort is called.
  1284. throw e;
  1285. }
  1286. // {{MEM_INITIALIZER}}
  1287. // include: memoryprofiler.js
  1288. // end include: memoryprofiler.js
  1289. // include: URIUtils.js
  1290. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  1291. var dataURIPrefix = 'data:application/octet-stream;base64,';
  1292. // Indicates whether filename is a base64 data URI.
  1293. function isDataURI(filename) {
  1294. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  1295. return filename.startsWith(dataURIPrefix);
  1296. }
  1297. // Indicates whether filename is delivered via file protocol (as opposed to http/https)
  1298. function isFileURI(filename) {
  1299. return filename.startsWith('file://');
  1300. }
  1301. // end include: URIUtils.js
  1302. function createExportWrapper(name, fixedasm) {
  1303. return function() {
  1304. var displayName = name;
  1305. var asm = fixedasm;
  1306. if (!fixedasm) {
  1307. asm = Module['asm'];
  1308. }
  1309. assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization');
  1310. assert(!runtimeExited, 'native function `' + displayName + '` called after runtime exit (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
  1311. if (!asm[name]) {
  1312. assert(asm[name], 'exported native function `' + displayName + '` not found');
  1313. }
  1314. return asm[name].apply(null, arguments);
  1315. };
  1316. }
  1317. var wasmBinaryFile;
  1318. wasmBinaryFile = 'libopus.wasm?v=be6f45f8';
  1319. if (!isDataURI(wasmBinaryFile)) {
  1320. wasmBinaryFile = locateFile(wasmBinaryFile);
  1321. }
  1322. function getBinary(file) {
  1323. try {
  1324. if (file == wasmBinaryFile && wasmBinary) {
  1325. return new Uint8Array(wasmBinary);
  1326. }
  1327. if (readBinary) {
  1328. return readBinary(file);
  1329. } else {
  1330. throw "both async and sync fetching of the wasm failed";
  1331. }
  1332. }
  1333. catch (err) {
  1334. abort(err);
  1335. }
  1336. }
  1337. function getBinaryPromise() {
  1338. // If we don't have the binary yet, try to to load it asynchronously.
  1339. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
  1340. // See https://github.com/github/fetch/pull/92#issuecomment-140665932
  1341. // Cordova or Electron apps are typically loaded from a file:// url.
  1342. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR.
  1343. if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
  1344. if (typeof fetch === 'function'
  1345. && !isFileURI(wasmBinaryFile)
  1346. ) {
  1347. return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
  1348. if (!response['ok']) {
  1349. throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
  1350. }
  1351. return response['arrayBuffer']();
  1352. }).catch(function () {
  1353. return getBinary(wasmBinaryFile);
  1354. });
  1355. }
  1356. else {
  1357. if (readAsync) {
  1358. // fetch is not available or url is file => try XHR (readAsync uses XHR internally)
  1359. return new Promise(function(resolve, reject) {
  1360. readAsync(wasmBinaryFile, function(response) { resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))) }, reject)
  1361. });
  1362. }
  1363. }
  1364. }
  1365. // Otherwise, getBinary should be able to get it synchronously
  1366. return Promise.resolve().then(function() { return getBinary(wasmBinaryFile); });
  1367. }
  1368. // Create the wasm instance.
  1369. // Receives the wasm imports, returns the exports.
  1370. function createWasm() {
  1371. // prepare imports
  1372. var info = {
  1373. 'env': asmLibraryArg,
  1374. 'wasi_snapshot_preview1': asmLibraryArg,
  1375. };
  1376. // Load the wasm module and create an instance of using native support in the JS engine.
  1377. // handle a generated wasm instance, receiving its exports and
  1378. // performing other necessary setup
  1379. /** @param {WebAssembly.Module=} module*/
  1380. function receiveInstance(instance, module) {
  1381. var exports = instance.exports;
  1382. Module['asm'] = exports;
  1383. wasmMemory = Module['asm']['memory'];
  1384. assert(wasmMemory, "memory not found in wasm exports");
  1385. // This assertion doesn't hold when emscripten is run in --post-link
  1386. // mode.
  1387. // TODO(sbc): Read INITIAL_MEMORY out of the wasm file in post-link mode.
  1388. //assert(wasmMemory.buffer.byteLength === 16777216);
  1389. updateGlobalBufferAndViews(wasmMemory.buffer);
  1390. wasmTable = Module['asm']['__indirect_function_table'];
  1391. assert(wasmTable, "table not found in wasm exports");
  1392. addOnInit(Module['asm']['__wasm_call_ctors']);
  1393. removeRunDependency('wasm-instantiate');
  1394. }
  1395. // we can't run yet (except in a pthread, where we have a custom sync instantiator)
  1396. addRunDependency('wasm-instantiate');
  1397. // Prefer streaming instantiation if available.
  1398. // Async compilation can be confusing when an error on the page overwrites Module
  1399. // (for example, if the order of elements is wrong, and the one defining Module is
  1400. // later), so we save Module and check it later.
  1401. var trueModule = Module;
  1402. function receiveInstantiationResult(result) {
  1403. // 'result' is a ResultObject object which has both the module and instance.
  1404. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  1405. assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
  1406. trueModule = null;
  1407. // 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.
  1408. // When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
  1409. receiveInstance(result['instance']);
  1410. }
  1411. function instantiateArrayBuffer(receiver) {
  1412. return getBinaryPromise().then(function(binary) {
  1413. return WebAssembly.instantiate(binary, info);
  1414. }).then(function (instance) {
  1415. return instance;
  1416. }).then(receiver, function(reason) {
  1417. err('failed to asynchronously prepare wasm: ' + reason);
  1418. // Warn on some common problems.
  1419. if (isFileURI(wasmBinaryFile)) {
  1420. err('warning: Loading from a file URI (' + wasmBinaryFile + ') is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing');
  1421. }
  1422. abort(reason);
  1423. });
  1424. }
  1425. function instantiateAsync() {
  1426. if (!wasmBinary &&
  1427. typeof WebAssembly.instantiateStreaming === 'function' &&
  1428. !isDataURI(wasmBinaryFile) &&
  1429. // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
  1430. !isFileURI(wasmBinaryFile) &&
  1431. typeof fetch === 'function') {
  1432. return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
  1433. var result = WebAssembly.instantiateStreaming(response, info);
  1434. return result.then(
  1435. receiveInstantiationResult,
  1436. function(reason) {
  1437. // We expect the most common failure cause to be a bad MIME type for the binary,
  1438. // in which case falling back to ArrayBuffer instantiation should work.
  1439. err('wasm streaming compile failed: ' + reason);
  1440. err('falling back to ArrayBuffer instantiation');
  1441. return instantiateArrayBuffer(receiveInstantiationResult);
  1442. });
  1443. });
  1444. } else {
  1445. return instantiateArrayBuffer(receiveInstantiationResult);
  1446. }
  1447. }
  1448. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  1449. // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
  1450. // to any other async startup actions they are performing.
  1451. if (Module['instantiateWasm']) {
  1452. try {
  1453. var exports = Module['instantiateWasm'](info, receiveInstance);
  1454. return exports;
  1455. } catch(e) {
  1456. err('Module.instantiateWasm callback failed with error: ' + e);
  1457. return false;
  1458. }
  1459. }
  1460. instantiateAsync();
  1461. return {}; // no exports yet; we'll fill them in later
  1462. }
  1463. // Globals used by JS i64 conversions (see makeSetValue)
  1464. var tempDouble;
  1465. var tempI64;
  1466. // === Body ===
  1467. var ASM_CONSTS = {
  1468. };
  1469. function callRuntimeCallbacks(callbacks) {
  1470. while (callbacks.length > 0) {
  1471. var callback = callbacks.shift();
  1472. if (typeof callback == 'function') {
  1473. callback(Module); // Pass the module as the first argument.
  1474. continue;
  1475. }
  1476. var func = callback.func;
  1477. if (typeof func === 'number') {
  1478. if (callback.arg === undefined) {
  1479. getWasmTableEntry(func)();
  1480. } else {
  1481. getWasmTableEntry(func)(callback.arg);
  1482. }
  1483. } else {
  1484. func(callback.arg === undefined ? null : callback.arg);
  1485. }
  1486. }
  1487. }
  1488. function withStackSave(f) {
  1489. var stack = stackSave();
  1490. var ret = f();
  1491. stackRestore(stack);
  1492. return ret;
  1493. }
  1494. function demangle(func) {
  1495. warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
  1496. return func;
  1497. }
  1498. function demangleAll(text) {
  1499. var regex =
  1500. /\b_Z[\w\d_]+/g;
  1501. return text.replace(regex,
  1502. function(x) {
  1503. var y = demangle(x);
  1504. return x === y ? x : (y + ' [' + x + ']');
  1505. });
  1506. }
  1507. var wasmTableMirror = [];
  1508. function getWasmTableEntry(funcPtr) {
  1509. var func = wasmTableMirror[funcPtr];
  1510. if (!func) {
  1511. if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
  1512. wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
  1513. }
  1514. assert(wasmTable.get(funcPtr) == func, "JavaScript-side Wasm function table mirror is out of date!");
  1515. return func;
  1516. }
  1517. function handleException(e) {
  1518. // Certain exception types we do not treat as errors since they are used for
  1519. // internal control flow.
  1520. // 1. ExitStatus, which is thrown by exit()
  1521. // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others
  1522. // that wish to return to JS event loop.
  1523. if (e instanceof ExitStatus || e == 'unwind') {
  1524. return EXITSTATUS;
  1525. }
  1526. quit_(1, e);
  1527. }
  1528. function jsStackTrace() {
  1529. var error = new Error();
  1530. if (!error.stack) {
  1531. // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
  1532. // so try that as a special-case.
  1533. try {
  1534. throw new Error();
  1535. } catch(e) {
  1536. error = e;
  1537. }
  1538. if (!error.stack) {
  1539. return '(no stack trace available)';
  1540. }
  1541. }
  1542. return error.stack.toString();
  1543. }
  1544. function setWasmTableEntry(idx, func) {
  1545. wasmTable.set(idx, func);
  1546. wasmTableMirror[idx] = func;
  1547. }
  1548. function stackTrace() {
  1549. var js = jsStackTrace();
  1550. if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
  1551. return demangleAll(js);
  1552. }
  1553. function ___cxa_allocate_exception(size) {
  1554. // Thrown object is prepended by exception metadata block
  1555. return _malloc(size + 16) + 16;
  1556. }
  1557. function ExceptionInfo(excPtr) {
  1558. this.excPtr = excPtr;
  1559. this.ptr = excPtr - 16;
  1560. this.set_type = function(type) {
  1561. HEAP32[(((this.ptr)+(4))>>2)] = type;
  1562. };
  1563. this.get_type = function() {
  1564. return HEAP32[(((this.ptr)+(4))>>2)];
  1565. };
  1566. this.set_destructor = function(destructor) {
  1567. HEAP32[(((this.ptr)+(8))>>2)] = destructor;
  1568. };
  1569. this.get_destructor = function() {
  1570. return HEAP32[(((this.ptr)+(8))>>2)];
  1571. };
  1572. this.set_refcount = function(refcount) {
  1573. HEAP32[((this.ptr)>>2)] = refcount;
  1574. };
  1575. this.set_caught = function (caught) {
  1576. caught = caught ? 1 : 0;
  1577. HEAP8[(((this.ptr)+(12))>>0)] = caught;
  1578. };
  1579. this.get_caught = function () {
  1580. return HEAP8[(((this.ptr)+(12))>>0)] != 0;
  1581. };
  1582. this.set_rethrown = function (rethrown) {
  1583. rethrown = rethrown ? 1 : 0;
  1584. HEAP8[(((this.ptr)+(13))>>0)] = rethrown;
  1585. };
  1586. this.get_rethrown = function () {
  1587. return HEAP8[(((this.ptr)+(13))>>0)] != 0;
  1588. };
  1589. // Initialize native structure fields. Should be called once after allocated.
  1590. this.init = function(type, destructor) {
  1591. this.set_type(type);
  1592. this.set_destructor(destructor);
  1593. this.set_refcount(0);
  1594. this.set_caught(false);
  1595. this.set_rethrown(false);
  1596. }
  1597. this.add_ref = function() {
  1598. var value = HEAP32[((this.ptr)>>2)];
  1599. HEAP32[((this.ptr)>>2)] = value + 1;
  1600. };
  1601. // Returns true if last reference released.
  1602. this.release_ref = function() {
  1603. var prev = HEAP32[((this.ptr)>>2)];
  1604. HEAP32[((this.ptr)>>2)] = prev - 1;
  1605. assert(prev > 0);
  1606. return prev === 1;
  1607. };
  1608. }
  1609. var exceptionLast = 0;
  1610. var uncaughtExceptionCount = 0;
  1611. function ___cxa_throw(ptr, type, destructor) {
  1612. var info = new ExceptionInfo(ptr);
  1613. // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.
  1614. info.init(type, destructor);
  1615. exceptionLast = ptr;
  1616. uncaughtExceptionCount++;
  1617. throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -s NO_DISABLE_EXCEPTION_CATCHING or -s EXCEPTION_CATCHING_ALLOWED=[..] to catch.";
  1618. }
  1619. function _abort() {
  1620. abort('native code called abort()');
  1621. }
  1622. function _emscripten_memcpy_big(dest, src, num) {
  1623. HEAPU8.copyWithin(dest, src, src + num);
  1624. }
  1625. function abortOnCannotGrowMemory(requestedSize) {
  1626. abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s INITIAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
  1627. }
  1628. function _emscripten_resize_heap(requestedSize) {
  1629. var oldSize = HEAPU8.length;
  1630. requestedSize = requestedSize >>> 0;
  1631. abortOnCannotGrowMemory(requestedSize);
  1632. }
  1633. var ENV = {};
  1634. function getExecutableName() {
  1635. return thisProgram || './this.program';
  1636. }
  1637. function getEnvStrings() {
  1638. if (!getEnvStrings.strings) {
  1639. // Default values.
  1640. // Browser language detection #8751
  1641. var lang = ((typeof navigator === 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8';
  1642. var env = {
  1643. 'USER': 'web_user',
  1644. 'LOGNAME': 'web_user',
  1645. 'PATH': '/',
  1646. 'PWD': '/',
  1647. 'HOME': '/home/web_user',
  1648. 'LANG': lang,
  1649. '_': getExecutableName()
  1650. };
  1651. // Apply the user-provided values, if any.
  1652. for (var x in ENV) {
  1653. // x is a key in ENV; if ENV[x] is undefined, that means it was
  1654. // explicitly set to be so. We allow user code to do that to
  1655. // force variables with default values to remain unset.
  1656. if (ENV[x] === undefined) delete env[x];
  1657. else env[x] = ENV[x];
  1658. }
  1659. var strings = [];
  1660. for (var x in env) {
  1661. strings.push(x + '=' + env[x]);
  1662. }
  1663. getEnvStrings.strings = strings;
  1664. }
  1665. return getEnvStrings.strings;
  1666. }
  1667. var PATH = {splitPath:function(filename) {
  1668. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  1669. return splitPathRe.exec(filename).slice(1);
  1670. },normalizeArray:function(parts, allowAboveRoot) {
  1671. // if the path tries to go above the root, `up` ends up > 0
  1672. var up = 0;
  1673. for (var i = parts.length - 1; i >= 0; i--) {
  1674. var last = parts[i];
  1675. if (last === '.') {
  1676. parts.splice(i, 1);
  1677. } else if (last === '..') {
  1678. parts.splice(i, 1);
  1679. up++;
  1680. } else if (up) {
  1681. parts.splice(i, 1);
  1682. up--;
  1683. }
  1684. }
  1685. // if the path is allowed to go above the root, restore leading ..s
  1686. if (allowAboveRoot) {
  1687. for (; up; up--) {
  1688. parts.unshift('..');
  1689. }
  1690. }
  1691. return parts;
  1692. },normalize:function(path) {
  1693. var isAbsolute = path.charAt(0) === '/',
  1694. trailingSlash = path.substr(-1) === '/';
  1695. // Normalize the path
  1696. path = PATH.normalizeArray(path.split('/').filter(function(p) {
  1697. return !!p;
  1698. }), !isAbsolute).join('/');
  1699. if (!path && !isAbsolute) {
  1700. path = '.';
  1701. }
  1702. if (path && trailingSlash) {
  1703. path += '/';
  1704. }
  1705. return (isAbsolute ? '/' : '') + path;
  1706. },dirname:function(path) {
  1707. var result = PATH.splitPath(path),
  1708. root = result[0],
  1709. dir = result[1];
  1710. if (!root && !dir) {
  1711. // No dirname whatsoever
  1712. return '.';
  1713. }
  1714. if (dir) {
  1715. // It has a dirname, strip trailing slash
  1716. dir = dir.substr(0, dir.length - 1);
  1717. }
  1718. return root + dir;
  1719. },basename:function(path) {
  1720. // EMSCRIPTEN return '/'' for '/', not an empty string
  1721. if (path === '/') return '/';
  1722. path = PATH.normalize(path);
  1723. path = path.replace(/\/$/, "");
  1724. var lastSlash = path.lastIndexOf('/');
  1725. if (lastSlash === -1) return path;
  1726. return path.substr(lastSlash+1);
  1727. },extname:function(path) {
  1728. return PATH.splitPath(path)[3];
  1729. },join:function() {
  1730. var paths = Array.prototype.slice.call(arguments, 0);
  1731. return PATH.normalize(paths.join('/'));
  1732. },join2:function(l, r) {
  1733. return PATH.normalize(l + '/' + r);
  1734. }};
  1735. function getRandomDevice() {
  1736. if (typeof crypto === 'object' && typeof crypto['getRandomValues'] === 'function') {
  1737. // for modern web browsers
  1738. var randomBuffer = new Uint8Array(1);
  1739. return function() { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
  1740. } else
  1741. if (ENVIRONMENT_IS_NODE) {
  1742. // for nodejs with or without crypto support included
  1743. try {
  1744. var crypto_module = require('crypto');
  1745. // nodejs has crypto support
  1746. return function() { return crypto_module['randomBytes'](1)[0]; };
  1747. } catch (e) {
  1748. // nodejs doesn't have crypto support
  1749. }
  1750. }
  1751. // we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096
  1752. return function() { abort("no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: function(array) { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"); };
  1753. }
  1754. var PATH_FS = {resolve:function() {
  1755. var resolvedPath = '',
  1756. resolvedAbsolute = false;
  1757. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1758. var path = (i >= 0) ? arguments[i] : FS.cwd();
  1759. // Skip empty and invalid entries
  1760. if (typeof path !== 'string') {
  1761. throw new TypeError('Arguments to path.resolve must be strings');
  1762. } else if (!path) {
  1763. return ''; // an invalid portion invalidates the whole thing
  1764. }
  1765. resolvedPath = path + '/' + resolvedPath;
  1766. resolvedAbsolute = path.charAt(0) === '/';
  1767. }
  1768. // At this point the path should be resolved to a full absolute path, but
  1769. // handle relative paths to be safe (might happen when process.cwd() fails)
  1770. resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
  1771. return !!p;
  1772. }), !resolvedAbsolute).join('/');
  1773. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1774. },relative:function(from, to) {
  1775. from = PATH_FS.resolve(from).substr(1);
  1776. to = PATH_FS.resolve(to).substr(1);
  1777. function trim(arr) {
  1778. var start = 0;
  1779. for (; start < arr.length; start++) {
  1780. if (arr[start] !== '') break;
  1781. }
  1782. var end = arr.length - 1;
  1783. for (; end >= 0; end--) {
  1784. if (arr[end] !== '') break;
  1785. }
  1786. if (start > end) return [];
  1787. return arr.slice(start, end - start + 1);
  1788. }
  1789. var fromParts = trim(from.split('/'));
  1790. var toParts = trim(to.split('/'));
  1791. var length = Math.min(fromParts.length, toParts.length);
  1792. var samePartsLength = length;
  1793. for (var i = 0; i < length; i++) {
  1794. if (fromParts[i] !== toParts[i]) {
  1795. samePartsLength = i;
  1796. break;
  1797. }
  1798. }
  1799. var outputParts = [];
  1800. for (var i = samePartsLength; i < fromParts.length; i++) {
  1801. outputParts.push('..');
  1802. }
  1803. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1804. return outputParts.join('/');
  1805. }};
  1806. var TTY = {ttys:[],init:function () {
  1807. // https://github.com/emscripten-core/emscripten/pull/1555
  1808. // if (ENVIRONMENT_IS_NODE) {
  1809. // // currently, FS.init does not distinguish if process.stdin is a file or TTY
  1810. // // device, it always assumes it's a TTY device. because of this, we're forcing
  1811. // // process.stdin to UTF8 encoding to at least make stdin reading compatible
  1812. // // with text files until FS.init can be refactored.
  1813. // process['stdin']['setEncoding']('utf8');
  1814. // }
  1815. },shutdown:function() {
  1816. // https://github.com/emscripten-core/emscripten/pull/1555
  1817. // if (ENVIRONMENT_IS_NODE) {
  1818. // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
  1819. // // 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
  1820. // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
  1821. // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
  1822. // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
  1823. // process['stdin']['pause']();
  1824. // }
  1825. },register:function(dev, ops) {
  1826. TTY.ttys[dev] = { input: [], output: [], ops: ops };
  1827. FS.registerDevice(dev, TTY.stream_ops);
  1828. },stream_ops:{open:function(stream) {
  1829. var tty = TTY.ttys[stream.node.rdev];
  1830. if (!tty) {
  1831. throw new FS.ErrnoError(43);
  1832. }
  1833. stream.tty = tty;
  1834. stream.seekable = false;
  1835. },close:function(stream) {
  1836. // flush any pending line data
  1837. stream.tty.ops.flush(stream.tty);
  1838. },flush:function(stream) {
  1839. stream.tty.ops.flush(stream.tty);
  1840. },read:function(stream, buffer, offset, length, pos /* ignored */) {
  1841. if (!stream.tty || !stream.tty.ops.get_char) {
  1842. throw new FS.ErrnoError(60);
  1843. }
  1844. var bytesRead = 0;
  1845. for (var i = 0; i < length; i++) {
  1846. var result;
  1847. try {
  1848. result = stream.tty.ops.get_char(stream.tty);
  1849. } catch (e) {
  1850. throw new FS.ErrnoError(29);
  1851. }
  1852. if (result === undefined && bytesRead === 0) {
  1853. throw new FS.ErrnoError(6);
  1854. }
  1855. if (result === null || result === undefined) break;
  1856. bytesRead++;
  1857. buffer[offset+i] = result;
  1858. }
  1859. if (bytesRead) {
  1860. stream.node.timestamp = Date.now();
  1861. }
  1862. return bytesRead;
  1863. },write:function(stream, buffer, offset, length, pos) {
  1864. if (!stream.tty || !stream.tty.ops.put_char) {
  1865. throw new FS.ErrnoError(60);
  1866. }
  1867. try {
  1868. for (var i = 0; i < length; i++) {
  1869. stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
  1870. }
  1871. } catch (e) {
  1872. throw new FS.ErrnoError(29);
  1873. }
  1874. if (length) {
  1875. stream.node.timestamp = Date.now();
  1876. }
  1877. return i;
  1878. }},default_tty_ops:{get_char:function(tty) {
  1879. if (!tty.input.length) {
  1880. var result = null;
  1881. if (ENVIRONMENT_IS_NODE) {
  1882. // we will read data by chunks of BUFSIZE
  1883. var BUFSIZE = 256;
  1884. var buf = Buffer.alloc(BUFSIZE);
  1885. var bytesRead = 0;
  1886. try {
  1887. bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE, null);
  1888. } catch(e) {
  1889. // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
  1890. // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
  1891. if (e.toString().includes('EOF')) bytesRead = 0;
  1892. else throw e;
  1893. }
  1894. if (bytesRead > 0) {
  1895. result = buf.slice(0, bytesRead).toString('utf-8');
  1896. } else {
  1897. result = null;
  1898. }
  1899. } else
  1900. if (typeof window != 'undefined' &&
  1901. typeof window.prompt == 'function') {
  1902. // Browser.
  1903. result = window.prompt('Input: '); // returns null on cancel
  1904. if (result !== null) {
  1905. result += '\n';
  1906. }
  1907. } else if (typeof readline == 'function') {
  1908. // Command line.
  1909. result = readline();
  1910. if (result !== null) {
  1911. result += '\n';
  1912. }
  1913. }
  1914. if (!result) {
  1915. return null;
  1916. }
  1917. tty.input = intArrayFromString(result, true);
  1918. }
  1919. return tty.input.shift();
  1920. },put_char:function(tty, val) {
  1921. if (val === null || val === 10) {
  1922. out(UTF8ArrayToString(tty.output, 0));
  1923. tty.output = [];
  1924. } else {
  1925. if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
  1926. }
  1927. },flush:function(tty) {
  1928. if (tty.output && tty.output.length > 0) {
  1929. out(UTF8ArrayToString(tty.output, 0));
  1930. tty.output = [];
  1931. }
  1932. }},default_tty1_ops:{put_char:function(tty, val) {
  1933. if (val === null || val === 10) {
  1934. err(UTF8ArrayToString(tty.output, 0));
  1935. tty.output = [];
  1936. } else {
  1937. if (val != 0) tty.output.push(val);
  1938. }
  1939. },flush:function(tty) {
  1940. if (tty.output && tty.output.length > 0) {
  1941. err(UTF8ArrayToString(tty.output, 0));
  1942. tty.output = [];
  1943. }
  1944. }}};
  1945. function zeroMemory(address, size) {
  1946. HEAPU8.fill(0, address, address + size);
  1947. }
  1948. function alignMemory(size, alignment) {
  1949. assert(alignment, "alignment argument is required");
  1950. return Math.ceil(size / alignment) * alignment;
  1951. }
  1952. function mmapAlloc(size) {
  1953. abort('internal error: mmapAlloc called but `memalign` native symbol not exported');
  1954. }
  1955. var MEMFS = {ops_table:null,mount:function(mount) {
  1956. return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  1957. },createNode:function(parent, name, mode, dev) {
  1958. if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
  1959. // no supported
  1960. throw new FS.ErrnoError(63);
  1961. }
  1962. if (!MEMFS.ops_table) {
  1963. MEMFS.ops_table = {
  1964. dir: {
  1965. node: {
  1966. getattr: MEMFS.node_ops.getattr,
  1967. setattr: MEMFS.node_ops.setattr,
  1968. lookup: MEMFS.node_ops.lookup,
  1969. mknod: MEMFS.node_ops.mknod,
  1970. rename: MEMFS.node_ops.rename,
  1971. unlink: MEMFS.node_ops.unlink,
  1972. rmdir: MEMFS.node_ops.rmdir,
  1973. readdir: MEMFS.node_ops.readdir,
  1974. symlink: MEMFS.node_ops.symlink
  1975. },
  1976. stream: {
  1977. llseek: MEMFS.stream_ops.llseek
  1978. }
  1979. },
  1980. file: {
  1981. node: {
  1982. getattr: MEMFS.node_ops.getattr,
  1983. setattr: MEMFS.node_ops.setattr
  1984. },
  1985. stream: {
  1986. llseek: MEMFS.stream_ops.llseek,
  1987. read: MEMFS.stream_ops.read,
  1988. write: MEMFS.stream_ops.write,
  1989. allocate: MEMFS.stream_ops.allocate,
  1990. mmap: MEMFS.stream_ops.mmap,
  1991. msync: MEMFS.stream_ops.msync
  1992. }
  1993. },
  1994. link: {
  1995. node: {
  1996. getattr: MEMFS.node_ops.getattr,
  1997. setattr: MEMFS.node_ops.setattr,
  1998. readlink: MEMFS.node_ops.readlink
  1999. },
  2000. stream: {}
  2001. },
  2002. chrdev: {
  2003. node: {
  2004. getattr: MEMFS.node_ops.getattr,
  2005. setattr: MEMFS.node_ops.setattr
  2006. },
  2007. stream: FS.chrdev_stream_ops
  2008. }
  2009. };
  2010. }
  2011. var node = FS.createNode(parent, name, mode, dev);
  2012. if (FS.isDir(node.mode)) {
  2013. node.node_ops = MEMFS.ops_table.dir.node;
  2014. node.stream_ops = MEMFS.ops_table.dir.stream;
  2015. node.contents = {};
  2016. } else if (FS.isFile(node.mode)) {
  2017. node.node_ops = MEMFS.ops_table.file.node;
  2018. node.stream_ops = MEMFS.ops_table.file.stream;
  2019. node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
  2020. // 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
  2021. // for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
  2022. // penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
  2023. node.contents = null;
  2024. } else if (FS.isLink(node.mode)) {
  2025. node.node_ops = MEMFS.ops_table.link.node;
  2026. node.stream_ops = MEMFS.ops_table.link.stream;
  2027. } else if (FS.isChrdev(node.mode)) {
  2028. node.node_ops = MEMFS.ops_table.chrdev.node;
  2029. node.stream_ops = MEMFS.ops_table.chrdev.stream;
  2030. }
  2031. node.timestamp = Date.now();
  2032. // add the new node to the parent
  2033. if (parent) {
  2034. parent.contents[name] = node;
  2035. parent.timestamp = node.timestamp;
  2036. }
  2037. return node;
  2038. },getFileDataAsTypedArray:function(node) {
  2039. if (!node.contents) return new Uint8Array(0);
  2040. if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
  2041. return new Uint8Array(node.contents);
  2042. },expandFileStorage:function(node, newCapacity) {
  2043. var prevCapacity = node.contents ? node.contents.length : 0;
  2044. if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
  2045. // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
  2046. // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
  2047. // avoid overshooting the allocation cap by a very large margin.
  2048. var CAPACITY_DOUBLING_MAX = 1024 * 1024;
  2049. newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>> 0);
  2050. if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
  2051. var oldContents = node.contents;
  2052. node.contents = new Uint8Array(newCapacity); // Allocate new storage.
  2053. if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
  2054. },resizeFileStorage:function(node, newSize) {
  2055. if (node.usedBytes == newSize) return;
  2056. if (newSize == 0) {
  2057. node.contents = null; // Fully decommit when requesting a resize to zero.
  2058. node.usedBytes = 0;
  2059. } else {
  2060. var oldContents = node.contents;
  2061. node.contents = new Uint8Array(newSize); // Allocate new storage.
  2062. if (oldContents) {
  2063. node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
  2064. }
  2065. node.usedBytes = newSize;
  2066. }
  2067. },node_ops:{getattr:function(node) {
  2068. var attr = {};
  2069. // device numbers reuse inode numbers.
  2070. attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
  2071. attr.ino = node.id;
  2072. attr.mode = node.mode;
  2073. attr.nlink = 1;
  2074. attr.uid = 0;
  2075. attr.gid = 0;
  2076. attr.rdev = node.rdev;
  2077. if (FS.isDir(node.mode)) {
  2078. attr.size = 4096;
  2079. } else if (FS.isFile(node.mode)) {
  2080. attr.size = node.usedBytes;
  2081. } else if (FS.isLink(node.mode)) {
  2082. attr.size = node.link.length;
  2083. } else {
  2084. attr.size = 0;
  2085. }
  2086. attr.atime = new Date(node.timestamp);
  2087. attr.mtime = new Date(node.timestamp);
  2088. attr.ctime = new Date(node.timestamp);
  2089. // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
  2090. // but this is not required by the standard.
  2091. attr.blksize = 4096;
  2092. attr.blocks = Math.ceil(attr.size / attr.blksize);
  2093. return attr;
  2094. },setattr:function(node, attr) {
  2095. if (attr.mode !== undefined) {
  2096. node.mode = attr.mode;
  2097. }
  2098. if (attr.timestamp !== undefined) {
  2099. node.timestamp = attr.timestamp;
  2100. }
  2101. if (attr.size !== undefined) {
  2102. MEMFS.resizeFileStorage(node, attr.size);
  2103. }
  2104. },lookup:function(parent, name) {
  2105. throw FS.genericErrors[44];
  2106. },mknod:function(parent, name, mode, dev) {
  2107. return MEMFS.createNode(parent, name, mode, dev);
  2108. },rename:function(old_node, new_dir, new_name) {
  2109. // if we're overwriting a directory at new_name, make sure it's empty.
  2110. if (FS.isDir(old_node.mode)) {
  2111. var new_node;
  2112. try {
  2113. new_node = FS.lookupNode(new_dir, new_name);
  2114. } catch (e) {
  2115. }
  2116. if (new_node) {
  2117. for (var i in new_node.contents) {
  2118. throw new FS.ErrnoError(55);
  2119. }
  2120. }
  2121. }
  2122. // do the internal rewiring
  2123. delete old_node.parent.contents[old_node.name];
  2124. old_node.parent.timestamp = Date.now()
  2125. old_node.name = new_name;
  2126. new_dir.contents[new_name] = old_node;
  2127. new_dir.timestamp = old_node.parent.timestamp;
  2128. old_node.parent = new_dir;
  2129. },unlink:function(parent, name) {
  2130. delete parent.contents[name];
  2131. parent.timestamp = Date.now();
  2132. },rmdir:function(parent, name) {
  2133. var node = FS.lookupNode(parent, name);
  2134. for (var i in node.contents) {
  2135. throw new FS.ErrnoError(55);
  2136. }
  2137. delete parent.contents[name];
  2138. parent.timestamp = Date.now();
  2139. },readdir:function(node) {
  2140. var entries = ['.', '..'];
  2141. for (var key in node.contents) {
  2142. if (!node.contents.hasOwnProperty(key)) {
  2143. continue;
  2144. }
  2145. entries.push(key);
  2146. }
  2147. return entries;
  2148. },symlink:function(parent, newname, oldpath) {
  2149. var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
  2150. node.link = oldpath;
  2151. return node;
  2152. },readlink:function(node) {
  2153. if (!FS.isLink(node.mode)) {
  2154. throw new FS.ErrnoError(28);
  2155. }
  2156. return node.link;
  2157. }},stream_ops:{read:function(stream, buffer, offset, length, position) {
  2158. var contents = stream.node.contents;
  2159. if (position >= stream.node.usedBytes) return 0;
  2160. var size = Math.min(stream.node.usedBytes - position, length);
  2161. assert(size >= 0);
  2162. if (size > 8 && contents.subarray) { // non-trivial, and typed array
  2163. buffer.set(contents.subarray(position, position + size), offset);
  2164. } else {
  2165. for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
  2166. }
  2167. return size;
  2168. },write:function(stream, buffer, offset, length, position, canOwn) {
  2169. // The data buffer should be a typed array view
  2170. assert(!(buffer instanceof ArrayBuffer));
  2171. if (!length) return 0;
  2172. var node = stream.node;
  2173. node.timestamp = Date.now();
  2174. if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
  2175. if (canOwn) {
  2176. assert(position === 0, 'canOwn must imply no weird position inside the file');
  2177. node.contents = buffer.subarray(offset, offset + length);
  2178. node.usedBytes = length;
  2179. return length;
  2180. } else if (node.usedBytes === 0 && position === 0) { // 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.
  2181. node.contents = buffer.slice(offset, offset + length);
  2182. node.usedBytes = length;
  2183. return length;
  2184. } else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
  2185. node.contents.set(buffer.subarray(offset, offset + length), position);
  2186. return length;
  2187. }
  2188. }
  2189. // Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
  2190. MEMFS.expandFileStorage(node, position+length);
  2191. if (node.contents.subarray && buffer.subarray) {
  2192. // Use typed array write which is available.
  2193. node.contents.set(buffer.subarray(offset, offset + length), position);
  2194. } else {
  2195. for (var i = 0; i < length; i++) {
  2196. node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
  2197. }
  2198. }
  2199. node.usedBytes = Math.max(node.usedBytes, position + length);
  2200. return length;
  2201. },llseek:function(stream, offset, whence) {
  2202. var position = offset;
  2203. if (whence === 1) {
  2204. position += stream.position;
  2205. } else if (whence === 2) {
  2206. if (FS.isFile(stream.node.mode)) {
  2207. position += stream.node.usedBytes;
  2208. }
  2209. }
  2210. if (position < 0) {
  2211. throw new FS.ErrnoError(28);
  2212. }
  2213. return position;
  2214. },allocate:function(stream, offset, length) {
  2215. MEMFS.expandFileStorage(stream.node, offset + length);
  2216. stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
  2217. },mmap:function(stream, address, length, position, prot, flags) {
  2218. if (address !== 0) {
  2219. // We don't currently support location hints for the address of the mapping
  2220. throw new FS.ErrnoError(28);
  2221. }
  2222. if (!FS.isFile(stream.node.mode)) {
  2223. throw new FS.ErrnoError(43);
  2224. }
  2225. var ptr;
  2226. var allocated;
  2227. var contents = stream.node.contents;
  2228. // Only make a new copy when MAP_PRIVATE is specified.
  2229. if (!(flags & 2) && contents.buffer === buffer) {
  2230. // We can't emulate MAP_SHARED when the file is not backed by the buffer
  2231. // we're mapping to (e.g. the HEAP buffer).
  2232. allocated = false;
  2233. ptr = contents.byteOffset;
  2234. } else {
  2235. // Try to avoid unnecessary slices.
  2236. if (position > 0 || position + length < contents.length) {
  2237. if (contents.subarray) {
  2238. contents = contents.subarray(position, position + length);
  2239. } else {
  2240. contents = Array.prototype.slice.call(contents, position, position + length);
  2241. }
  2242. }
  2243. allocated = true;
  2244. ptr = mmapAlloc(length);
  2245. if (!ptr) {
  2246. throw new FS.ErrnoError(48);
  2247. }
  2248. HEAP8.set(contents, ptr);
  2249. }
  2250. return { ptr: ptr, allocated: allocated };
  2251. },msync:function(stream, buffer, offset, length, mmapFlags) {
  2252. if (!FS.isFile(stream.node.mode)) {
  2253. throw new FS.ErrnoError(43);
  2254. }
  2255. if (mmapFlags & 2) {
  2256. // MAP_PRIVATE calls need not to be synced back to underlying fs
  2257. return 0;
  2258. }
  2259. var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
  2260. // should we check if bytesWritten and length are the same?
  2261. return 0;
  2262. }}};
  2263. function asyncLoad(url, onload, onerror, noRunDep) {
  2264. var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : '';
  2265. readAsync(url, function(arrayBuffer) {
  2266. assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
  2267. onload(new Uint8Array(arrayBuffer));
  2268. if (dep) removeRunDependency(dep);
  2269. }, function(event) {
  2270. if (onerror) {
  2271. onerror();
  2272. } else {
  2273. throw 'Loading data file "' + url + '" failed.';
  2274. }
  2275. });
  2276. if (dep) addRunDependency(dep);
  2277. }
  2278. var ERRNO_MESSAGES = {0:"Success",1:"Arg list too long",2:"Permission denied",3:"Address already in use",4:"Address not available",5:"Address family not supported by protocol family",6:"No more processes",7:"Socket already connected",8:"Bad file number",9:"Trying to read unreadable message",10:"Mount device busy",11:"Operation canceled",12:"No children",13:"Connection aborted",14:"Connection refused",15:"Connection reset by peer",16:"File locking deadlock error",17:"Destination address required",18:"Math arg out of domain of func",19:"Quota exceeded",20:"File exists",21:"Bad address",22:"File too large",23:"Host is unreachable",24:"Identifier removed",25:"Illegal byte sequence",26:"Connection already in progress",27:"Interrupted system call",28:"Invalid argument",29:"I/O error",30:"Socket is already connected",31:"Is a directory",32:"Too many symbolic links",33:"Too many open files",34:"Too many links",35:"Message too long",36:"Multihop attempted",37:"File or path name too long",38:"Network interface is not configured",39:"Connection reset by network",40:"Network is unreachable",41:"Too many open files in system",42:"No buffer space available",43:"No such device",44:"No such file or directory",45:"Exec format error",46:"No record locks available",47:"The link has been severed",48:"Not enough core",49:"No message of desired type",50:"Protocol not available",51:"No space left on device",52:"Function not implemented",53:"Socket is not connected",54:"Not a directory",55:"Directory not empty",56:"State not recoverable",57:"Socket operation on non-socket",59:"Not a typewriter",60:"No such device or address",61:"Value too large for defined data type",62:"Previous owner died",63:"Not super-user",64:"Broken pipe",65:"Protocol error",66:"Unknown protocol",67:"Protocol wrong type for socket",68:"Math result not representable",69:"Read only file system",70:"Illegal seek",71:"No such process",72:"Stale file handle",73:"Connection timed out",74:"Text file busy",75:"Cross-device link",100:"Device not a stream",101:"Bad font file fmt",102:"Invalid slot",103:"Invalid request code",104:"No anode",105:"Block device required",106:"Channel number out of range",107:"Level 3 halted",108:"Level 3 reset",109:"Link number out of range",110:"Protocol driver not attached",111:"No CSI structure available",112:"Level 2 halted",113:"Invalid exchange",114:"Invalid request descriptor",115:"Exchange full",116:"No data (for no delay io)",117:"Timer expired",118:"Out of streams resources",119:"Machine is not on the network",120:"Package not installed",121:"The object is remote",122:"Advertise error",123:"Srmount error",124:"Communication error on send",125:"Cross mount point (not really error)",126:"Given log. name not unique",127:"f.d. invalid for this operation",128:"Remote address changed",129:"Can access a needed shared lib",130:"Accessing a corrupted shared lib",131:".lib section in a.out corrupted",132:"Attempting to link in too many libs",133:"Attempting to exec a shared library",135:"Streams pipe error",136:"Too many users",137:"Socket type not supported",138:"Not supported",139:"Protocol family not supported",140:"Can't send after socket shutdown",141:"Too many references",142:"Host is down",148:"No medium (in tape drive)",156:"Level 2 not synchronized"};
  2279. var ERRNO_CODES = {};
  2280. var FS = {root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:function(path, opts = {}) {
  2281. path = PATH_FS.resolve(FS.cwd(), path);
  2282. if (!path) return { path: '', node: null };
  2283. var defaults = {
  2284. follow_mount: true,
  2285. recurse_count: 0
  2286. };
  2287. for (var key in defaults) {
  2288. if (opts[key] === undefined) {
  2289. opts[key] = defaults[key];
  2290. }
  2291. }
  2292. if (opts.recurse_count > 8) { // max recursive lookup of 8
  2293. throw new FS.ErrnoError(32);
  2294. }
  2295. // split the path
  2296. var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
  2297. return !!p;
  2298. }), false);
  2299. // start at the root
  2300. var current = FS.root;
  2301. var current_path = '/';
  2302. for (var i = 0; i < parts.length; i++) {
  2303. var islast = (i === parts.length-1);
  2304. if (islast && opts.parent) {
  2305. // stop resolving
  2306. break;
  2307. }
  2308. current = FS.lookupNode(current, parts[i]);
  2309. current_path = PATH.join2(current_path, parts[i]);
  2310. // jump to the mount's root node if this is a mountpoint
  2311. if (FS.isMountpoint(current)) {
  2312. if (!islast || (islast && opts.follow_mount)) {
  2313. current = current.mounted.root;
  2314. }
  2315. }
  2316. // by default, lookupPath will not follow a symlink if it is the final path component.
  2317. // setting opts.follow = true will override this behavior.
  2318. if (!islast || opts.follow) {
  2319. var count = 0;
  2320. while (FS.isLink(current.mode)) {
  2321. var link = FS.readlink(current_path);
  2322. current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
  2323. var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
  2324. current = lookup.node;
  2325. if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
  2326. throw new FS.ErrnoError(32);
  2327. }
  2328. }
  2329. }
  2330. }
  2331. return { path: current_path, node: current };
  2332. },getPath:function(node) {
  2333. var path;
  2334. while (true) {
  2335. if (FS.isRoot(node)) {
  2336. var mount = node.mount.mountpoint;
  2337. if (!path) return mount;
  2338. return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
  2339. }
  2340. path = path ? node.name + '/' + path : node.name;
  2341. node = node.parent;
  2342. }
  2343. },hashName:function(parentid, name) {
  2344. var hash = 0;
  2345. for (var i = 0; i < name.length; i++) {
  2346. hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
  2347. }
  2348. return ((parentid + hash) >>> 0) % FS.nameTable.length;
  2349. },hashAddNode:function(node) {
  2350. var hash = FS.hashName(node.parent.id, node.name);
  2351. node.name_next = FS.nameTable[hash];
  2352. FS.nameTable[hash] = node;
  2353. },hashRemoveNode:function(node) {
  2354. var hash = FS.hashName(node.parent.id, node.name);
  2355. if (FS.nameTable[hash] === node) {
  2356. FS.nameTable[hash] = node.name_next;
  2357. } else {
  2358. var current = FS.nameTable[hash];
  2359. while (current) {
  2360. if (current.name_next === node) {
  2361. current.name_next = node.name_next;
  2362. break;
  2363. }
  2364. current = current.name_next;
  2365. }
  2366. }
  2367. },lookupNode:function(parent, name) {
  2368. var errCode = FS.mayLookup(parent);
  2369. if (errCode) {
  2370. throw new FS.ErrnoError(errCode, parent);
  2371. }
  2372. var hash = FS.hashName(parent.id, name);
  2373. for (var node = FS.nameTable[hash]; node; node = node.name_next) {
  2374. var nodeName = node.name;
  2375. if (node.parent.id === parent.id && nodeName === name) {
  2376. return node;
  2377. }
  2378. }
  2379. // if we failed to find it in the cache, call into the VFS
  2380. return FS.lookup(parent, name);
  2381. },createNode:function(parent, name, mode, rdev) {
  2382. assert(typeof parent === 'object')
  2383. var node = new FS.FSNode(parent, name, mode, rdev);
  2384. FS.hashAddNode(node);
  2385. return node;
  2386. },destroyNode:function(node) {
  2387. FS.hashRemoveNode(node);
  2388. },isRoot:function(node) {
  2389. return node === node.parent;
  2390. },isMountpoint:function(node) {
  2391. return !!node.mounted;
  2392. },isFile:function(mode) {
  2393. return (mode & 61440) === 32768;
  2394. },isDir:function(mode) {
  2395. return (mode & 61440) === 16384;
  2396. },isLink:function(mode) {
  2397. return (mode & 61440) === 40960;
  2398. },isChrdev:function(mode) {
  2399. return (mode & 61440) === 8192;
  2400. },isBlkdev:function(mode) {
  2401. return (mode & 61440) === 24576;
  2402. },isFIFO:function(mode) {
  2403. return (mode & 61440) === 4096;
  2404. },isSocket:function(mode) {
  2405. return (mode & 49152) === 49152;
  2406. },flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:function(str) {
  2407. var flags = FS.flagModes[str];
  2408. if (typeof flags === 'undefined') {
  2409. throw new Error('Unknown file open mode: ' + str);
  2410. }
  2411. return flags;
  2412. },flagsToPermissionString:function(flag) {
  2413. var perms = ['r', 'w', 'rw'][flag & 3];
  2414. if ((flag & 512)) {
  2415. perms += 'w';
  2416. }
  2417. return perms;
  2418. },nodePermissions:function(node, perms) {
  2419. if (FS.ignorePermissions) {
  2420. return 0;
  2421. }
  2422. // return 0 if any user, group or owner bits are set.
  2423. if (perms.includes('r') && !(node.mode & 292)) {
  2424. return 2;
  2425. } else if (perms.includes('w') && !(node.mode & 146)) {
  2426. return 2;
  2427. } else if (perms.includes('x') && !(node.mode & 73)) {
  2428. return 2;
  2429. }
  2430. return 0;
  2431. },mayLookup:function(dir) {
  2432. var errCode = FS.nodePermissions(dir, 'x');
  2433. if (errCode) return errCode;
  2434. if (!dir.node_ops.lookup) return 2;
  2435. return 0;
  2436. },mayCreate:function(dir, name) {
  2437. try {
  2438. var node = FS.lookupNode(dir, name);
  2439. return 20;
  2440. } catch (e) {
  2441. }
  2442. return FS.nodePermissions(dir, 'wx');
  2443. },mayDelete:function(dir, name, isdir) {
  2444. var node;
  2445. try {
  2446. node = FS.lookupNode(dir, name);
  2447. } catch (e) {
  2448. return e.errno;
  2449. }
  2450. var errCode = FS.nodePermissions(dir, 'wx');
  2451. if (errCode) {
  2452. return errCode;
  2453. }
  2454. if (isdir) {
  2455. if (!FS.isDir(node.mode)) {
  2456. return 54;
  2457. }
  2458. if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
  2459. return 10;
  2460. }
  2461. } else {
  2462. if (FS.isDir(node.mode)) {
  2463. return 31;
  2464. }
  2465. }
  2466. return 0;
  2467. },mayOpen:function(node, flags) {
  2468. if (!node) {
  2469. return 44;
  2470. }
  2471. if (FS.isLink(node.mode)) {
  2472. return 32;
  2473. } else if (FS.isDir(node.mode)) {
  2474. if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
  2475. (flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
  2476. return 31;
  2477. }
  2478. }
  2479. return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
  2480. },MAX_OPEN_FDS:4096,nextfd:function(fd_start = 0, fd_end = FS.MAX_OPEN_FDS) {
  2481. for (var fd = fd_start; fd <= fd_end; fd++) {
  2482. if (!FS.streams[fd]) {
  2483. return fd;
  2484. }
  2485. }
  2486. throw new FS.ErrnoError(33);
  2487. },getStream:function(fd) {
  2488. return FS.streams[fd];
  2489. },createStream:function(stream, fd_start, fd_end) {
  2490. if (!FS.FSStream) {
  2491. FS.FSStream = /** @constructor */ function(){};
  2492. FS.FSStream.prototype = {
  2493. object: {
  2494. get: function() { return this.node; },
  2495. set: function(val) { this.node = val; }
  2496. },
  2497. isRead: {
  2498. get: function() { return (this.flags & 2097155) !== 1; }
  2499. },
  2500. isWrite: {
  2501. get: function() { return (this.flags & 2097155) !== 0; }
  2502. },
  2503. isAppend: {
  2504. get: function() { return (this.flags & 1024); }
  2505. }
  2506. };
  2507. }
  2508. // clone it, so we can return an instance of FSStream
  2509. var newStream = new FS.FSStream();
  2510. for (var p in stream) {
  2511. newStream[p] = stream[p];
  2512. }
  2513. stream = newStream;
  2514. var fd = FS.nextfd(fd_start, fd_end);
  2515. stream.fd = fd;
  2516. FS.streams[fd] = stream;
  2517. return stream;
  2518. },closeStream:function(fd) {
  2519. FS.streams[fd] = null;
  2520. },chrdev_stream_ops:{open:function(stream) {
  2521. var device = FS.getDevice(stream.node.rdev);
  2522. // override node's stream ops with the device's
  2523. stream.stream_ops = device.stream_ops;
  2524. // forward the open call
  2525. if (stream.stream_ops.open) {
  2526. stream.stream_ops.open(stream);
  2527. }
  2528. },llseek:function() {
  2529. throw new FS.ErrnoError(70);
  2530. }},major:function(dev) {
  2531. return ((dev) >> 8);
  2532. },minor:function(dev) {
  2533. return ((dev) & 0xff);
  2534. },makedev:function(ma, mi) {
  2535. return ((ma) << 8 | (mi));
  2536. },registerDevice:function(dev, ops) {
  2537. FS.devices[dev] = { stream_ops: ops };
  2538. },getDevice:function(dev) {
  2539. return FS.devices[dev];
  2540. },getMounts:function(mount) {
  2541. var mounts = [];
  2542. var check = [mount];
  2543. while (check.length) {
  2544. var m = check.pop();
  2545. mounts.push(m);
  2546. check.push.apply(check, m.mounts);
  2547. }
  2548. return mounts;
  2549. },syncfs:function(populate, callback) {
  2550. if (typeof(populate) === 'function') {
  2551. callback = populate;
  2552. populate = false;
  2553. }
  2554. FS.syncFSRequests++;
  2555. if (FS.syncFSRequests > 1) {
  2556. err('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
  2557. }
  2558. var mounts = FS.getMounts(FS.root.mount);
  2559. var completed = 0;
  2560. function doCallback(errCode) {
  2561. assert(FS.syncFSRequests > 0);
  2562. FS.syncFSRequests--;
  2563. return callback(errCode);
  2564. }
  2565. function done(errCode) {
  2566. if (errCode) {
  2567. if (!done.errored) {
  2568. done.errored = true;
  2569. return doCallback(errCode);
  2570. }
  2571. return;
  2572. }
  2573. if (++completed >= mounts.length) {
  2574. doCallback(null);
  2575. }
  2576. };
  2577. // sync all mounts
  2578. mounts.forEach(function (mount) {
  2579. if (!mount.type.syncfs) {
  2580. return done(null);
  2581. }
  2582. mount.type.syncfs(mount, populate, done);
  2583. });
  2584. },mount:function(type, opts, mountpoint) {
  2585. if (typeof type === 'string') {
  2586. // The filesystem was not included, and instead we have an error
  2587. // message stored in the variable.
  2588. throw type;
  2589. }
  2590. var root = mountpoint === '/';
  2591. var pseudo = !mountpoint;
  2592. var node;
  2593. if (root && FS.root) {
  2594. throw new FS.ErrnoError(10);
  2595. } else if (!root && !pseudo) {
  2596. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2597. mountpoint = lookup.path; // use the absolute path
  2598. node = lookup.node;
  2599. if (FS.isMountpoint(node)) {
  2600. throw new FS.ErrnoError(10);
  2601. }
  2602. if (!FS.isDir(node.mode)) {
  2603. throw new FS.ErrnoError(54);
  2604. }
  2605. }
  2606. var mount = {
  2607. type: type,
  2608. opts: opts,
  2609. mountpoint: mountpoint,
  2610. mounts: []
  2611. };
  2612. // create a root node for the fs
  2613. var mountRoot = type.mount(mount);
  2614. mountRoot.mount = mount;
  2615. mount.root = mountRoot;
  2616. if (root) {
  2617. FS.root = mountRoot;
  2618. } else if (node) {
  2619. // set as a mountpoint
  2620. node.mounted = mount;
  2621. // add the new mount to the current mount's children
  2622. if (node.mount) {
  2623. node.mount.mounts.push(mount);
  2624. }
  2625. }
  2626. return mountRoot;
  2627. },unmount:function (mountpoint) {
  2628. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2629. if (!FS.isMountpoint(lookup.node)) {
  2630. throw new FS.ErrnoError(28);
  2631. }
  2632. // destroy the nodes for this mount, and all its child mounts
  2633. var node = lookup.node;
  2634. var mount = node.mounted;
  2635. var mounts = FS.getMounts(mount);
  2636. Object.keys(FS.nameTable).forEach(function (hash) {
  2637. var current = FS.nameTable[hash];
  2638. while (current) {
  2639. var next = current.name_next;
  2640. if (mounts.includes(current.mount)) {
  2641. FS.destroyNode(current);
  2642. }
  2643. current = next;
  2644. }
  2645. });
  2646. // no longer a mountpoint
  2647. node.mounted = null;
  2648. // remove this mount from the child mounts
  2649. var idx = node.mount.mounts.indexOf(mount);
  2650. assert(idx !== -1);
  2651. node.mount.mounts.splice(idx, 1);
  2652. },lookup:function(parent, name) {
  2653. return parent.node_ops.lookup(parent, name);
  2654. },mknod:function(path, mode, dev) {
  2655. var lookup = FS.lookupPath(path, { parent: true });
  2656. var parent = lookup.node;
  2657. var name = PATH.basename(path);
  2658. if (!name || name === '.' || name === '..') {
  2659. throw new FS.ErrnoError(28);
  2660. }
  2661. var errCode = FS.mayCreate(parent, name);
  2662. if (errCode) {
  2663. throw new FS.ErrnoError(errCode);
  2664. }
  2665. if (!parent.node_ops.mknod) {
  2666. throw new FS.ErrnoError(63);
  2667. }
  2668. return parent.node_ops.mknod(parent, name, mode, dev);
  2669. },create:function(path, mode) {
  2670. mode = mode !== undefined ? mode : 438 /* 0666 */;
  2671. mode &= 4095;
  2672. mode |= 32768;
  2673. return FS.mknod(path, mode, 0);
  2674. },mkdir:function(path, mode) {
  2675. mode = mode !== undefined ? mode : 511 /* 0777 */;
  2676. mode &= 511 | 512;
  2677. mode |= 16384;
  2678. return FS.mknod(path, mode, 0);
  2679. },mkdirTree:function(path, mode) {
  2680. var dirs = path.split('/');
  2681. var d = '';
  2682. for (var i = 0; i < dirs.length; ++i) {
  2683. if (!dirs[i]) continue;
  2684. d += '/' + dirs[i];
  2685. try {
  2686. FS.mkdir(d, mode);
  2687. } catch(e) {
  2688. if (e.errno != 20) throw e;
  2689. }
  2690. }
  2691. },mkdev:function(path, mode, dev) {
  2692. if (typeof(dev) === 'undefined') {
  2693. dev = mode;
  2694. mode = 438 /* 0666 */;
  2695. }
  2696. mode |= 8192;
  2697. return FS.mknod(path, mode, dev);
  2698. },symlink:function(oldpath, newpath) {
  2699. if (!PATH_FS.resolve(oldpath)) {
  2700. throw new FS.ErrnoError(44);
  2701. }
  2702. var lookup = FS.lookupPath(newpath, { parent: true });
  2703. var parent = lookup.node;
  2704. if (!parent) {
  2705. throw new FS.ErrnoError(44);
  2706. }
  2707. var newname = PATH.basename(newpath);
  2708. var errCode = FS.mayCreate(parent, newname);
  2709. if (errCode) {
  2710. throw new FS.ErrnoError(errCode);
  2711. }
  2712. if (!parent.node_ops.symlink) {
  2713. throw new FS.ErrnoError(63);
  2714. }
  2715. return parent.node_ops.symlink(parent, newname, oldpath);
  2716. },rename:function(old_path, new_path) {
  2717. var old_dirname = PATH.dirname(old_path);
  2718. var new_dirname = PATH.dirname(new_path);
  2719. var old_name = PATH.basename(old_path);
  2720. var new_name = PATH.basename(new_path);
  2721. // parents must exist
  2722. var lookup, old_dir, new_dir;
  2723. // let the errors from non existant directories percolate up
  2724. lookup = FS.lookupPath(old_path, { parent: true });
  2725. old_dir = lookup.node;
  2726. lookup = FS.lookupPath(new_path, { parent: true });
  2727. new_dir = lookup.node;
  2728. if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
  2729. // need to be part of the same mount
  2730. if (old_dir.mount !== new_dir.mount) {
  2731. throw new FS.ErrnoError(75);
  2732. }
  2733. // source must exist
  2734. var old_node = FS.lookupNode(old_dir, old_name);
  2735. // old path should not be an ancestor of the new path
  2736. var relative = PATH_FS.relative(old_path, new_dirname);
  2737. if (relative.charAt(0) !== '.') {
  2738. throw new FS.ErrnoError(28);
  2739. }
  2740. // new path should not be an ancestor of the old path
  2741. relative = PATH_FS.relative(new_path, old_dirname);
  2742. if (relative.charAt(0) !== '.') {
  2743. throw new FS.ErrnoError(55);
  2744. }
  2745. // see if the new path already exists
  2746. var new_node;
  2747. try {
  2748. new_node = FS.lookupNode(new_dir, new_name);
  2749. } catch (e) {
  2750. // not fatal
  2751. }
  2752. // early out if nothing needs to change
  2753. if (old_node === new_node) {
  2754. return;
  2755. }
  2756. // we'll need to delete the old entry
  2757. var isdir = FS.isDir(old_node.mode);
  2758. var errCode = FS.mayDelete(old_dir, old_name, isdir);
  2759. if (errCode) {
  2760. throw new FS.ErrnoError(errCode);
  2761. }
  2762. // need delete permissions if we'll be overwriting.
  2763. // need create permissions if new doesn't already exist.
  2764. errCode = new_node ?
  2765. FS.mayDelete(new_dir, new_name, isdir) :
  2766. FS.mayCreate(new_dir, new_name);
  2767. if (errCode) {
  2768. throw new FS.ErrnoError(errCode);
  2769. }
  2770. if (!old_dir.node_ops.rename) {
  2771. throw new FS.ErrnoError(63);
  2772. }
  2773. if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
  2774. throw new FS.ErrnoError(10);
  2775. }
  2776. // if we are going to change the parent, check write permissions
  2777. if (new_dir !== old_dir) {
  2778. errCode = FS.nodePermissions(old_dir, 'w');
  2779. if (errCode) {
  2780. throw new FS.ErrnoError(errCode);
  2781. }
  2782. }
  2783. // remove the node from the lookup hash
  2784. FS.hashRemoveNode(old_node);
  2785. // do the underlying fs rename
  2786. try {
  2787. old_dir.node_ops.rename(old_node, new_dir, new_name);
  2788. } catch (e) {
  2789. throw e;
  2790. } finally {
  2791. // add the node back to the hash (in case node_ops.rename
  2792. // changed its name)
  2793. FS.hashAddNode(old_node);
  2794. }
  2795. },rmdir:function(path) {
  2796. var lookup = FS.lookupPath(path, { parent: true });
  2797. var parent = lookup.node;
  2798. var name = PATH.basename(path);
  2799. var node = FS.lookupNode(parent, name);
  2800. var errCode = FS.mayDelete(parent, name, true);
  2801. if (errCode) {
  2802. throw new FS.ErrnoError(errCode);
  2803. }
  2804. if (!parent.node_ops.rmdir) {
  2805. throw new FS.ErrnoError(63);
  2806. }
  2807. if (FS.isMountpoint(node)) {
  2808. throw new FS.ErrnoError(10);
  2809. }
  2810. parent.node_ops.rmdir(parent, name);
  2811. FS.destroyNode(node);
  2812. },readdir:function(path) {
  2813. var lookup = FS.lookupPath(path, { follow: true });
  2814. var node = lookup.node;
  2815. if (!node.node_ops.readdir) {
  2816. throw new FS.ErrnoError(54);
  2817. }
  2818. return node.node_ops.readdir(node);
  2819. },unlink:function(path) {
  2820. var lookup = FS.lookupPath(path, { parent: true });
  2821. var parent = lookup.node;
  2822. if (!parent) {
  2823. throw new FS.ErrnoError(44);
  2824. }
  2825. var name = PATH.basename(path);
  2826. var node = FS.lookupNode(parent, name);
  2827. var errCode = FS.mayDelete(parent, name, false);
  2828. if (errCode) {
  2829. // According to POSIX, we should map EISDIR to EPERM, but
  2830. // we instead do what Linux does (and we must, as we use
  2831. // the musl linux libc).
  2832. throw new FS.ErrnoError(errCode);
  2833. }
  2834. if (!parent.node_ops.unlink) {
  2835. throw new FS.ErrnoError(63);
  2836. }
  2837. if (FS.isMountpoint(node)) {
  2838. throw new FS.ErrnoError(10);
  2839. }
  2840. parent.node_ops.unlink(parent, name);
  2841. FS.destroyNode(node);
  2842. },readlink:function(path) {
  2843. var lookup = FS.lookupPath(path);
  2844. var link = lookup.node;
  2845. if (!link) {
  2846. throw new FS.ErrnoError(44);
  2847. }
  2848. if (!link.node_ops.readlink) {
  2849. throw new FS.ErrnoError(28);
  2850. }
  2851. return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
  2852. },stat:function(path, dontFollow) {
  2853. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2854. var node = lookup.node;
  2855. if (!node) {
  2856. throw new FS.ErrnoError(44);
  2857. }
  2858. if (!node.node_ops.getattr) {
  2859. throw new FS.ErrnoError(63);
  2860. }
  2861. return node.node_ops.getattr(node);
  2862. },lstat:function(path) {
  2863. return FS.stat(path, true);
  2864. },chmod:function(path, mode, dontFollow) {
  2865. var node;
  2866. if (typeof path === 'string') {
  2867. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2868. node = lookup.node;
  2869. } else {
  2870. node = path;
  2871. }
  2872. if (!node.node_ops.setattr) {
  2873. throw new FS.ErrnoError(63);
  2874. }
  2875. node.node_ops.setattr(node, {
  2876. mode: (mode & 4095) | (node.mode & ~4095),
  2877. timestamp: Date.now()
  2878. });
  2879. },lchmod:function(path, mode) {
  2880. FS.chmod(path, mode, true);
  2881. },fchmod:function(fd, mode) {
  2882. var stream = FS.getStream(fd);
  2883. if (!stream) {
  2884. throw new FS.ErrnoError(8);
  2885. }
  2886. FS.chmod(stream.node, mode);
  2887. },chown:function(path, uid, gid, dontFollow) {
  2888. var node;
  2889. if (typeof path === 'string') {
  2890. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2891. node = lookup.node;
  2892. } else {
  2893. node = path;
  2894. }
  2895. if (!node.node_ops.setattr) {
  2896. throw new FS.ErrnoError(63);
  2897. }
  2898. node.node_ops.setattr(node, {
  2899. timestamp: Date.now()
  2900. // we ignore the uid / gid for now
  2901. });
  2902. },lchown:function(path, uid, gid) {
  2903. FS.chown(path, uid, gid, true);
  2904. },fchown:function(fd, uid, gid) {
  2905. var stream = FS.getStream(fd);
  2906. if (!stream) {
  2907. throw new FS.ErrnoError(8);
  2908. }
  2909. FS.chown(stream.node, uid, gid);
  2910. },truncate:function(path, len) {
  2911. if (len < 0) {
  2912. throw new FS.ErrnoError(28);
  2913. }
  2914. var node;
  2915. if (typeof path === 'string') {
  2916. var lookup = FS.lookupPath(path, { follow: true });
  2917. node = lookup.node;
  2918. } else {
  2919. node = path;
  2920. }
  2921. if (!node.node_ops.setattr) {
  2922. throw new FS.ErrnoError(63);
  2923. }
  2924. if (FS.isDir(node.mode)) {
  2925. throw new FS.ErrnoError(31);
  2926. }
  2927. if (!FS.isFile(node.mode)) {
  2928. throw new FS.ErrnoError(28);
  2929. }
  2930. var errCode = FS.nodePermissions(node, 'w');
  2931. if (errCode) {
  2932. throw new FS.ErrnoError(errCode);
  2933. }
  2934. node.node_ops.setattr(node, {
  2935. size: len,
  2936. timestamp: Date.now()
  2937. });
  2938. },ftruncate:function(fd, len) {
  2939. var stream = FS.getStream(fd);
  2940. if (!stream) {
  2941. throw new FS.ErrnoError(8);
  2942. }
  2943. if ((stream.flags & 2097155) === 0) {
  2944. throw new FS.ErrnoError(28);
  2945. }
  2946. FS.truncate(stream.node, len);
  2947. },utime:function(path, atime, mtime) {
  2948. var lookup = FS.lookupPath(path, { follow: true });
  2949. var node = lookup.node;
  2950. node.node_ops.setattr(node, {
  2951. timestamp: Math.max(atime, mtime)
  2952. });
  2953. },open:function(path, flags, mode, fd_start, fd_end) {
  2954. if (path === "") {
  2955. throw new FS.ErrnoError(44);
  2956. }
  2957. flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
  2958. mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
  2959. if ((flags & 64)) {
  2960. mode = (mode & 4095) | 32768;
  2961. } else {
  2962. mode = 0;
  2963. }
  2964. var node;
  2965. if (typeof path === 'object') {
  2966. node = path;
  2967. } else {
  2968. path = PATH.normalize(path);
  2969. try {
  2970. var lookup = FS.lookupPath(path, {
  2971. follow: !(flags & 131072)
  2972. });
  2973. node = lookup.node;
  2974. } catch (e) {
  2975. // ignore
  2976. }
  2977. }
  2978. // perhaps we need to create the node
  2979. var created = false;
  2980. if ((flags & 64)) {
  2981. if (node) {
  2982. // if O_CREAT and O_EXCL are set, error out if the node already exists
  2983. if ((flags & 128)) {
  2984. throw new FS.ErrnoError(20);
  2985. }
  2986. } else {
  2987. // node doesn't exist, try to create it
  2988. node = FS.mknod(path, mode, 0);
  2989. created = true;
  2990. }
  2991. }
  2992. if (!node) {
  2993. throw new FS.ErrnoError(44);
  2994. }
  2995. // can't truncate a device
  2996. if (FS.isChrdev(node.mode)) {
  2997. flags &= ~512;
  2998. }
  2999. // if asked only for a directory, then this must be one
  3000. if ((flags & 65536) && !FS.isDir(node.mode)) {
  3001. throw new FS.ErrnoError(54);
  3002. }
  3003. // check permissions, if this is not a file we just created now (it is ok to
  3004. // create and write to a file with read-only permissions; it is read-only
  3005. // for later use)
  3006. if (!created) {
  3007. var errCode = FS.mayOpen(node, flags);
  3008. if (errCode) {
  3009. throw new FS.ErrnoError(errCode);
  3010. }
  3011. }
  3012. // do truncation if necessary
  3013. if ((flags & 512)) {
  3014. FS.truncate(node, 0);
  3015. }
  3016. // we've already handled these, don't pass down to the underlying vfs
  3017. flags &= ~(128 | 512 | 131072);
  3018. // register the stream with the filesystem
  3019. var stream = FS.createStream({
  3020. node: node,
  3021. path: FS.getPath(node), // we want the absolute path to the node
  3022. id: node.id,
  3023. flags: flags,
  3024. mode: node.mode,
  3025. seekable: true,
  3026. position: 0,
  3027. stream_ops: node.stream_ops,
  3028. node_ops: node.node_ops,
  3029. // used by the file family libc calls (fopen, fwrite, ferror, etc.)
  3030. ungotten: [],
  3031. error: false
  3032. }, fd_start, fd_end);
  3033. // call the new stream's open function
  3034. if (stream.stream_ops.open) {
  3035. stream.stream_ops.open(stream);
  3036. }
  3037. if (Module['logReadFiles'] && !(flags & 1)) {
  3038. if (!FS.readFiles) FS.readFiles = {};
  3039. if (!(path in FS.readFiles)) {
  3040. FS.readFiles[path] = 1;
  3041. }
  3042. }
  3043. return stream;
  3044. },close:function(stream) {
  3045. if (FS.isClosed(stream)) {
  3046. throw new FS.ErrnoError(8);
  3047. }
  3048. if (stream.getdents) stream.getdents = null; // free readdir state
  3049. try {
  3050. if (stream.stream_ops.close) {
  3051. stream.stream_ops.close(stream);
  3052. }
  3053. } catch (e) {
  3054. throw e;
  3055. } finally {
  3056. FS.closeStream(stream.fd);
  3057. }
  3058. stream.fd = null;
  3059. },isClosed:function(stream) {
  3060. return stream.fd === null;
  3061. },llseek:function(stream, offset, whence) {
  3062. if (FS.isClosed(stream)) {
  3063. throw new FS.ErrnoError(8);
  3064. }
  3065. if (!stream.seekable || !stream.stream_ops.llseek) {
  3066. throw new FS.ErrnoError(70);
  3067. }
  3068. if (whence != 0 && whence != 1 && whence != 2) {
  3069. throw new FS.ErrnoError(28);
  3070. }
  3071. stream.position = stream.stream_ops.llseek(stream, offset, whence);
  3072. stream.ungotten = [];
  3073. return stream.position;
  3074. },read:function(stream, buffer, offset, length, position) {
  3075. if (length < 0 || position < 0) {
  3076. throw new FS.ErrnoError(28);
  3077. }
  3078. if (FS.isClosed(stream)) {
  3079. throw new FS.ErrnoError(8);
  3080. }
  3081. if ((stream.flags & 2097155) === 1) {
  3082. throw new FS.ErrnoError(8);
  3083. }
  3084. if (FS.isDir(stream.node.mode)) {
  3085. throw new FS.ErrnoError(31);
  3086. }
  3087. if (!stream.stream_ops.read) {
  3088. throw new FS.ErrnoError(28);
  3089. }
  3090. var seeking = typeof position !== 'undefined';
  3091. if (!seeking) {
  3092. position = stream.position;
  3093. } else if (!stream.seekable) {
  3094. throw new FS.ErrnoError(70);
  3095. }
  3096. var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
  3097. if (!seeking) stream.position += bytesRead;
  3098. return bytesRead;
  3099. },write:function(stream, buffer, offset, length, position, canOwn) {
  3100. if (length < 0 || position < 0) {
  3101. throw new FS.ErrnoError(28);
  3102. }
  3103. if (FS.isClosed(stream)) {
  3104. throw new FS.ErrnoError(8);
  3105. }
  3106. if ((stream.flags & 2097155) === 0) {
  3107. throw new FS.ErrnoError(8);
  3108. }
  3109. if (FS.isDir(stream.node.mode)) {
  3110. throw new FS.ErrnoError(31);
  3111. }
  3112. if (!stream.stream_ops.write) {
  3113. throw new FS.ErrnoError(28);
  3114. }
  3115. if (stream.seekable && stream.flags & 1024) {
  3116. // seek to the end before writing in append mode
  3117. FS.llseek(stream, 0, 2);
  3118. }
  3119. var seeking = typeof position !== 'undefined';
  3120. if (!seeking) {
  3121. position = stream.position;
  3122. } else if (!stream.seekable) {
  3123. throw new FS.ErrnoError(70);
  3124. }
  3125. var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
  3126. if (!seeking) stream.position += bytesWritten;
  3127. return bytesWritten;
  3128. },allocate:function(stream, offset, length) {
  3129. if (FS.isClosed(stream)) {
  3130. throw new FS.ErrnoError(8);
  3131. }
  3132. if (offset < 0 || length <= 0) {
  3133. throw new FS.ErrnoError(28);
  3134. }
  3135. if ((stream.flags & 2097155) === 0) {
  3136. throw new FS.ErrnoError(8);
  3137. }
  3138. if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
  3139. throw new FS.ErrnoError(43);
  3140. }
  3141. if (!stream.stream_ops.allocate) {
  3142. throw new FS.ErrnoError(138);
  3143. }
  3144. stream.stream_ops.allocate(stream, offset, length);
  3145. },mmap:function(stream, address, length, position, prot, flags) {
  3146. // User requests writing to file (prot & PROT_WRITE != 0).
  3147. // Checking if we have permissions to write to the file unless
  3148. // MAP_PRIVATE flag is set. According to POSIX spec it is possible
  3149. // to write to file opened in read-only mode with MAP_PRIVATE flag,
  3150. // as all modifications will be visible only in the memory of
  3151. // the current process.
  3152. if ((prot & 2) !== 0
  3153. && (flags & 2) === 0
  3154. && (stream.flags & 2097155) !== 2) {
  3155. throw new FS.ErrnoError(2);
  3156. }
  3157. if ((stream.flags & 2097155) === 1) {
  3158. throw new FS.ErrnoError(2);
  3159. }
  3160. if (!stream.stream_ops.mmap) {
  3161. throw new FS.ErrnoError(43);
  3162. }
  3163. return stream.stream_ops.mmap(stream, address, length, position, prot, flags);
  3164. },msync:function(stream, buffer, offset, length, mmapFlags) {
  3165. if (!stream || !stream.stream_ops.msync) {
  3166. return 0;
  3167. }
  3168. return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
  3169. },munmap:function(stream) {
  3170. return 0;
  3171. },ioctl:function(stream, cmd, arg) {
  3172. if (!stream.stream_ops.ioctl) {
  3173. throw new FS.ErrnoError(59);
  3174. }
  3175. return stream.stream_ops.ioctl(stream, cmd, arg);
  3176. },readFile:function(path, opts = {}) {
  3177. opts.flags = opts.flags || 0;
  3178. opts.encoding = opts.encoding || 'binary';
  3179. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  3180. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  3181. }
  3182. var ret;
  3183. var stream = FS.open(path, opts.flags);
  3184. var stat = FS.stat(path);
  3185. var length = stat.size;
  3186. var buf = new Uint8Array(length);
  3187. FS.read(stream, buf, 0, length, 0);
  3188. if (opts.encoding === 'utf8') {
  3189. ret = UTF8ArrayToString(buf, 0);
  3190. } else if (opts.encoding === 'binary') {
  3191. ret = buf;
  3192. }
  3193. FS.close(stream);
  3194. return ret;
  3195. },writeFile:function(path, data, opts = {}) {
  3196. opts.flags = opts.flags || 577;
  3197. var stream = FS.open(path, opts.flags, opts.mode);
  3198. if (typeof data === 'string') {
  3199. var buf = new Uint8Array(lengthBytesUTF8(data)+1);
  3200. var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
  3201. FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
  3202. } else if (ArrayBuffer.isView(data)) {
  3203. FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
  3204. } else {
  3205. throw new Error('Unsupported data type');
  3206. }
  3207. FS.close(stream);
  3208. },cwd:function() {
  3209. return FS.currentPath;
  3210. },chdir:function(path) {
  3211. var lookup = FS.lookupPath(path, { follow: true });
  3212. if (lookup.node === null) {
  3213. throw new FS.ErrnoError(44);
  3214. }
  3215. if (!FS.isDir(lookup.node.mode)) {
  3216. throw new FS.ErrnoError(54);
  3217. }
  3218. var errCode = FS.nodePermissions(lookup.node, 'x');
  3219. if (errCode) {
  3220. throw new FS.ErrnoError(errCode);
  3221. }
  3222. FS.currentPath = lookup.path;
  3223. },createDefaultDirectories:function() {
  3224. FS.mkdir('/tmp');
  3225. FS.mkdir('/home');
  3226. FS.mkdir('/home/web_user');
  3227. },createDefaultDevices:function() {
  3228. // create /dev
  3229. FS.mkdir('/dev');
  3230. // setup /dev/null
  3231. FS.registerDevice(FS.makedev(1, 3), {
  3232. read: function() { return 0; },
  3233. write: function(stream, buffer, offset, length, pos) { return length; }
  3234. });
  3235. FS.mkdev('/dev/null', FS.makedev(1, 3));
  3236. // setup /dev/tty and /dev/tty1
  3237. // stderr needs to print output using err() rather than out()
  3238. // so we register a second tty just for it.
  3239. TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
  3240. TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
  3241. FS.mkdev('/dev/tty', FS.makedev(5, 0));
  3242. FS.mkdev('/dev/tty1', FS.makedev(6, 0));
  3243. // setup /dev/[u]random
  3244. var random_device = getRandomDevice();
  3245. FS.createDevice('/dev', 'random', random_device);
  3246. FS.createDevice('/dev', 'urandom', random_device);
  3247. // we're not going to emulate the actual shm device,
  3248. // just create the tmp dirs that reside in it commonly
  3249. FS.mkdir('/dev/shm');
  3250. FS.mkdir('/dev/shm/tmp');
  3251. },createSpecialDirectories:function() {
  3252. // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the
  3253. // name of the stream for fd 6 (see test_unistd_ttyname)
  3254. FS.mkdir('/proc');
  3255. var proc_self = FS.mkdir('/proc/self');
  3256. FS.mkdir('/proc/self/fd');
  3257. FS.mount({
  3258. mount: function() {
  3259. var node = FS.createNode(proc_self, 'fd', 16384 | 511 /* 0777 */, 73);
  3260. node.node_ops = {
  3261. lookup: function(parent, name) {
  3262. var fd = +name;
  3263. var stream = FS.getStream(fd);
  3264. if (!stream) throw new FS.ErrnoError(8);
  3265. var ret = {
  3266. parent: null,
  3267. mount: { mountpoint: 'fake' },
  3268. node_ops: { readlink: function() { return stream.path } }
  3269. };
  3270. ret.parent = ret; // make it look like a simple root node
  3271. return ret;
  3272. }
  3273. };
  3274. return node;
  3275. }
  3276. }, {}, '/proc/self/fd');
  3277. },createStandardStreams:function() {
  3278. // TODO deprecate the old functionality of a single
  3279. // input / output callback and that utilizes FS.createDevice
  3280. // and instead require a unique set of stream ops
  3281. // by default, we symlink the standard streams to the
  3282. // default tty devices. however, if the standard streams
  3283. // have been overwritten we create a unique device for
  3284. // them instead.
  3285. if (Module['stdin']) {
  3286. FS.createDevice('/dev', 'stdin', Module['stdin']);
  3287. } else {
  3288. FS.symlink('/dev/tty', '/dev/stdin');
  3289. }
  3290. if (Module['stdout']) {
  3291. FS.createDevice('/dev', 'stdout', null, Module['stdout']);
  3292. } else {
  3293. FS.symlink('/dev/tty', '/dev/stdout');
  3294. }
  3295. if (Module['stderr']) {
  3296. FS.createDevice('/dev', 'stderr', null, Module['stderr']);
  3297. } else {
  3298. FS.symlink('/dev/tty1', '/dev/stderr');
  3299. }
  3300. // open default streams for the stdin, stdout and stderr devices
  3301. var stdin = FS.open('/dev/stdin', 0);
  3302. var stdout = FS.open('/dev/stdout', 1);
  3303. var stderr = FS.open('/dev/stderr', 1);
  3304. assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
  3305. assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
  3306. assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
  3307. },ensureErrnoError:function() {
  3308. if (FS.ErrnoError) return;
  3309. FS.ErrnoError = /** @this{Object} */ function ErrnoError(errno, node) {
  3310. this.node = node;
  3311. this.setErrno = /** @this{Object} */ function(errno) {
  3312. this.errno = errno;
  3313. for (var key in ERRNO_CODES) {
  3314. if (ERRNO_CODES[key] === errno) {
  3315. this.code = key;
  3316. break;
  3317. }
  3318. }
  3319. };
  3320. this.setErrno(errno);
  3321. this.message = ERRNO_MESSAGES[errno];
  3322. // Try to get a maximally helpful stack trace. On Node.js, getting Error.stack
  3323. // now ensures it shows what we want.
  3324. if (this.stack) {
  3325. // Define the stack property for Node.js 4, which otherwise errors on the next line.
  3326. Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true });
  3327. this.stack = demangleAll(this.stack);
  3328. }
  3329. };
  3330. FS.ErrnoError.prototype = new Error();
  3331. FS.ErrnoError.prototype.constructor = FS.ErrnoError;
  3332. // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
  3333. [44].forEach(function(code) {
  3334. FS.genericErrors[code] = new FS.ErrnoError(code);
  3335. FS.genericErrors[code].stack = '<generic error, no stack>';
  3336. });
  3337. },staticInit:function() {
  3338. FS.ensureErrnoError();
  3339. FS.nameTable = new Array(4096);
  3340. FS.mount(MEMFS, {}, '/');
  3341. FS.createDefaultDirectories();
  3342. FS.createDefaultDevices();
  3343. FS.createSpecialDirectories();
  3344. FS.filesystems = {
  3345. 'MEMFS': MEMFS,
  3346. };
  3347. },init:function(input, output, error) {
  3348. assert(!FS.init.initialized, 'FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)');
  3349. FS.init.initialized = true;
  3350. FS.ensureErrnoError();
  3351. // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
  3352. Module['stdin'] = input || Module['stdin'];
  3353. Module['stdout'] = output || Module['stdout'];
  3354. Module['stderr'] = error || Module['stderr'];
  3355. FS.createStandardStreams();
  3356. },quit:function() {
  3357. FS.init.initialized = false;
  3358. // force-flush all streams, so we get musl std streams printed out
  3359. _fflush(0);
  3360. // close all of our streams
  3361. for (var i = 0; i < FS.streams.length; i++) {
  3362. var stream = FS.streams[i];
  3363. if (!stream) {
  3364. continue;
  3365. }
  3366. FS.close(stream);
  3367. }
  3368. },getMode:function(canRead, canWrite) {
  3369. var mode = 0;
  3370. if (canRead) mode |= 292 | 73;
  3371. if (canWrite) mode |= 146;
  3372. return mode;
  3373. },findObject:function(path, dontResolveLastLink) {
  3374. var ret = FS.analyzePath(path, dontResolveLastLink);
  3375. if (ret.exists) {
  3376. return ret.object;
  3377. } else {
  3378. return null;
  3379. }
  3380. },analyzePath:function(path, dontResolveLastLink) {
  3381. // operate from within the context of the symlink's target
  3382. try {
  3383. var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  3384. path = lookup.path;
  3385. } catch (e) {
  3386. }
  3387. var ret = {
  3388. isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
  3389. parentExists: false, parentPath: null, parentObject: null
  3390. };
  3391. try {
  3392. var lookup = FS.lookupPath(path, { parent: true });
  3393. ret.parentExists = true;
  3394. ret.parentPath = lookup.path;
  3395. ret.parentObject = lookup.node;
  3396. ret.name = PATH.basename(path);
  3397. lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  3398. ret.exists = true;
  3399. ret.path = lookup.path;
  3400. ret.object = lookup.node;
  3401. ret.name = lookup.node.name;
  3402. ret.isRoot = lookup.path === '/';
  3403. } catch (e) {
  3404. ret.error = e.errno;
  3405. };
  3406. return ret;
  3407. },createPath:function(parent, path, canRead, canWrite) {
  3408. parent = typeof parent === 'string' ? parent : FS.getPath(parent);
  3409. var parts = path.split('/').reverse();
  3410. while (parts.length) {
  3411. var part = parts.pop();
  3412. if (!part) continue;
  3413. var current = PATH.join2(parent, part);
  3414. try {
  3415. FS.mkdir(current);
  3416. } catch (e) {
  3417. // ignore EEXIST
  3418. }
  3419. parent = current;
  3420. }
  3421. return current;
  3422. },createFile:function(parent, name, properties, canRead, canWrite) {
  3423. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3424. var mode = FS.getMode(canRead, canWrite);
  3425. return FS.create(path, mode);
  3426. },createDataFile:function(parent, name, data, canRead, canWrite, canOwn) {
  3427. var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
  3428. var mode = FS.getMode(canRead, canWrite);
  3429. var node = FS.create(path, mode);
  3430. if (data) {
  3431. if (typeof data === 'string') {
  3432. var arr = new Array(data.length);
  3433. for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
  3434. data = arr;
  3435. }
  3436. // make sure we can write to the file
  3437. FS.chmod(node, mode | 146);
  3438. var stream = FS.open(node, 577);
  3439. FS.write(stream, data, 0, data.length, 0, canOwn);
  3440. FS.close(stream);
  3441. FS.chmod(node, mode);
  3442. }
  3443. return node;
  3444. },createDevice:function(parent, name, input, output) {
  3445. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  3446. var mode = FS.getMode(!!input, !!output);
  3447. if (!FS.createDevice.major) FS.createDevice.major = 64;
  3448. var dev = FS.makedev(FS.createDevice.major++, 0);
  3449. // Create a fake device that a set of stream ops to emulate
  3450. // the old behavior.
  3451. FS.registerDevice(dev, {
  3452. open: function(stream) {
  3453. stream.seekable = false;
  3454. },
  3455. close: function(stream) {
  3456. // flush any pending line data
  3457. if (output && output.buffer && output.buffer.length) {
  3458. output(10);
  3459. }
  3460. },
  3461. read: function(stream, buffer, offset, length, pos /* ignored */) {
  3462. var bytesRead = 0;
  3463. for (var i = 0; i < length; i++) {
  3464. var result;
  3465. try {
  3466. result = input();
  3467. } catch (e) {
  3468. throw new FS.ErrnoError(29);
  3469. }
  3470. if (result === undefined && bytesRead === 0) {
  3471. throw new FS.ErrnoError(6);
  3472. }
  3473. if (result === null || result === undefined) break;
  3474. bytesRead++;
  3475. buffer[offset+i] = result;
  3476. }
  3477. if (bytesRead) {
  3478. stream.node.timestamp = Date.now();
  3479. }
  3480. return bytesRead;
  3481. },
  3482. write: function(stream, buffer, offset, length, pos) {
  3483. for (var i = 0; i < length; i++) {
  3484. try {
  3485. output(buffer[offset+i]);
  3486. } catch (e) {
  3487. throw new FS.ErrnoError(29);
  3488. }
  3489. }
  3490. if (length) {
  3491. stream.node.timestamp = Date.now();
  3492. }
  3493. return i;
  3494. }
  3495. });
  3496. return FS.mkdev(path, mode, dev);
  3497. },forceLoadFile:function(obj) {
  3498. if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
  3499. if (typeof XMLHttpRequest !== 'undefined') {
  3500. 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.");
  3501. } else if (read_) {
  3502. // Command-line.
  3503. try {
  3504. // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
  3505. // read() will try to parse UTF8.
  3506. obj.contents = intArrayFromString(read_(obj.url), true);
  3507. obj.usedBytes = obj.contents.length;
  3508. } catch (e) {
  3509. throw new FS.ErrnoError(29);
  3510. }
  3511. } else {
  3512. throw new Error('Cannot load without read() or XMLHttpRequest.');
  3513. }
  3514. },createLazyFile:function(parent, name, url, canRead, canWrite) {
  3515. // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
  3516. /** @constructor */
  3517. function LazyUint8Array() {
  3518. this.lengthKnown = false;
  3519. this.chunks = []; // Loaded chunks. Index is the chunk number
  3520. }
  3521. LazyUint8Array.prototype.get = /** @this{Object} */ function LazyUint8Array_get(idx) {
  3522. if (idx > this.length-1 || idx < 0) {
  3523. return undefined;
  3524. }
  3525. var chunkOffset = idx % this.chunkSize;
  3526. var chunkNum = (idx / this.chunkSize)|0;
  3527. return this.getter(chunkNum)[chunkOffset];
  3528. };
  3529. LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
  3530. this.getter = getter;
  3531. };
  3532. LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
  3533. // Find length
  3534. var xhr = new XMLHttpRequest();
  3535. xhr.open('HEAD', url, false);
  3536. xhr.send(null);
  3537. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3538. var datalength = Number(xhr.getResponseHeader("Content-length"));
  3539. var header;
  3540. var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
  3541. var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
  3542. var chunkSize = 1024*1024; // Chunk size in bytes
  3543. if (!hasByteServing) chunkSize = datalength;
  3544. // Function to get a range from the remote URL.
  3545. var doXHR = (function(from, to) {
  3546. if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
  3547. if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
  3548. // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
  3549. var xhr = new XMLHttpRequest();
  3550. xhr.open('GET', url, false);
  3551. if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
  3552. // Some hints to the browser that we want binary data.
  3553. if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
  3554. if (xhr.overrideMimeType) {
  3555. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  3556. }
  3557. xhr.send(null);
  3558. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3559. if (xhr.response !== undefined) {
  3560. return new Uint8Array(/** @type{Array<number>} */(xhr.response || []));
  3561. } else {
  3562. return intArrayFromString(xhr.responseText || '', true);
  3563. }
  3564. });
  3565. var lazyArray = this;
  3566. lazyArray.setDataGetter(function(chunkNum) {
  3567. var start = chunkNum * chunkSize;
  3568. var end = (chunkNum+1) * chunkSize - 1; // including this byte
  3569. end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
  3570. if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
  3571. lazyArray.chunks[chunkNum] = doXHR(start, end);
  3572. }
  3573. if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
  3574. return lazyArray.chunks[chunkNum];
  3575. });
  3576. if (usesGzip || !datalength) {
  3577. // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
  3578. chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
  3579. datalength = this.getter(0).length;
  3580. chunkSize = datalength;
  3581. out("LazyFiles on gzip forces download of the whole file when length is accessed");
  3582. }
  3583. this._length = datalength;
  3584. this._chunkSize = chunkSize;
  3585. this.lengthKnown = true;
  3586. };
  3587. if (typeof XMLHttpRequest !== 'undefined') {
  3588. if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
  3589. var lazyArray = new LazyUint8Array();
  3590. Object.defineProperties(lazyArray, {
  3591. length: {
  3592. get: /** @this{Object} */ function() {
  3593. if (!this.lengthKnown) {
  3594. this.cacheLength();
  3595. }
  3596. return this._length;
  3597. }
  3598. },
  3599. chunkSize: {
  3600. get: /** @this{Object} */ function() {
  3601. if (!this.lengthKnown) {
  3602. this.cacheLength();
  3603. }
  3604. return this._chunkSize;
  3605. }
  3606. }
  3607. });
  3608. var properties = { isDevice: false, contents: lazyArray };
  3609. } else {
  3610. var properties = { isDevice: false, url: url };
  3611. }
  3612. var node = FS.createFile(parent, name, properties, canRead, canWrite);
  3613. // This is a total hack, but I want to get this lazy file code out of the
  3614. // core of MEMFS. If we want to keep this lazy file concept I feel it should
  3615. // be its own thin LAZYFS proxying calls to MEMFS.
  3616. if (properties.contents) {
  3617. node.contents = properties.contents;
  3618. } else if (properties.url) {
  3619. node.contents = null;
  3620. node.url = properties.url;
  3621. }
  3622. // Add a function that defers querying the file size until it is asked the first time.
  3623. Object.defineProperties(node, {
  3624. usedBytes: {
  3625. get: /** @this {FSNode} */ function() { return this.contents.length; }
  3626. }
  3627. });
  3628. // override each stream op with one that tries to force load the lazy file first
  3629. var stream_ops = {};
  3630. var keys = Object.keys(node.stream_ops);
  3631. keys.forEach(function(key) {
  3632. var fn = node.stream_ops[key];
  3633. stream_ops[key] = function forceLoadLazyFile() {
  3634. FS.forceLoadFile(node);
  3635. return fn.apply(null, arguments);
  3636. };
  3637. });
  3638. // use a custom read function
  3639. stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
  3640. FS.forceLoadFile(node);
  3641. var contents = stream.node.contents;
  3642. if (position >= contents.length)
  3643. return 0;
  3644. var size = Math.min(contents.length - position, length);
  3645. assert(size >= 0);
  3646. if (contents.slice) { // normal array
  3647. for (var i = 0; i < size; i++) {
  3648. buffer[offset + i] = contents[position + i];
  3649. }
  3650. } else {
  3651. for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
  3652. buffer[offset + i] = contents.get(position + i);
  3653. }
  3654. }
  3655. return size;
  3656. };
  3657. node.stream_ops = stream_ops;
  3658. return node;
  3659. },createPreloadedFile:function(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
  3660. Browser.init(); // XXX perhaps this method should move onto Browser?
  3661. // TODO we should allow people to just pass in a complete filename instead
  3662. // of parent and name being that we just join them anyways
  3663. var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
  3664. var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
  3665. function processData(byteArray) {
  3666. function finish(byteArray) {
  3667. if (preFinish) preFinish();
  3668. if (!dontCreateFile) {
  3669. FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
  3670. }
  3671. if (onload) onload();
  3672. removeRunDependency(dep);
  3673. }
  3674. var handled = false;
  3675. Module['preloadPlugins'].forEach(function(plugin) {
  3676. if (handled) return;
  3677. if (plugin['canHandle'](fullname)) {
  3678. plugin['handle'](byteArray, fullname, finish, function() {
  3679. if (onerror) onerror();
  3680. removeRunDependency(dep);
  3681. });
  3682. handled = true;
  3683. }
  3684. });
  3685. if (!handled) finish(byteArray);
  3686. }
  3687. addRunDependency(dep);
  3688. if (typeof url == 'string') {
  3689. asyncLoad(url, function(byteArray) {
  3690. processData(byteArray);
  3691. }, onerror);
  3692. } else {
  3693. processData(url);
  3694. }
  3695. },indexedDB:function() {
  3696. return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  3697. },DB_NAME:function() {
  3698. return 'EM_FS_' + window.location.pathname;
  3699. },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function(paths, onload, onerror) {
  3700. onload = onload || function(){};
  3701. onerror = onerror || function(){};
  3702. var indexedDB = FS.indexedDB();
  3703. try {
  3704. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3705. } catch (e) {
  3706. return onerror(e);
  3707. }
  3708. openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
  3709. out('creating db');
  3710. var db = openRequest.result;
  3711. db.createObjectStore(FS.DB_STORE_NAME);
  3712. };
  3713. openRequest.onsuccess = function openRequest_onsuccess() {
  3714. var db = openRequest.result;
  3715. var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
  3716. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3717. var ok = 0, fail = 0, total = paths.length;
  3718. function finish() {
  3719. if (fail == 0) onload(); else onerror();
  3720. }
  3721. paths.forEach(function(path) {
  3722. var putRequest = files.put(FS.analyzePath(path).object.contents, path);
  3723. putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
  3724. putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
  3725. });
  3726. transaction.onerror = onerror;
  3727. };
  3728. openRequest.onerror = onerror;
  3729. },loadFilesFromDB:function(paths, onload, onerror) {
  3730. onload = onload || function(){};
  3731. onerror = onerror || function(){};
  3732. var indexedDB = FS.indexedDB();
  3733. try {
  3734. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3735. } catch (e) {
  3736. return onerror(e);
  3737. }
  3738. openRequest.onupgradeneeded = onerror; // no database to load from
  3739. openRequest.onsuccess = function openRequest_onsuccess() {
  3740. var db = openRequest.result;
  3741. try {
  3742. var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
  3743. } catch(e) {
  3744. onerror(e);
  3745. return;
  3746. }
  3747. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3748. var ok = 0, fail = 0, total = paths.length;
  3749. function finish() {
  3750. if (fail == 0) onload(); else onerror();
  3751. }
  3752. paths.forEach(function(path) {
  3753. var getRequest = files.get(path);
  3754. getRequest.onsuccess = function getRequest_onsuccess() {
  3755. if (FS.analyzePath(path).exists) {
  3756. FS.unlink(path);
  3757. }
  3758. FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
  3759. ok++;
  3760. if (ok + fail == total) finish();
  3761. };
  3762. getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
  3763. });
  3764. transaction.onerror = onerror;
  3765. };
  3766. openRequest.onerror = onerror;
  3767. },absolutePath:function() {
  3768. abort('FS.absolutePath has been removed; use PATH_FS.resolve instead');
  3769. },createFolder:function() {
  3770. abort('FS.createFolder has been removed; use FS.mkdir instead');
  3771. },createLink:function() {
  3772. abort('FS.createLink has been removed; use FS.symlink instead');
  3773. },joinPath:function() {
  3774. abort('FS.joinPath has been removed; use PATH.join instead');
  3775. },mmapAlloc:function() {
  3776. abort('FS.mmapAlloc has been replaced by the top level function mmapAlloc');
  3777. },standardizePath:function() {
  3778. abort('FS.standardizePath has been removed; use PATH.normalize instead');
  3779. }};
  3780. var SYSCALLS = {mappings:{},DEFAULT_POLLMASK:5,calculateAt:function(dirfd, path, allowEmpty) {
  3781. if (path[0] === '/') {
  3782. return path;
  3783. }
  3784. // relative path
  3785. var dir;
  3786. if (dirfd === -100) {
  3787. dir = FS.cwd();
  3788. } else {
  3789. var dirstream = FS.getStream(dirfd);
  3790. if (!dirstream) throw new FS.ErrnoError(8);
  3791. dir = dirstream.path;
  3792. }
  3793. if (path.length == 0) {
  3794. if (!allowEmpty) {
  3795. throw new FS.ErrnoError(44);;
  3796. }
  3797. return dir;
  3798. }
  3799. return PATH.join2(dir, path);
  3800. },doStat:function(func, path, buf) {
  3801. try {
  3802. var stat = func(path);
  3803. } catch (e) {
  3804. if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
  3805. // an error occurred while trying to look up the path; we should just report ENOTDIR
  3806. return -54;
  3807. }
  3808. throw e;
  3809. }
  3810. HEAP32[((buf)>>2)] = stat.dev;
  3811. HEAP32[(((buf)+(4))>>2)] = 0;
  3812. HEAP32[(((buf)+(8))>>2)] = stat.ino;
  3813. HEAP32[(((buf)+(12))>>2)] = stat.mode;
  3814. HEAP32[(((buf)+(16))>>2)] = stat.nlink;
  3815. HEAP32[(((buf)+(20))>>2)] = stat.uid;
  3816. HEAP32[(((buf)+(24))>>2)] = stat.gid;
  3817. HEAP32[(((buf)+(28))>>2)] = stat.rdev;
  3818. HEAP32[(((buf)+(32))>>2)] = 0;
  3819. (tempI64 = [stat.size>>>0,(tempDouble=stat.size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(40))>>2)] = tempI64[0],HEAP32[(((buf)+(44))>>2)] = tempI64[1]);
  3820. HEAP32[(((buf)+(48))>>2)] = 4096;
  3821. HEAP32[(((buf)+(52))>>2)] = stat.blocks;
  3822. HEAP32[(((buf)+(56))>>2)] = (stat.atime.getTime() / 1000)|0;
  3823. HEAP32[(((buf)+(60))>>2)] = 0;
  3824. HEAP32[(((buf)+(64))>>2)] = (stat.mtime.getTime() / 1000)|0;
  3825. HEAP32[(((buf)+(68))>>2)] = 0;
  3826. HEAP32[(((buf)+(72))>>2)] = (stat.ctime.getTime() / 1000)|0;
  3827. HEAP32[(((buf)+(76))>>2)] = 0;
  3828. (tempI64 = [stat.ino>>>0,(tempDouble=stat.ino,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(80))>>2)] = tempI64[0],HEAP32[(((buf)+(84))>>2)] = tempI64[1]);
  3829. return 0;
  3830. },doMsync:function(addr, stream, len, flags, offset) {
  3831. var buffer = HEAPU8.slice(addr, addr + len);
  3832. FS.msync(stream, buffer, offset, len, flags);
  3833. },doMkdir:function(path, mode) {
  3834. // remove a trailing slash, if one - /a/b/ has basename of '', but
  3835. // we want to create b in the context of this function
  3836. path = PATH.normalize(path);
  3837. if (path[path.length-1] === '/') path = path.substr(0, path.length-1);
  3838. FS.mkdir(path, mode, 0);
  3839. return 0;
  3840. },doMknod:function(path, mode, dev) {
  3841. // we don't want this in the JS API as it uses mknod to create all nodes.
  3842. switch (mode & 61440) {
  3843. case 32768:
  3844. case 8192:
  3845. case 24576:
  3846. case 4096:
  3847. case 49152:
  3848. break;
  3849. default: return -28;
  3850. }
  3851. FS.mknod(path, mode, dev);
  3852. return 0;
  3853. },doReadlink:function(path, buf, bufsize) {
  3854. if (bufsize <= 0) return -28;
  3855. var ret = FS.readlink(path);
  3856. var len = Math.min(bufsize, lengthBytesUTF8(ret));
  3857. var endChar = HEAP8[buf+len];
  3858. stringToUTF8(ret, buf, bufsize+1);
  3859. // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
  3860. // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
  3861. HEAP8[buf+len] = endChar;
  3862. return len;
  3863. },doAccess:function(path, amode) {
  3864. if (amode & ~7) {
  3865. // need a valid mode
  3866. return -28;
  3867. }
  3868. var lookup = FS.lookupPath(path, { follow: true });
  3869. var node = lookup.node;
  3870. if (!node) {
  3871. return -44;
  3872. }
  3873. var perms = '';
  3874. if (amode & 4) perms += 'r';
  3875. if (amode & 2) perms += 'w';
  3876. if (amode & 1) perms += 'x';
  3877. if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
  3878. return -2;
  3879. }
  3880. return 0;
  3881. },doDup:function(path, flags, suggestFD) {
  3882. var suggest = FS.getStream(suggestFD);
  3883. if (suggest) FS.close(suggest);
  3884. return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
  3885. },doReadv:function(stream, iov, iovcnt, offset) {
  3886. var ret = 0;
  3887. for (var i = 0; i < iovcnt; i++) {
  3888. var ptr = HEAP32[(((iov)+(i*8))>>2)];
  3889. var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
  3890. var curr = FS.read(stream, HEAP8,ptr, len, offset);
  3891. if (curr < 0) return -1;
  3892. ret += curr;
  3893. if (curr < len) break; // nothing more to read
  3894. }
  3895. return ret;
  3896. },doWritev:function(stream, iov, iovcnt, offset) {
  3897. var ret = 0;
  3898. for (var i = 0; i < iovcnt; i++) {
  3899. var ptr = HEAP32[(((iov)+(i*8))>>2)];
  3900. var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
  3901. var curr = FS.write(stream, HEAP8,ptr, len, offset);
  3902. if (curr < 0) return -1;
  3903. ret += curr;
  3904. }
  3905. return ret;
  3906. },varargs:undefined,get:function() {
  3907. assert(SYSCALLS.varargs != undefined);
  3908. SYSCALLS.varargs += 4;
  3909. var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
  3910. return ret;
  3911. },getStr:function(ptr) {
  3912. var ret = UTF8ToString(ptr);
  3913. return ret;
  3914. },getStreamFromFD:function(fd) {
  3915. var stream = FS.getStream(fd);
  3916. if (!stream) throw new FS.ErrnoError(8);
  3917. return stream;
  3918. },get64:function(low, high) {
  3919. if (low >= 0) assert(high === 0);
  3920. else assert(high === -1);
  3921. return low;
  3922. }};
  3923. function _environ_get(__environ, environ_buf) {
  3924. var bufSize = 0;
  3925. getEnvStrings().forEach(function(string, i) {
  3926. var ptr = environ_buf + bufSize;
  3927. HEAP32[(((__environ)+(i * 4))>>2)] = ptr;
  3928. writeAsciiToMemory(string, ptr);
  3929. bufSize += string.length + 1;
  3930. });
  3931. return 0;
  3932. }
  3933. function _environ_sizes_get(penviron_count, penviron_buf_size) {
  3934. var strings = getEnvStrings();
  3935. HEAP32[((penviron_count)>>2)] = strings.length;
  3936. var bufSize = 0;
  3937. strings.forEach(function(string) {
  3938. bufSize += string.length + 1;
  3939. });
  3940. HEAP32[((penviron_buf_size)>>2)] = bufSize;
  3941. return 0;
  3942. }
  3943. function _fd_close(fd) {try {
  3944. var stream = SYSCALLS.getStreamFromFD(fd);
  3945. FS.close(stream);
  3946. return 0;
  3947. } catch (e) {
  3948. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  3949. return e.errno;
  3950. }
  3951. }
  3952. function _fd_read(fd, iov, iovcnt, pnum) {try {
  3953. var stream = SYSCALLS.getStreamFromFD(fd);
  3954. var num = SYSCALLS.doReadv(stream, iov, iovcnt);
  3955. HEAP32[((pnum)>>2)] = num;
  3956. return 0;
  3957. } catch (e) {
  3958. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  3959. return e.errno;
  3960. }
  3961. }
  3962. function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {try {
  3963. var stream = SYSCALLS.getStreamFromFD(fd);
  3964. var HIGH_OFFSET = 0x100000000; // 2^32
  3965. // use an unsigned operator on low and shift high by 32-bits
  3966. var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0);
  3967. var DOUBLE_LIMIT = 0x20000000000000; // 2^53
  3968. // we also check for equality since DOUBLE_LIMIT + 1 == DOUBLE_LIMIT
  3969. if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) {
  3970. return -61;
  3971. }
  3972. FS.llseek(stream, offset, whence);
  3973. (tempI64 = [stream.position>>>0,(tempDouble=stream.position,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((newOffset)>>2)] = tempI64[0],HEAP32[(((newOffset)+(4))>>2)] = tempI64[1]);
  3974. if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
  3975. return 0;
  3976. } catch (e) {
  3977. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  3978. return e.errno;
  3979. }
  3980. }
  3981. function _fd_write(fd, iov, iovcnt, pnum) {try {
  3982. ;
  3983. var stream = SYSCALLS.getStreamFromFD(fd);
  3984. var num = SYSCALLS.doWritev(stream, iov, iovcnt);
  3985. HEAP32[((pnum)>>2)] = num;
  3986. return 0;
  3987. } catch (e) {
  3988. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  3989. return e.errno;
  3990. }
  3991. }
  3992. function _setTempRet0(val) {
  3993. setTempRet0(val);
  3994. }
  3995. function __isLeapYear(year) {
  3996. return year%4 === 0 && (year%100 !== 0 || year%400 === 0);
  3997. }
  3998. function __arraySum(array, index) {
  3999. var sum = 0;
  4000. for (var i = 0; i <= index; sum += array[i++]) {
  4001. // no-op
  4002. }
  4003. return sum;
  4004. }
  4005. var __MONTH_DAYS_LEAP = [31,29,31,30,31,30,31,31,30,31,30,31];
  4006. var __MONTH_DAYS_REGULAR = [31,28,31,30,31,30,31,31,30,31,30,31];
  4007. function __addDays(date, days) {
  4008. var newDate = new Date(date.getTime());
  4009. while (days > 0) {
  4010. var leap = __isLeapYear(newDate.getFullYear());
  4011. var currentMonth = newDate.getMonth();
  4012. var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth];
  4013. if (days > daysInCurrentMonth-newDate.getDate()) {
  4014. // we spill over to next month
  4015. days -= (daysInCurrentMonth-newDate.getDate()+1);
  4016. newDate.setDate(1);
  4017. if (currentMonth < 11) {
  4018. newDate.setMonth(currentMonth+1)
  4019. } else {
  4020. newDate.setMonth(0);
  4021. newDate.setFullYear(newDate.getFullYear()+1);
  4022. }
  4023. } else {
  4024. // we stay in current month
  4025. newDate.setDate(newDate.getDate()+days);
  4026. return newDate;
  4027. }
  4028. }
  4029. return newDate;
  4030. }
  4031. function _strftime(s, maxsize, format, tm) {
  4032. // size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr);
  4033. // http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
  4034. var tm_zone = HEAP32[(((tm)+(40))>>2)];
  4035. var date = {
  4036. tm_sec: HEAP32[((tm)>>2)],
  4037. tm_min: HEAP32[(((tm)+(4))>>2)],
  4038. tm_hour: HEAP32[(((tm)+(8))>>2)],
  4039. tm_mday: HEAP32[(((tm)+(12))>>2)],
  4040. tm_mon: HEAP32[(((tm)+(16))>>2)],
  4041. tm_year: HEAP32[(((tm)+(20))>>2)],
  4042. tm_wday: HEAP32[(((tm)+(24))>>2)],
  4043. tm_yday: HEAP32[(((tm)+(28))>>2)],
  4044. tm_isdst: HEAP32[(((tm)+(32))>>2)],
  4045. tm_gmtoff: HEAP32[(((tm)+(36))>>2)],
  4046. tm_zone: tm_zone ? UTF8ToString(tm_zone) : ''
  4047. };
  4048. var pattern = UTF8ToString(format);
  4049. // expand format
  4050. var EXPANSION_RULES_1 = {
  4051. '%c': '%a %b %d %H:%M:%S %Y', // Replaced by the locale's appropriate date and time representation - e.g., Mon Aug 3 14:02:01 2013
  4052. '%D': '%m/%d/%y', // Equivalent to %m / %d / %y
  4053. '%F': '%Y-%m-%d', // Equivalent to %Y - %m - %d
  4054. '%h': '%b', // Equivalent to %b
  4055. '%r': '%I:%M:%S %p', // Replaced by the time in a.m. and p.m. notation
  4056. '%R': '%H:%M', // Replaced by the time in 24-hour notation
  4057. '%T': '%H:%M:%S', // Replaced by the time
  4058. '%x': '%m/%d/%y', // Replaced by the locale's appropriate date representation
  4059. '%X': '%H:%M:%S', // Replaced by the locale's appropriate time representation
  4060. // Modified Conversion Specifiers
  4061. '%Ec': '%c', // Replaced by the locale's alternative appropriate date and time representation.
  4062. '%EC': '%C', // Replaced by the name of the base year (period) in the locale's alternative representation.
  4063. '%Ex': '%m/%d/%y', // Replaced by the locale's alternative date representation.
  4064. '%EX': '%H:%M:%S', // Replaced by the locale's alternative time representation.
  4065. '%Ey': '%y', // Replaced by the offset from %EC (year only) in the locale's alternative representation.
  4066. '%EY': '%Y', // Replaced by the full alternative year representation.
  4067. '%Od': '%d', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading zeros if there is any alternative symbol for zero; otherwise, with leading <space> characters.
  4068. '%Oe': '%e', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading <space> characters.
  4069. '%OH': '%H', // Replaced by the hour (24-hour clock) using the locale's alternative numeric symbols.
  4070. '%OI': '%I', // Replaced by the hour (12-hour clock) using the locale's alternative numeric symbols.
  4071. '%Om': '%m', // Replaced by the month using the locale's alternative numeric symbols.
  4072. '%OM': '%M', // Replaced by the minutes using the locale's alternative numeric symbols.
  4073. '%OS': '%S', // Replaced by the seconds using the locale's alternative numeric symbols.
  4074. '%Ou': '%u', // Replaced by the weekday as a number in the locale's alternative representation (Monday=1).
  4075. '%OU': '%U', // Replaced by the week number of the year (Sunday as the first day of the week, rules corresponding to %U ) using the locale's alternative numeric symbols.
  4076. '%OV': '%V', // Replaced by the week number of the year (Monday as the first day of the week, rules corresponding to %V ) using the locale's alternative numeric symbols.
  4077. '%Ow': '%w', // Replaced by the number of the weekday (Sunday=0) using the locale's alternative numeric symbols.
  4078. '%OW': '%W', // Replaced by the week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
  4079. '%Oy': '%y', // Replaced by the year (offset from %C ) using the locale's alternative numeric symbols.
  4080. };
  4081. for (var rule in EXPANSION_RULES_1) {
  4082. pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_1[rule]);
  4083. }
  4084. var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  4085. var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  4086. function leadingSomething(value, digits, character) {
  4087. var str = typeof value === 'number' ? value.toString() : (value || '');
  4088. while (str.length < digits) {
  4089. str = character[0]+str;
  4090. }
  4091. return str;
  4092. }
  4093. function leadingNulls(value, digits) {
  4094. return leadingSomething(value, digits, '0');
  4095. }
  4096. function compareByDay(date1, date2) {
  4097. function sgn(value) {
  4098. return value < 0 ? -1 : (value > 0 ? 1 : 0);
  4099. }
  4100. var compare;
  4101. if ((compare = sgn(date1.getFullYear()-date2.getFullYear())) === 0) {
  4102. if ((compare = sgn(date1.getMonth()-date2.getMonth())) === 0) {
  4103. compare = sgn(date1.getDate()-date2.getDate());
  4104. }
  4105. }
  4106. return compare;
  4107. }
  4108. function getFirstWeekStartDate(janFourth) {
  4109. switch (janFourth.getDay()) {
  4110. case 0: // Sunday
  4111. return new Date(janFourth.getFullYear()-1, 11, 29);
  4112. case 1: // Monday
  4113. return janFourth;
  4114. case 2: // Tuesday
  4115. return new Date(janFourth.getFullYear(), 0, 3);
  4116. case 3: // Wednesday
  4117. return new Date(janFourth.getFullYear(), 0, 2);
  4118. case 4: // Thursday
  4119. return new Date(janFourth.getFullYear(), 0, 1);
  4120. case 5: // Friday
  4121. return new Date(janFourth.getFullYear()-1, 11, 31);
  4122. case 6: // Saturday
  4123. return new Date(janFourth.getFullYear()-1, 11, 30);
  4124. }
  4125. }
  4126. function getWeekBasedYear(date) {
  4127. var thisDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday);
  4128. var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4);
  4129. var janFourthNextYear = new Date(thisDate.getFullYear()+1, 0, 4);
  4130. var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
  4131. var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
  4132. if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) {
  4133. // this date is after the start of the first week of this year
  4134. if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) {
  4135. return thisDate.getFullYear()+1;
  4136. } else {
  4137. return thisDate.getFullYear();
  4138. }
  4139. } else {
  4140. return thisDate.getFullYear()-1;
  4141. }
  4142. }
  4143. var EXPANSION_RULES_2 = {
  4144. '%a': function(date) {
  4145. return WEEKDAYS[date.tm_wday].substring(0,3);
  4146. },
  4147. '%A': function(date) {
  4148. return WEEKDAYS[date.tm_wday];
  4149. },
  4150. '%b': function(date) {
  4151. return MONTHS[date.tm_mon].substring(0,3);
  4152. },
  4153. '%B': function(date) {
  4154. return MONTHS[date.tm_mon];
  4155. },
  4156. '%C': function(date) {
  4157. var year = date.tm_year+1900;
  4158. return leadingNulls((year/100)|0,2);
  4159. },
  4160. '%d': function(date) {
  4161. return leadingNulls(date.tm_mday, 2);
  4162. },
  4163. '%e': function(date) {
  4164. return leadingSomething(date.tm_mday, 2, ' ');
  4165. },
  4166. '%g': function(date) {
  4167. // %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year.
  4168. // In this system, weeks begin on a Monday and week 1 of the year is the week that includes
  4169. // January 4th, which is also the week that includes the first Thursday of the year, and
  4170. // is also the first week that contains at least four days in the year.
  4171. // If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of
  4172. // the last week of the preceding year; thus, for Saturday 2nd January 1999,
  4173. // %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th,
  4174. // or 31st is a Monday, it and any following days are part of week 1 of the following year.
  4175. // Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.
  4176. return getWeekBasedYear(date).toString().substring(2);
  4177. },
  4178. '%G': function(date) {
  4179. return getWeekBasedYear(date);
  4180. },
  4181. '%H': function(date) {
  4182. return leadingNulls(date.tm_hour, 2);
  4183. },
  4184. '%I': function(date) {
  4185. var twelveHour = date.tm_hour;
  4186. if (twelveHour == 0) twelveHour = 12;
  4187. else if (twelveHour > 12) twelveHour -= 12;
  4188. return leadingNulls(twelveHour, 2);
  4189. },
  4190. '%j': function(date) {
  4191. // Day of the year (001-366)
  4192. return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon-1), 3);
  4193. },
  4194. '%m': function(date) {
  4195. return leadingNulls(date.tm_mon+1, 2);
  4196. },
  4197. '%M': function(date) {
  4198. return leadingNulls(date.tm_min, 2);
  4199. },
  4200. '%n': function() {
  4201. return '\n';
  4202. },
  4203. '%p': function(date) {
  4204. if (date.tm_hour >= 0 && date.tm_hour < 12) {
  4205. return 'AM';
  4206. } else {
  4207. return 'PM';
  4208. }
  4209. },
  4210. '%S': function(date) {
  4211. return leadingNulls(date.tm_sec, 2);
  4212. },
  4213. '%t': function() {
  4214. return '\t';
  4215. },
  4216. '%u': function(date) {
  4217. return date.tm_wday || 7;
  4218. },
  4219. '%U': function(date) {
  4220. // Replaced by the week number of the year as a decimal number [00,53].
  4221. // The first Sunday of January is the first day of week 1;
  4222. // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
  4223. var janFirst = new Date(date.tm_year+1900, 0, 1);
  4224. var firstSunday = janFirst.getDay() === 0 ? janFirst : __addDays(janFirst, 7-janFirst.getDay());
  4225. var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday);
  4226. // is target date after the first Sunday?
  4227. if (compareByDay(firstSunday, endDate) < 0) {
  4228. // calculate difference in days between first Sunday and endDate
  4229. var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31;
  4230. var firstSundayUntilEndJanuary = 31-firstSunday.getDate();
  4231. var days = firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();
  4232. return leadingNulls(Math.ceil(days/7), 2);
  4233. }
  4234. return compareByDay(firstSunday, janFirst) === 0 ? '01': '00';
  4235. },
  4236. '%V': function(date) {
  4237. // Replaced by the week number of the year (Monday as the first day of the week)
  4238. // as a decimal number [01,53]. If the week containing 1 January has four
  4239. // or more days in the new year, then it is considered week 1.
  4240. // Otherwise, it is the last week of the previous year, and the next week is week 1.
  4241. // Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]
  4242. var janFourthThisYear = new Date(date.tm_year+1900, 0, 4);
  4243. var janFourthNextYear = new Date(date.tm_year+1901, 0, 4);
  4244. var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
  4245. var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
  4246. var endDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday);
  4247. if (compareByDay(endDate, firstWeekStartThisYear) < 0) {
  4248. // if given date is before this years first week, then it belongs to the 53rd week of last year
  4249. return '53';
  4250. }
  4251. if (compareByDay(firstWeekStartNextYear, endDate) <= 0) {
  4252. // if given date is after next years first week, then it belongs to the 01th week of next year
  4253. return '01';
  4254. }
  4255. // given date is in between CW 01..53 of this calendar year
  4256. var daysDifference;
  4257. if (firstWeekStartThisYear.getFullYear() < date.tm_year+1900) {
  4258. // first CW of this year starts last year
  4259. daysDifference = date.tm_yday+32-firstWeekStartThisYear.getDate()
  4260. } else {
  4261. // first CW of this year starts this year
  4262. daysDifference = date.tm_yday+1-firstWeekStartThisYear.getDate();
  4263. }
  4264. return leadingNulls(Math.ceil(daysDifference/7), 2);
  4265. },
  4266. '%w': function(date) {
  4267. return date.tm_wday;
  4268. },
  4269. '%W': function(date) {
  4270. // Replaced by the week number of the year as a decimal number [00,53].
  4271. // The first Monday of January is the first day of week 1;
  4272. // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
  4273. var janFirst = new Date(date.tm_year, 0, 1);
  4274. var firstMonday = janFirst.getDay() === 1 ? janFirst : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7-janFirst.getDay()+1);
  4275. var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday);
  4276. // is target date after the first Monday?
  4277. if (compareByDay(firstMonday, endDate) < 0) {
  4278. var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31;
  4279. var firstMondayUntilEndJanuary = 31-firstMonday.getDate();
  4280. var days = firstMondayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();
  4281. return leadingNulls(Math.ceil(days/7), 2);
  4282. }
  4283. return compareByDay(firstMonday, janFirst) === 0 ? '01': '00';
  4284. },
  4285. '%y': function(date) {
  4286. // Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]
  4287. return (date.tm_year+1900).toString().substring(2);
  4288. },
  4289. '%Y': function(date) {
  4290. // Replaced by the year as a decimal number (for example, 1997). [ tm_year]
  4291. return date.tm_year+1900;
  4292. },
  4293. '%z': function(date) {
  4294. // Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ).
  4295. // For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich).
  4296. var off = date.tm_gmtoff;
  4297. var ahead = off >= 0;
  4298. off = Math.abs(off) / 60;
  4299. // convert from minutes into hhmm format (which means 60 minutes = 100 units)
  4300. off = (off / 60)*100 + (off % 60);
  4301. return (ahead ? '+' : '-') + String("0000" + off).slice(-4);
  4302. },
  4303. '%Z': function(date) {
  4304. return date.tm_zone;
  4305. },
  4306. '%%': function() {
  4307. return '%';
  4308. }
  4309. };
  4310. for (var rule in EXPANSION_RULES_2) {
  4311. if (pattern.includes(rule)) {
  4312. pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_2[rule](date));
  4313. }
  4314. }
  4315. var bytes = intArrayFromString(pattern, false);
  4316. if (bytes.length > maxsize) {
  4317. return 0;
  4318. }
  4319. writeArrayToMemory(bytes, s);
  4320. return bytes.length-1;
  4321. }
  4322. function _strftime_l(s, maxsize, format, tm) {
  4323. return _strftime(s, maxsize, format, tm); // no locale support yet
  4324. }
  4325. var FSNode = /** @constructor */ function(parent, name, mode, rdev) {
  4326. if (!parent) {
  4327. parent = this; // root node sets parent to itself
  4328. }
  4329. this.parent = parent;
  4330. this.mount = parent.mount;
  4331. this.mounted = null;
  4332. this.id = FS.nextInode++;
  4333. this.name = name;
  4334. this.mode = mode;
  4335. this.node_ops = {};
  4336. this.stream_ops = {};
  4337. this.rdev = rdev;
  4338. };
  4339. var readMode = 292/*292*/ | 73/*73*/;
  4340. var writeMode = 146/*146*/;
  4341. Object.defineProperties(FSNode.prototype, {
  4342. read: {
  4343. get: /** @this{FSNode} */function() {
  4344. return (this.mode & readMode) === readMode;
  4345. },
  4346. set: /** @this{FSNode} */function(val) {
  4347. val ? this.mode |= readMode : this.mode &= ~readMode;
  4348. }
  4349. },
  4350. write: {
  4351. get: /** @this{FSNode} */function() {
  4352. return (this.mode & writeMode) === writeMode;
  4353. },
  4354. set: /** @this{FSNode} */function(val) {
  4355. val ? this.mode |= writeMode : this.mode &= ~writeMode;
  4356. }
  4357. },
  4358. isFolder: {
  4359. get: /** @this{FSNode} */function() {
  4360. return FS.isDir(this.mode);
  4361. }
  4362. },
  4363. isDevice: {
  4364. get: /** @this{FSNode} */function() {
  4365. return FS.isChrdev(this.mode);
  4366. }
  4367. }
  4368. });
  4369. FS.FSNode = FSNode;
  4370. FS.staticInit();;
  4371. ERRNO_CODES = {
  4372. 'EPERM': 63,
  4373. 'ENOENT': 44,
  4374. 'ESRCH': 71,
  4375. 'EINTR': 27,
  4376. 'EIO': 29,
  4377. 'ENXIO': 60,
  4378. 'E2BIG': 1,
  4379. 'ENOEXEC': 45,
  4380. 'EBADF': 8,
  4381. 'ECHILD': 12,
  4382. 'EAGAIN': 6,
  4383. 'EWOULDBLOCK': 6,
  4384. 'ENOMEM': 48,
  4385. 'EACCES': 2,
  4386. 'EFAULT': 21,
  4387. 'ENOTBLK': 105,
  4388. 'EBUSY': 10,
  4389. 'EEXIST': 20,
  4390. 'EXDEV': 75,
  4391. 'ENODEV': 43,
  4392. 'ENOTDIR': 54,
  4393. 'EISDIR': 31,
  4394. 'EINVAL': 28,
  4395. 'ENFILE': 41,
  4396. 'EMFILE': 33,
  4397. 'ENOTTY': 59,
  4398. 'ETXTBSY': 74,
  4399. 'EFBIG': 22,
  4400. 'ENOSPC': 51,
  4401. 'ESPIPE': 70,
  4402. 'EROFS': 69,
  4403. 'EMLINK': 34,
  4404. 'EPIPE': 64,
  4405. 'EDOM': 18,
  4406. 'ERANGE': 68,
  4407. 'ENOMSG': 49,
  4408. 'EIDRM': 24,
  4409. 'ECHRNG': 106,
  4410. 'EL2NSYNC': 156,
  4411. 'EL3HLT': 107,
  4412. 'EL3RST': 108,
  4413. 'ELNRNG': 109,
  4414. 'EUNATCH': 110,
  4415. 'ENOCSI': 111,
  4416. 'EL2HLT': 112,
  4417. 'EDEADLK': 16,
  4418. 'ENOLCK': 46,
  4419. 'EBADE': 113,
  4420. 'EBADR': 114,
  4421. 'EXFULL': 115,
  4422. 'ENOANO': 104,
  4423. 'EBADRQC': 103,
  4424. 'EBADSLT': 102,
  4425. 'EDEADLOCK': 16,
  4426. 'EBFONT': 101,
  4427. 'ENOSTR': 100,
  4428. 'ENODATA': 116,
  4429. 'ETIME': 117,
  4430. 'ENOSR': 118,
  4431. 'ENONET': 119,
  4432. 'ENOPKG': 120,
  4433. 'EREMOTE': 121,
  4434. 'ENOLINK': 47,
  4435. 'EADV': 122,
  4436. 'ESRMNT': 123,
  4437. 'ECOMM': 124,
  4438. 'EPROTO': 65,
  4439. 'EMULTIHOP': 36,
  4440. 'EDOTDOT': 125,
  4441. 'EBADMSG': 9,
  4442. 'ENOTUNIQ': 126,
  4443. 'EBADFD': 127,
  4444. 'EREMCHG': 128,
  4445. 'ELIBACC': 129,
  4446. 'ELIBBAD': 130,
  4447. 'ELIBSCN': 131,
  4448. 'ELIBMAX': 132,
  4449. 'ELIBEXEC': 133,
  4450. 'ENOSYS': 52,
  4451. 'ENOTEMPTY': 55,
  4452. 'ENAMETOOLONG': 37,
  4453. 'ELOOP': 32,
  4454. 'EOPNOTSUPP': 138,
  4455. 'EPFNOSUPPORT': 139,
  4456. 'ECONNRESET': 15,
  4457. 'ENOBUFS': 42,
  4458. 'EAFNOSUPPORT': 5,
  4459. 'EPROTOTYPE': 67,
  4460. 'ENOTSOCK': 57,
  4461. 'ENOPROTOOPT': 50,
  4462. 'ESHUTDOWN': 140,
  4463. 'ECONNREFUSED': 14,
  4464. 'EADDRINUSE': 3,
  4465. 'ECONNABORTED': 13,
  4466. 'ENETUNREACH': 40,
  4467. 'ENETDOWN': 38,
  4468. 'ETIMEDOUT': 73,
  4469. 'EHOSTDOWN': 142,
  4470. 'EHOSTUNREACH': 23,
  4471. 'EINPROGRESS': 26,
  4472. 'EALREADY': 7,
  4473. 'EDESTADDRREQ': 17,
  4474. 'EMSGSIZE': 35,
  4475. 'EPROTONOSUPPORT': 66,
  4476. 'ESOCKTNOSUPPORT': 137,
  4477. 'EADDRNOTAVAIL': 4,
  4478. 'ENETRESET': 39,
  4479. 'EISCONN': 30,
  4480. 'ENOTCONN': 53,
  4481. 'ETOOMANYREFS': 141,
  4482. 'EUSERS': 136,
  4483. 'EDQUOT': 19,
  4484. 'ESTALE': 72,
  4485. 'ENOTSUP': 138,
  4486. 'ENOMEDIUM': 148,
  4487. 'EILSEQ': 25,
  4488. 'EOVERFLOW': 61,
  4489. 'ECANCELED': 11,
  4490. 'ENOTRECOVERABLE': 56,
  4491. 'EOWNERDEAD': 62,
  4492. 'ESTRPIPE': 135,
  4493. };;
  4494. var ASSERTIONS = true;
  4495. /** @type {function(string, boolean=, number=)} */
  4496. function intArrayFromString(stringy, dontAddNull, length) {
  4497. var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
  4498. var u8array = new Array(len);
  4499. var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
  4500. if (dontAddNull) u8array.length = numBytesWritten;
  4501. return u8array;
  4502. }
  4503. function intArrayToString(array) {
  4504. var ret = [];
  4505. for (var i = 0; i < array.length; i++) {
  4506. var chr = array[i];
  4507. if (chr > 0xFF) {
  4508. if (ASSERTIONS) {
  4509. assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
  4510. }
  4511. chr &= 0xFF;
  4512. }
  4513. ret.push(String.fromCharCode(chr));
  4514. }
  4515. return ret.join('');
  4516. }
  4517. var asmLibraryArg = {
  4518. "__cxa_allocate_exception": ___cxa_allocate_exception,
  4519. "__cxa_throw": ___cxa_throw,
  4520. "abort": _abort,
  4521. "emscripten_memcpy_big": _emscripten_memcpy_big,
  4522. "emscripten_resize_heap": _emscripten_resize_heap,
  4523. "environ_get": _environ_get,
  4524. "environ_sizes_get": _environ_sizes_get,
  4525. "fd_close": _fd_close,
  4526. "fd_read": _fd_read,
  4527. "fd_seek": _fd_seek,
  4528. "fd_write": _fd_write,
  4529. "setTempRet0": _setTempRet0,
  4530. "strftime_l": _strftime_l
  4531. };
  4532. var asm = createWasm();
  4533. /** @type {function(...*):?} */
  4534. var ___wasm_call_ctors = Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors");
  4535. /** @type {function(...*):?} */
  4536. var _Encoder_new = Module["_Encoder_new"] = createExportWrapper("Encoder_new");
  4537. /** @type {function(...*):?} */
  4538. var _Encoder_delete = Module["_Encoder_delete"] = createExportWrapper("Encoder_delete");
  4539. /** @type {function(...*):?} */
  4540. var _Encoder_input = Module["_Encoder_input"] = createExportWrapper("Encoder_input");
  4541. /** @type {function(...*):?} */
  4542. var _Encoder_output = Module["_Encoder_output"] = createExportWrapper("Encoder_output");
  4543. /** @type {function(...*):?} */
  4544. var _Decoder_new = Module["_Decoder_new"] = createExportWrapper("Decoder_new");
  4545. /** @type {function(...*):?} */
  4546. var _Decoder_delete = Module["_Decoder_delete"] = createExportWrapper("Decoder_delete");
  4547. /** @type {function(...*):?} */
  4548. var _Decoder_input = Module["_Decoder_input"] = createExportWrapper("Decoder_input");
  4549. /** @type {function(...*):?} */
  4550. var _Decoder_output = Module["_Decoder_output"] = createExportWrapper("Decoder_output");
  4551. /** @type {function(...*):?} */
  4552. var _String_size = Module["_String_size"] = createExportWrapper("String_size");
  4553. /** @type {function(...*):?} */
  4554. var _String_new = Module["_String_new"] = createExportWrapper("String_new");
  4555. /** @type {function(...*):?} */
  4556. var _String_data = Module["_String_data"] = createExportWrapper("String_data");
  4557. /** @type {function(...*):?} */
  4558. var _String_delete = Module["_String_delete"] = createExportWrapper("String_delete");
  4559. /** @type {function(...*):?} */
  4560. var _Int16Array_size = Module["_Int16Array_size"] = createExportWrapper("Int16Array_size");
  4561. /** @type {function(...*):?} */
  4562. var _Int16Array_new = Module["_Int16Array_new"] = createExportWrapper("Int16Array_new");
  4563. /** @type {function(...*):?} */
  4564. var _Int16Array_data = Module["_Int16Array_data"] = createExportWrapper("Int16Array_data");
  4565. /** @type {function(...*):?} */
  4566. var _Int16Array_delete = Module["_Int16Array_delete"] = createExportWrapper("Int16Array_delete");
  4567. /** @type {function(...*):?} */
  4568. var _malloc = Module["_malloc"] = createExportWrapper("malloc");
  4569. /** @type {function(...*):?} */
  4570. var _free = Module["_free"] = createExportWrapper("free");
  4571. /** @type {function(...*):?} */
  4572. var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location");
  4573. /** @type {function(...*):?} */
  4574. var _fflush = Module["_fflush"] = createExportWrapper("fflush");
  4575. /** @type {function(...*):?} */
  4576. var _emscripten_stack_init = Module["_emscripten_stack_init"] = function() {
  4577. return (_emscripten_stack_init = Module["_emscripten_stack_init"] = Module["asm"]["emscripten_stack_init"]).apply(null, arguments);
  4578. };
  4579. /** @type {function(...*):?} */
  4580. var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() {
  4581. return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments);
  4582. };
  4583. /** @type {function(...*):?} */
  4584. var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() {
  4585. return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments);
  4586. };
  4587. /** @type {function(...*):?} */
  4588. var stackSave = Module["stackSave"] = createExportWrapper("stackSave");
  4589. /** @type {function(...*):?} */
  4590. var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore");
  4591. /** @type {function(...*):?} */
  4592. var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc");
  4593. /** @type {function(...*):?} */
  4594. var dynCall_viijii = Module["dynCall_viijii"] = createExportWrapper("dynCall_viijii");
  4595. /** @type {function(...*):?} */
  4596. var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji");
  4597. /** @type {function(...*):?} */
  4598. var dynCall_iiiiij = Module["dynCall_iiiiij"] = createExportWrapper("dynCall_iiiiij");
  4599. /** @type {function(...*):?} */
  4600. var dynCall_iiiiijj = Module["dynCall_iiiiijj"] = createExportWrapper("dynCall_iiiiijj");
  4601. /** @type {function(...*):?} */
  4602. var dynCall_iiiiiijj = Module["dynCall_iiiiiijj"] = createExportWrapper("dynCall_iiiiiijj");
  4603. // === Auto-generated postamble setup entry stuff ===
  4604. if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = () => abort("'intArrayFromString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4605. if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = () => abort("'intArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4606. if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = () => abort("'ccall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4607. if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = () => abort("'cwrap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4608. if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = () => abort("'setValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4609. if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = () => abort("'getValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4610. if (!Object.getOwnPropertyDescriptor(Module, "allocate")) Module["allocate"] = () => abort("'allocate' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4611. if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = () => abort("'UTF8ArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4612. if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = () => abort("'UTF8ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4613. if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = () => abort("'stringToUTF8Array' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4614. if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = () => abort("'stringToUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4615. if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = () => abort("'lengthBytesUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4616. if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = () => abort("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4617. if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = () => abort("'addOnPreRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4618. if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = () => abort("'addOnInit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4619. if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = () => abort("'addOnPreMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4620. if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = () => abort("'addOnExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4621. if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = () => abort("'addOnPostRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4622. if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = () => abort("'writeStringToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4623. if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = () => abort("'writeArrayToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4624. if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = () => abort("'writeAsciiToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4625. if (!Object.getOwnPropertyDescriptor(Module, "addRunDependency")) Module["addRunDependency"] = () => abort("'addRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4626. if (!Object.getOwnPropertyDescriptor(Module, "removeRunDependency")) Module["removeRunDependency"] = () => abort("'removeRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4627. if (!Object.getOwnPropertyDescriptor(Module, "FS_createFolder")) Module["FS_createFolder"] = () => abort("'FS_createFolder' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4628. if (!Object.getOwnPropertyDescriptor(Module, "FS_createPath")) Module["FS_createPath"] = () => abort("'FS_createPath' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4629. if (!Object.getOwnPropertyDescriptor(Module, "FS_createDataFile")) Module["FS_createDataFile"] = () => abort("'FS_createDataFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4630. if (!Object.getOwnPropertyDescriptor(Module, "FS_createPreloadedFile")) Module["FS_createPreloadedFile"] = () => abort("'FS_createPreloadedFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4631. if (!Object.getOwnPropertyDescriptor(Module, "FS_createLazyFile")) Module["FS_createLazyFile"] = () => abort("'FS_createLazyFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4632. if (!Object.getOwnPropertyDescriptor(Module, "FS_createLink")) Module["FS_createLink"] = () => abort("'FS_createLink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4633. if (!Object.getOwnPropertyDescriptor(Module, "FS_createDevice")) Module["FS_createDevice"] = () => abort("'FS_createDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4634. if (!Object.getOwnPropertyDescriptor(Module, "FS_unlink")) Module["FS_unlink"] = () => abort("'FS_unlink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
  4635. if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = () => abort("'getLEB' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4636. if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = () => abort("'getFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4637. if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = () => abort("'alignFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4638. if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = () => abort("'registerFunctions' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4639. if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = () => abort("'addFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4640. if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = () => abort("'removeFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4641. if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = () => abort("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4642. if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = () => abort("'prettyPrint' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4643. if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = () => abort("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4644. if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = () => abort("'getCompilerSetting' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4645. if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = () => abort("'print' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4646. if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = () => abort("'printErr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4647. if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = () => abort("'getTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4648. if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = () => abort("'setTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4649. if (!Object.getOwnPropertyDescriptor(Module, "callMain")) Module["callMain"] = () => abort("'callMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4650. if (!Object.getOwnPropertyDescriptor(Module, "abort")) Module["abort"] = () => abort("'abort' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4651. if (!Object.getOwnPropertyDescriptor(Module, "keepRuntimeAlive")) Module["keepRuntimeAlive"] = () => abort("'keepRuntimeAlive' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4652. if (!Object.getOwnPropertyDescriptor(Module, "zeroMemory")) Module["zeroMemory"] = () => abort("'zeroMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4653. if (!Object.getOwnPropertyDescriptor(Module, "stringToNewUTF8")) Module["stringToNewUTF8"] = () => abort("'stringToNewUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4654. if (!Object.getOwnPropertyDescriptor(Module, "setFileTime")) Module["setFileTime"] = () => abort("'setFileTime' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4655. if (!Object.getOwnPropertyDescriptor(Module, "abortOnCannotGrowMemory")) Module["abortOnCannotGrowMemory"] = () => abort("'abortOnCannotGrowMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4656. if (!Object.getOwnPropertyDescriptor(Module, "emscripten_realloc_buffer")) Module["emscripten_realloc_buffer"] = () => abort("'emscripten_realloc_buffer' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4657. if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = () => abort("'ENV' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4658. if (!Object.getOwnPropertyDescriptor(Module, "withStackSave")) Module["withStackSave"] = () => abort("'withStackSave' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4659. if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_CODES")) Module["ERRNO_CODES"] = () => abort("'ERRNO_CODES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4660. if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_MESSAGES")) Module["ERRNO_MESSAGES"] = () => abort("'ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4661. if (!Object.getOwnPropertyDescriptor(Module, "setErrNo")) Module["setErrNo"] = () => abort("'setErrNo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4662. if (!Object.getOwnPropertyDescriptor(Module, "inetPton4")) Module["inetPton4"] = () => abort("'inetPton4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4663. if (!Object.getOwnPropertyDescriptor(Module, "inetNtop4")) Module["inetNtop4"] = () => abort("'inetNtop4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4664. if (!Object.getOwnPropertyDescriptor(Module, "inetPton6")) Module["inetPton6"] = () => abort("'inetPton6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4665. if (!Object.getOwnPropertyDescriptor(Module, "inetNtop6")) Module["inetNtop6"] = () => abort("'inetNtop6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4666. if (!Object.getOwnPropertyDescriptor(Module, "readSockaddr")) Module["readSockaddr"] = () => abort("'readSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4667. if (!Object.getOwnPropertyDescriptor(Module, "writeSockaddr")) Module["writeSockaddr"] = () => abort("'writeSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4668. if (!Object.getOwnPropertyDescriptor(Module, "DNS")) Module["DNS"] = () => abort("'DNS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4669. if (!Object.getOwnPropertyDescriptor(Module, "getHostByName")) Module["getHostByName"] = () => abort("'getHostByName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4670. if (!Object.getOwnPropertyDescriptor(Module, "GAI_ERRNO_MESSAGES")) Module["GAI_ERRNO_MESSAGES"] = () => abort("'GAI_ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4671. if (!Object.getOwnPropertyDescriptor(Module, "Protocols")) Module["Protocols"] = () => abort("'Protocols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4672. if (!Object.getOwnPropertyDescriptor(Module, "Sockets")) Module["Sockets"] = () => abort("'Sockets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4673. if (!Object.getOwnPropertyDescriptor(Module, "getRandomDevice")) Module["getRandomDevice"] = () => abort("'getRandomDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4674. if (!Object.getOwnPropertyDescriptor(Module, "traverseStack")) Module["traverseStack"] = () => abort("'traverseStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4675. if (!Object.getOwnPropertyDescriptor(Module, "convertFrameToPC")) Module["convertFrameToPC"] = () => abort("'convertFrameToPC' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4676. if (!Object.getOwnPropertyDescriptor(Module, "UNWIND_CACHE")) Module["UNWIND_CACHE"] = () => abort("'UNWIND_CACHE' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4677. if (!Object.getOwnPropertyDescriptor(Module, "saveInUnwindCache")) Module["saveInUnwindCache"] = () => abort("'saveInUnwindCache' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4678. if (!Object.getOwnPropertyDescriptor(Module, "convertPCtoSourceLocation")) Module["convertPCtoSourceLocation"] = () => abort("'convertPCtoSourceLocation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4679. if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgsArray")) Module["readAsmConstArgsArray"] = () => abort("'readAsmConstArgsArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4680. if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgs")) Module["readAsmConstArgs"] = () => abort("'readAsmConstArgs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4681. if (!Object.getOwnPropertyDescriptor(Module, "mainThreadEM_ASM")) Module["mainThreadEM_ASM"] = () => abort("'mainThreadEM_ASM' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4682. if (!Object.getOwnPropertyDescriptor(Module, "jstoi_q")) Module["jstoi_q"] = () => abort("'jstoi_q' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4683. if (!Object.getOwnPropertyDescriptor(Module, "jstoi_s")) Module["jstoi_s"] = () => abort("'jstoi_s' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4684. if (!Object.getOwnPropertyDescriptor(Module, "getExecutableName")) Module["getExecutableName"] = () => abort("'getExecutableName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4685. if (!Object.getOwnPropertyDescriptor(Module, "listenOnce")) Module["listenOnce"] = () => abort("'listenOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4686. if (!Object.getOwnPropertyDescriptor(Module, "autoResumeAudioContext")) Module["autoResumeAudioContext"] = () => abort("'autoResumeAudioContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4687. if (!Object.getOwnPropertyDescriptor(Module, "dynCallLegacy")) Module["dynCallLegacy"] = () => abort("'dynCallLegacy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4688. if (!Object.getOwnPropertyDescriptor(Module, "getDynCaller")) Module["getDynCaller"] = () => abort("'getDynCaller' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4689. if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = () => abort("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4690. if (!Object.getOwnPropertyDescriptor(Module, "callRuntimeCallbacks")) Module["callRuntimeCallbacks"] = () => abort("'callRuntimeCallbacks' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4691. if (!Object.getOwnPropertyDescriptor(Module, "wasmTableMirror")) Module["wasmTableMirror"] = () => abort("'wasmTableMirror' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4692. if (!Object.getOwnPropertyDescriptor(Module, "setWasmTableEntry")) Module["setWasmTableEntry"] = () => abort("'setWasmTableEntry' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4693. if (!Object.getOwnPropertyDescriptor(Module, "getWasmTableEntry")) Module["getWasmTableEntry"] = () => abort("'getWasmTableEntry' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4694. if (!Object.getOwnPropertyDescriptor(Module, "handleException")) Module["handleException"] = () => abort("'handleException' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4695. if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePush")) Module["runtimeKeepalivePush"] = () => abort("'runtimeKeepalivePush' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4696. if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePop")) Module["runtimeKeepalivePop"] = () => abort("'runtimeKeepalivePop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4697. if (!Object.getOwnPropertyDescriptor(Module, "callUserCallback")) Module["callUserCallback"] = () => abort("'callUserCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4698. if (!Object.getOwnPropertyDescriptor(Module, "maybeExit")) Module["maybeExit"] = () => abort("'maybeExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4699. if (!Object.getOwnPropertyDescriptor(Module, "safeSetTimeout")) Module["safeSetTimeout"] = () => abort("'safeSetTimeout' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4700. if (!Object.getOwnPropertyDescriptor(Module, "asmjsMangle")) Module["asmjsMangle"] = () => abort("'asmjsMangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4701. if (!Object.getOwnPropertyDescriptor(Module, "asyncLoad")) Module["asyncLoad"] = () => abort("'asyncLoad' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4702. if (!Object.getOwnPropertyDescriptor(Module, "alignMemory")) Module["alignMemory"] = () => abort("'alignMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4703. if (!Object.getOwnPropertyDescriptor(Module, "mmapAlloc")) Module["mmapAlloc"] = () => abort("'mmapAlloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4704. if (!Object.getOwnPropertyDescriptor(Module, "reallyNegative")) Module["reallyNegative"] = () => abort("'reallyNegative' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4705. if (!Object.getOwnPropertyDescriptor(Module, "unSign")) Module["unSign"] = () => abort("'unSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4706. if (!Object.getOwnPropertyDescriptor(Module, "reSign")) Module["reSign"] = () => abort("'reSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4707. if (!Object.getOwnPropertyDescriptor(Module, "formatString")) Module["formatString"] = () => abort("'formatString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4708. if (!Object.getOwnPropertyDescriptor(Module, "PATH")) Module["PATH"] = () => abort("'PATH' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4709. if (!Object.getOwnPropertyDescriptor(Module, "PATH_FS")) Module["PATH_FS"] = () => abort("'PATH_FS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4710. if (!Object.getOwnPropertyDescriptor(Module, "SYSCALLS")) Module["SYSCALLS"] = () => abort("'SYSCALLS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4711. if (!Object.getOwnPropertyDescriptor(Module, "syscallMmap2")) Module["syscallMmap2"] = () => abort("'syscallMmap2' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4712. if (!Object.getOwnPropertyDescriptor(Module, "syscallMunmap")) Module["syscallMunmap"] = () => abort("'syscallMunmap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4713. if (!Object.getOwnPropertyDescriptor(Module, "getSocketFromFD")) Module["getSocketFromFD"] = () => abort("'getSocketFromFD' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4714. if (!Object.getOwnPropertyDescriptor(Module, "getSocketAddress")) Module["getSocketAddress"] = () => abort("'getSocketAddress' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4715. if (!Object.getOwnPropertyDescriptor(Module, "JSEvents")) Module["JSEvents"] = () => abort("'JSEvents' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4716. if (!Object.getOwnPropertyDescriptor(Module, "registerKeyEventCallback")) Module["registerKeyEventCallback"] = () => abort("'registerKeyEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4717. if (!Object.getOwnPropertyDescriptor(Module, "specialHTMLTargets")) Module["specialHTMLTargets"] = () => abort("'specialHTMLTargets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4718. if (!Object.getOwnPropertyDescriptor(Module, "maybeCStringToJsString")) Module["maybeCStringToJsString"] = () => abort("'maybeCStringToJsString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4719. if (!Object.getOwnPropertyDescriptor(Module, "findEventTarget")) Module["findEventTarget"] = () => abort("'findEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4720. if (!Object.getOwnPropertyDescriptor(Module, "findCanvasEventTarget")) Module["findCanvasEventTarget"] = () => abort("'findCanvasEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4721. if (!Object.getOwnPropertyDescriptor(Module, "getBoundingClientRect")) Module["getBoundingClientRect"] = () => abort("'getBoundingClientRect' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4722. if (!Object.getOwnPropertyDescriptor(Module, "fillMouseEventData")) Module["fillMouseEventData"] = () => abort("'fillMouseEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4723. if (!Object.getOwnPropertyDescriptor(Module, "registerMouseEventCallback")) Module["registerMouseEventCallback"] = () => abort("'registerMouseEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4724. if (!Object.getOwnPropertyDescriptor(Module, "registerWheelEventCallback")) Module["registerWheelEventCallback"] = () => abort("'registerWheelEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4725. if (!Object.getOwnPropertyDescriptor(Module, "registerUiEventCallback")) Module["registerUiEventCallback"] = () => abort("'registerUiEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4726. if (!Object.getOwnPropertyDescriptor(Module, "registerFocusEventCallback")) Module["registerFocusEventCallback"] = () => abort("'registerFocusEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4727. if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceOrientationEventData")) Module["fillDeviceOrientationEventData"] = () => abort("'fillDeviceOrientationEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4728. if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceOrientationEventCallback")) Module["registerDeviceOrientationEventCallback"] = () => abort("'registerDeviceOrientationEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4729. if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceMotionEventData")) Module["fillDeviceMotionEventData"] = () => abort("'fillDeviceMotionEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4730. if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceMotionEventCallback")) Module["registerDeviceMotionEventCallback"] = () => abort("'registerDeviceMotionEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4731. if (!Object.getOwnPropertyDescriptor(Module, "screenOrientation")) Module["screenOrientation"] = () => abort("'screenOrientation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4732. if (!Object.getOwnPropertyDescriptor(Module, "fillOrientationChangeEventData")) Module["fillOrientationChangeEventData"] = () => abort("'fillOrientationChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4733. if (!Object.getOwnPropertyDescriptor(Module, "registerOrientationChangeEventCallback")) Module["registerOrientationChangeEventCallback"] = () => abort("'registerOrientationChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4734. if (!Object.getOwnPropertyDescriptor(Module, "fillFullscreenChangeEventData")) Module["fillFullscreenChangeEventData"] = () => abort("'fillFullscreenChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4735. if (!Object.getOwnPropertyDescriptor(Module, "registerFullscreenChangeEventCallback")) Module["registerFullscreenChangeEventCallback"] = () => abort("'registerFullscreenChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4736. if (!Object.getOwnPropertyDescriptor(Module, "registerRestoreOldStyle")) Module["registerRestoreOldStyle"] = () => abort("'registerRestoreOldStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4737. if (!Object.getOwnPropertyDescriptor(Module, "hideEverythingExceptGivenElement")) Module["hideEverythingExceptGivenElement"] = () => abort("'hideEverythingExceptGivenElement' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4738. if (!Object.getOwnPropertyDescriptor(Module, "restoreHiddenElements")) Module["restoreHiddenElements"] = () => abort("'restoreHiddenElements' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4739. if (!Object.getOwnPropertyDescriptor(Module, "setLetterbox")) Module["setLetterbox"] = () => abort("'setLetterbox' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4740. if (!Object.getOwnPropertyDescriptor(Module, "currentFullscreenStrategy")) Module["currentFullscreenStrategy"] = () => abort("'currentFullscreenStrategy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4741. if (!Object.getOwnPropertyDescriptor(Module, "restoreOldWindowedStyle")) Module["restoreOldWindowedStyle"] = () => abort("'restoreOldWindowedStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4742. if (!Object.getOwnPropertyDescriptor(Module, "softFullscreenResizeWebGLRenderTarget")) Module["softFullscreenResizeWebGLRenderTarget"] = () => abort("'softFullscreenResizeWebGLRenderTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4743. if (!Object.getOwnPropertyDescriptor(Module, "doRequestFullscreen")) Module["doRequestFullscreen"] = () => abort("'doRequestFullscreen' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4744. if (!Object.getOwnPropertyDescriptor(Module, "fillPointerlockChangeEventData")) Module["fillPointerlockChangeEventData"] = () => abort("'fillPointerlockChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4745. if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockChangeEventCallback")) Module["registerPointerlockChangeEventCallback"] = () => abort("'registerPointerlockChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4746. if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockErrorEventCallback")) Module["registerPointerlockErrorEventCallback"] = () => abort("'registerPointerlockErrorEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4747. if (!Object.getOwnPropertyDescriptor(Module, "requestPointerLock")) Module["requestPointerLock"] = () => abort("'requestPointerLock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4748. if (!Object.getOwnPropertyDescriptor(Module, "fillVisibilityChangeEventData")) Module["fillVisibilityChangeEventData"] = () => abort("'fillVisibilityChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4749. if (!Object.getOwnPropertyDescriptor(Module, "registerVisibilityChangeEventCallback")) Module["registerVisibilityChangeEventCallback"] = () => abort("'registerVisibilityChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4750. if (!Object.getOwnPropertyDescriptor(Module, "registerTouchEventCallback")) Module["registerTouchEventCallback"] = () => abort("'registerTouchEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4751. if (!Object.getOwnPropertyDescriptor(Module, "fillGamepadEventData")) Module["fillGamepadEventData"] = () => abort("'fillGamepadEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4752. if (!Object.getOwnPropertyDescriptor(Module, "registerGamepadEventCallback")) Module["registerGamepadEventCallback"] = () => abort("'registerGamepadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4753. if (!Object.getOwnPropertyDescriptor(Module, "registerBeforeUnloadEventCallback")) Module["registerBeforeUnloadEventCallback"] = () => abort("'registerBeforeUnloadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4754. if (!Object.getOwnPropertyDescriptor(Module, "fillBatteryEventData")) Module["fillBatteryEventData"] = () => abort("'fillBatteryEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4755. if (!Object.getOwnPropertyDescriptor(Module, "battery")) Module["battery"] = () => abort("'battery' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4756. if (!Object.getOwnPropertyDescriptor(Module, "registerBatteryEventCallback")) Module["registerBatteryEventCallback"] = () => abort("'registerBatteryEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4757. if (!Object.getOwnPropertyDescriptor(Module, "setCanvasElementSize")) Module["setCanvasElementSize"] = () => abort("'setCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4758. if (!Object.getOwnPropertyDescriptor(Module, "getCanvasElementSize")) Module["getCanvasElementSize"] = () => abort("'getCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4759. if (!Object.getOwnPropertyDescriptor(Module, "demangle")) Module["demangle"] = () => abort("'demangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4760. if (!Object.getOwnPropertyDescriptor(Module, "demangleAll")) Module["demangleAll"] = () => abort("'demangleAll' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4761. if (!Object.getOwnPropertyDescriptor(Module, "jsStackTrace")) Module["jsStackTrace"] = () => abort("'jsStackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4762. if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = () => abort("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4763. if (!Object.getOwnPropertyDescriptor(Module, "getEnvStrings")) Module["getEnvStrings"] = () => abort("'getEnvStrings' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4764. if (!Object.getOwnPropertyDescriptor(Module, "checkWasiClock")) Module["checkWasiClock"] = () => abort("'checkWasiClock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4765. if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64")) Module["writeI53ToI64"] = () => abort("'writeI53ToI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4766. if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Clamped")) Module["writeI53ToI64Clamped"] = () => abort("'writeI53ToI64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4767. if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Signaling")) Module["writeI53ToI64Signaling"] = () => abort("'writeI53ToI64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4768. if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Clamped")) Module["writeI53ToU64Clamped"] = () => abort("'writeI53ToU64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4769. if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Signaling")) Module["writeI53ToU64Signaling"] = () => abort("'writeI53ToU64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4770. if (!Object.getOwnPropertyDescriptor(Module, "readI53FromI64")) Module["readI53FromI64"] = () => abort("'readI53FromI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4771. if (!Object.getOwnPropertyDescriptor(Module, "readI53FromU64")) Module["readI53FromU64"] = () => abort("'readI53FromU64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4772. if (!Object.getOwnPropertyDescriptor(Module, "convertI32PairToI53")) Module["convertI32PairToI53"] = () => abort("'convertI32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4773. if (!Object.getOwnPropertyDescriptor(Module, "convertU32PairToI53")) Module["convertU32PairToI53"] = () => abort("'convertU32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4774. if (!Object.getOwnPropertyDescriptor(Module, "setImmediateWrapped")) Module["setImmediateWrapped"] = () => abort("'setImmediateWrapped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4775. if (!Object.getOwnPropertyDescriptor(Module, "clearImmediateWrapped")) Module["clearImmediateWrapped"] = () => abort("'clearImmediateWrapped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4776. if (!Object.getOwnPropertyDescriptor(Module, "polyfillSetImmediate")) Module["polyfillSetImmediate"] = () => abort("'polyfillSetImmediate' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4777. if (!Object.getOwnPropertyDescriptor(Module, "uncaughtExceptionCount")) Module["uncaughtExceptionCount"] = () => abort("'uncaughtExceptionCount' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4778. if (!Object.getOwnPropertyDescriptor(Module, "exceptionLast")) Module["exceptionLast"] = () => abort("'exceptionLast' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4779. if (!Object.getOwnPropertyDescriptor(Module, "exceptionCaught")) Module["exceptionCaught"] = () => abort("'exceptionCaught' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4780. if (!Object.getOwnPropertyDescriptor(Module, "ExceptionInfo")) Module["ExceptionInfo"] = () => abort("'ExceptionInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4781. if (!Object.getOwnPropertyDescriptor(Module, "CatchInfo")) Module["CatchInfo"] = () => abort("'CatchInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4782. if (!Object.getOwnPropertyDescriptor(Module, "exception_addRef")) Module["exception_addRef"] = () => abort("'exception_addRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4783. if (!Object.getOwnPropertyDescriptor(Module, "exception_decRef")) Module["exception_decRef"] = () => abort("'exception_decRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4784. if (!Object.getOwnPropertyDescriptor(Module, "Browser")) Module["Browser"] = () => abort("'Browser' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4785. if (!Object.getOwnPropertyDescriptor(Module, "funcWrappers")) Module["funcWrappers"] = () => abort("'funcWrappers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4786. if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = () => abort("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4787. if (!Object.getOwnPropertyDescriptor(Module, "setMainLoop")) Module["setMainLoop"] = () => abort("'setMainLoop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4788. if (!Object.getOwnPropertyDescriptor(Module, "wget")) Module["wget"] = () => abort("'wget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4789. if (!Object.getOwnPropertyDescriptor(Module, "FS")) Module["FS"] = () => abort("'FS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4790. if (!Object.getOwnPropertyDescriptor(Module, "MEMFS")) Module["MEMFS"] = () => abort("'MEMFS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4791. if (!Object.getOwnPropertyDescriptor(Module, "TTY")) Module["TTY"] = () => abort("'TTY' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4792. if (!Object.getOwnPropertyDescriptor(Module, "PIPEFS")) Module["PIPEFS"] = () => abort("'PIPEFS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4793. if (!Object.getOwnPropertyDescriptor(Module, "SOCKFS")) Module["SOCKFS"] = () => abort("'SOCKFS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4794. if (!Object.getOwnPropertyDescriptor(Module, "_setNetworkCallback")) Module["_setNetworkCallback"] = () => abort("'_setNetworkCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4795. if (!Object.getOwnPropertyDescriptor(Module, "tempFixedLengthArray")) Module["tempFixedLengthArray"] = () => abort("'tempFixedLengthArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4796. if (!Object.getOwnPropertyDescriptor(Module, "miniTempWebGLFloatBuffers")) Module["miniTempWebGLFloatBuffers"] = () => abort("'miniTempWebGLFloatBuffers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4797. if (!Object.getOwnPropertyDescriptor(Module, "heapObjectForWebGLType")) Module["heapObjectForWebGLType"] = () => abort("'heapObjectForWebGLType' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4798. if (!Object.getOwnPropertyDescriptor(Module, "heapAccessShiftForWebGLHeap")) Module["heapAccessShiftForWebGLHeap"] = () => abort("'heapAccessShiftForWebGLHeap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4799. if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = () => abort("'GL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4800. if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGet")) Module["emscriptenWebGLGet"] = () => abort("'emscriptenWebGLGet' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4801. if (!Object.getOwnPropertyDescriptor(Module, "computeUnpackAlignedImageSize")) Module["computeUnpackAlignedImageSize"] = () => abort("'computeUnpackAlignedImageSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4802. if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetTexPixelData")) Module["emscriptenWebGLGetTexPixelData"] = () => abort("'emscriptenWebGLGetTexPixelData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4803. if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetUniform")) Module["emscriptenWebGLGetUniform"] = () => abort("'emscriptenWebGLGetUniform' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4804. if (!Object.getOwnPropertyDescriptor(Module, "webglGetUniformLocation")) Module["webglGetUniformLocation"] = () => abort("'webglGetUniformLocation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4805. if (!Object.getOwnPropertyDescriptor(Module, "webglPrepareUniformLocationsBeforeFirstUse")) Module["webglPrepareUniformLocationsBeforeFirstUse"] = () => abort("'webglPrepareUniformLocationsBeforeFirstUse' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4806. if (!Object.getOwnPropertyDescriptor(Module, "webglGetLeftBracePos")) Module["webglGetLeftBracePos"] = () => abort("'webglGetLeftBracePos' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4807. if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetVertexAttrib")) Module["emscriptenWebGLGetVertexAttrib"] = () => abort("'emscriptenWebGLGetVertexAttrib' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4808. if (!Object.getOwnPropertyDescriptor(Module, "writeGLArray")) Module["writeGLArray"] = () => abort("'writeGLArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4809. if (!Object.getOwnPropertyDescriptor(Module, "AL")) Module["AL"] = () => abort("'AL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4810. if (!Object.getOwnPropertyDescriptor(Module, "SDL_unicode")) Module["SDL_unicode"] = () => abort("'SDL_unicode' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4811. if (!Object.getOwnPropertyDescriptor(Module, "SDL_ttfContext")) Module["SDL_ttfContext"] = () => abort("'SDL_ttfContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4812. if (!Object.getOwnPropertyDescriptor(Module, "SDL_audio")) Module["SDL_audio"] = () => abort("'SDL_audio' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4813. if (!Object.getOwnPropertyDescriptor(Module, "SDL")) Module["SDL"] = () => abort("'SDL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4814. if (!Object.getOwnPropertyDescriptor(Module, "SDL_gfx")) Module["SDL_gfx"] = () => abort("'SDL_gfx' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4815. if (!Object.getOwnPropertyDescriptor(Module, "GLUT")) Module["GLUT"] = () => abort("'GLUT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4816. if (!Object.getOwnPropertyDescriptor(Module, "EGL")) Module["EGL"] = () => abort("'EGL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4817. if (!Object.getOwnPropertyDescriptor(Module, "GLFW_Window")) Module["GLFW_Window"] = () => abort("'GLFW_Window' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4818. if (!Object.getOwnPropertyDescriptor(Module, "GLFW")) Module["GLFW"] = () => abort("'GLFW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4819. if (!Object.getOwnPropertyDescriptor(Module, "GLEW")) Module["GLEW"] = () => abort("'GLEW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4820. if (!Object.getOwnPropertyDescriptor(Module, "IDBStore")) Module["IDBStore"] = () => abort("'IDBStore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4821. if (!Object.getOwnPropertyDescriptor(Module, "runAndAbortIfError")) Module["runAndAbortIfError"] = () => abort("'runAndAbortIfError' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4822. if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = () => abort("'warnOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4823. if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = () => abort("'stackSave' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4824. if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = () => abort("'stackRestore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4825. if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = () => abort("'stackAlloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4826. if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = () => abort("'AsciiToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4827. if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = () => abort("'stringToAscii' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4828. if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = () => abort("'UTF16ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4829. if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = () => abort("'stringToUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4830. if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = () => abort("'lengthBytesUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4831. if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = () => abort("'UTF32ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4832. if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = () => abort("'stringToUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4833. if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = () => abort("'lengthBytesUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4834. if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = () => abort("'allocateUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4835. if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8OnStack")) Module["allocateUTF8OnStack"] = () => abort("'allocateUTF8OnStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
  4836. Module["writeStackCookie"] = writeStackCookie;
  4837. Module["checkStackCookie"] = checkStackCookie;
  4838. if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NORMAL")) Object.defineProperty(Module, "ALLOC_NORMAL", { configurable: true, get: function() { abort("'ALLOC_NORMAL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
  4839. if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_STACK")) Object.defineProperty(Module, "ALLOC_STACK", { configurable: true, get: function() { abort("'ALLOC_STACK' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
  4840. var calledRun;
  4841. /**
  4842. * @constructor
  4843. * @this {ExitStatus}
  4844. */
  4845. function ExitStatus(status) {
  4846. this.name = "ExitStatus";
  4847. this.message = "Program terminated with exit(" + status + ")";
  4848. this.status = status;
  4849. }
  4850. var calledMain = false;
  4851. dependenciesFulfilled = function runCaller() {
  4852. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  4853. if (!calledRun) run();
  4854. if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  4855. };
  4856. function stackCheckInit() {
  4857. // This is normally called automatically during __wasm_call_ctors but need to
  4858. // get these values before even running any of the ctors so we call it redundantly
  4859. // here.
  4860. // TODO(sbc): Move writeStackCookie to native to to avoid this.
  4861. _emscripten_stack_init();
  4862. writeStackCookie();
  4863. }
  4864. /** @type {function(Array=)} */
  4865. function run(args) {
  4866. args = args || arguments_;
  4867. if (runDependencies > 0) {
  4868. return;
  4869. }
  4870. stackCheckInit();
  4871. preRun();
  4872. // a preRun added a dependency, run will be called later
  4873. if (runDependencies > 0) {
  4874. return;
  4875. }
  4876. function doRun() {
  4877. // run may have just been called through dependencies being fulfilled just in this very frame,
  4878. // or while the async setStatus time below was happening
  4879. if (calledRun) return;
  4880. calledRun = true;
  4881. Module['calledRun'] = true;
  4882. if (ABORT) return;
  4883. initRuntime();
  4884. if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
  4885. assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
  4886. postRun();
  4887. }
  4888. if (Module['setStatus']) {
  4889. Module['setStatus']('Running...');
  4890. setTimeout(function() {
  4891. setTimeout(function() {
  4892. Module['setStatus']('');
  4893. }, 1);
  4894. doRun();
  4895. }, 1);
  4896. } else
  4897. {
  4898. doRun();
  4899. }
  4900. checkStackCookie();
  4901. }
  4902. Module['run'] = run;
  4903. function checkUnflushedContent() {
  4904. // Compiler settings do not allow exiting the runtime, so flushing
  4905. // the streams is not possible. but in ASSERTIONS mode we check
  4906. // if there was something to flush, and if so tell the user they
  4907. // should request that the runtime be exitable.
  4908. // Normally we would not even include flush() at all, but in ASSERTIONS
  4909. // builds we do so just for this check, and here we see if there is any
  4910. // content to flush, that is, we check if there would have been
  4911. // something a non-ASSERTIONS build would have not seen.
  4912. // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
  4913. // mode (which has its own special function for this; otherwise, all
  4914. // the code is inside libc)
  4915. var oldOut = out;
  4916. var oldErr = err;
  4917. var has = false;
  4918. out = err = (x) => {
  4919. has = true;
  4920. }
  4921. try { // it doesn't matter if it fails
  4922. _fflush(0);
  4923. // also flush in the JS FS layer
  4924. ['stdout', 'stderr'].forEach(function(name) {
  4925. var info = FS.analyzePath('/dev/' + name);
  4926. if (!info) return;
  4927. var stream = info.object;
  4928. var rdev = stream.rdev;
  4929. var tty = TTY.ttys[rdev];
  4930. if (tty && tty.output && tty.output.length) {
  4931. has = true;
  4932. }
  4933. });
  4934. } catch(e) {}
  4935. out = oldOut;
  4936. err = oldErr;
  4937. if (has) {
  4938. warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.');
  4939. }
  4940. }
  4941. /** @param {boolean|number=} implicit */
  4942. function exit(status, implicit) {
  4943. EXITSTATUS = status;
  4944. checkUnflushedContent();
  4945. if (keepRuntimeAlive()) {
  4946. // if exit() was called, we may warn the user if the runtime isn't actually being shut down
  4947. if (!implicit) {
  4948. var msg = 'program exited (with status: ' + status + '), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)';
  4949. err(msg);
  4950. }
  4951. } else {
  4952. exitRuntime();
  4953. }
  4954. procExit(status);
  4955. }
  4956. function procExit(code) {
  4957. EXITSTATUS = code;
  4958. if (!keepRuntimeAlive()) {
  4959. if (Module['onExit']) Module['onExit'](code);
  4960. ABORT = true;
  4961. }
  4962. quit_(code, new ExitStatus(code));
  4963. }
  4964. if (Module['preInit']) {
  4965. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  4966. while (Module['preInit'].length > 0) {
  4967. Module['preInit'].pop()();
  4968. }
  4969. }
  4970. run();
  4971. // Encoder
  4972. // create encoder
  4973. // channels: 1-2
  4974. // samplerate: 8000,12000,16000,24000,48000
  4975. // bitrate: see Opus recommended bitrates
  4976. // frame_size: frame size in milliseconds (2.5,5,10,20,40,60), 20 is recommended
  4977. // voice_optimization: true/false
  4978. function Encoder(channels, samplerate, bitrate, frame_size, voice_optimization)
  4979. {
  4980. this.enc = Module._Encoder_new.apply(null, arguments);
  4981. this.out = Module._String_new();
  4982. }
  4983. // free encoder memory
  4984. Encoder.prototype.destroy = function()
  4985. {
  4986. Module._Encoder_delete(this.enc);
  4987. Module._String_delete(this.out);
  4988. }
  4989. // add samples to the encoder buffer
  4990. // samples: Int16Array of interleaved (if multiple channels) samples
  4991. Encoder.prototype.input = function(samples)
  4992. {
  4993. var ptr = Module._malloc(samples.length*samples.BYTES_PER_ELEMENT);
  4994. var pdata = new Uint8Array(Module.HEAPU8.buffer, ptr, samples.length*samples.BYTES_PER_ELEMENT);
  4995. pdata.set(new Uint8Array(samples.buffer, samples.byteOffset, samples.length*samples.BYTES_PER_ELEMENT));
  4996. Module._Encoder_input(this.enc, ptr, samples.length);
  4997. Module._free(ptr);
  4998. }
  4999. // output the next encoded packet
  5000. // return Uint8Array (valid until the next output call) or null if there is no packet to output
  5001. Encoder.prototype.output = function()
  5002. {
  5003. var ok = Module._Encoder_output(this.enc, this.out);
  5004. if(ok)
  5005. return new Uint8Array(Module.HEAPU8.buffer, Module._String_data(this.out), Module._String_size(this.out));
  5006. }
  5007. // Decoder
  5008. // create decoder
  5009. // channels and samplerate should match the encoder options
  5010. function Decoder(channels, samplerate)
  5011. {
  5012. this.dec = Module._Decoder_new.apply(null, arguments);
  5013. this.out = Module._Int16Array_new();
  5014. }
  5015. // free decoder memory
  5016. Decoder.prototype.destroy = function()
  5017. {
  5018. Module._Decoder_delete(this.dec);
  5019. Module._Int16Array_delete(this.out);
  5020. }
  5021. // add packet to the decoder buffer
  5022. // packet: Uint8Array
  5023. Decoder.prototype.input = function(packet)
  5024. {
  5025. var ptr = Module._malloc(packet.length*packet.BYTES_PER_ELEMENT);
  5026. var pdata = new Uint8Array(Module.HEAPU8.buffer, ptr, packet.length*packet.BYTES_PER_ELEMENT);
  5027. pdata.set(new Uint8Array(packet.buffer, packet.byteOffset, packet.length*packet.BYTES_PER_ELEMENT));
  5028. Module._Decoder_input(this.dec, ptr, packet.length);
  5029. Module._free(ptr);
  5030. }
  5031. // output the next decoded samples
  5032. // return samples (interleaved if multiple channels) as Int16Array (valid until the next output call) or null if there is no output
  5033. Decoder.prototype.output = function()
  5034. {
  5035. var ok = Module._Decoder_output(this.dec, this.out);
  5036. if(ok)
  5037. return new Int16Array(Module.HEAPU8.buffer, Module._Int16Array_data(this.out), Module._Int16Array_size(this.out));
  5038. }
  5039. //export objects
  5040. Module.Encoder = Encoder;
  5041. Module.Decoder = Decoder;
  5042. //make the module global if not using nodejs
  5043. if(Module["ENVIRONMENT"] != "NODE")
  5044. libopus = Module;
  5045. var dec;
  5046. var i = 0;
  5047. self.addEventListener('message', (e) => {
  5048. if (e.data.channels > 0) {
  5049. if (dec) dec.destroy();
  5050. dec = new Decoder(e.data.channels, e.data.sampleRate);
  5051. } else {
  5052. dec.input(e.data);
  5053. self.postMessage(dec.output().slice(0));
  5054. }
  5055. });