float-mm.c.js 201 KB

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