shaderc.js 308 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if (typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if (typeof define === 'function' && define.amd)
  5. define("shaderc", [], factory);
  6. else if (typeof exports === 'object')
  7. exports["shaderc"] = factory();
  8. else
  9. root["Shaderc"] = factory();
  10. })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function () {
  11. const Shaderc = (Module) => {
  12. Module = Module || {};
  13. const returnPromise = new Promise(res => {
  14. Module.onRuntimeInitialized = () => {
  15. res(Module);
  16. };
  17. });
  18. // Sometimes an existing Module object exists with properties
  19. // meant to overwrite the default module functionality. Here
  20. // we collect those properties and reapply _after_ we configure
  21. // the current environment's defaults to avoid having to be so
  22. // defensive during initialization.
  23. var moduleOverrides = {};
  24. for (var key in Module) {
  25. if (Module.hasOwnProperty(key)) {
  26. moduleOverrides[key] = Module[key];
  27. }
  28. }
  29. // The environment setup code below is customized to use Module.
  30. // *** Environment setup code ***
  31. var ENVIRONMENT_IS_WEB = false;
  32. var ENVIRONMENT_IS_WORKER = false;
  33. var ENVIRONMENT_IS_NODE = false;
  34. var ENVIRONMENT_IS_SHELL = false;
  35. // Three configurations we can be running in:
  36. // 1) We could be the application main() thread running in the main JS UI thread. (ENVIRONMENT_IS_WORKER == false and ENVIRONMENT_IS_PTHREAD == false)
  37. // 2) We could be the application main() thread proxied to worker. (with Emscripten -s PROXY_TO_WORKER=1) (ENVIRONMENT_IS_WORKER == true, ENVIRONMENT_IS_PTHREAD == false)
  38. // 3) We could be an application pthread running in a worker. (ENVIRONMENT_IS_WORKER == true and ENVIRONMENT_IS_PTHREAD == true)
  39. if (Module['ENVIRONMENT']) {
  40. if (Module['ENVIRONMENT'] === 'WEB') {
  41. ENVIRONMENT_IS_WEB = true;
  42. } else if (Module['ENVIRONMENT'] === 'WORKER') {
  43. ENVIRONMENT_IS_WORKER = true;
  44. } else if (Module['ENVIRONMENT'] === 'NODE') {
  45. ENVIRONMENT_IS_NODE = true;
  46. } else if (Module['ENVIRONMENT'] === 'SHELL') {
  47. ENVIRONMENT_IS_SHELL = true;
  48. } else {
  49. throw new Error('The provided Module[\'ENVIRONMENT\'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.');
  50. }
  51. } else {
  52. ENVIRONMENT_IS_WEB = typeof window === 'object';
  53. ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
  54. ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function' && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER;
  55. ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  56. }
  57. if (ENVIRONMENT_IS_NODE) {
  58. // Expose functionality in the same simple way that the shells work
  59. // Note that we pollute the global namespace here, otherwise we break in node
  60. if (!Module['print']) Module['print'] = console.log;
  61. if (!Module['printErr']) Module['printErr'] = console.warn;
  62. var nodeFS;
  63. var nodePath;
  64. Module['read'] = function shell_read(filename, binary) {
  65. if (!nodeFS) nodeFS = require('fs');
  66. if (!nodePath) nodePath = require('path');
  67. filename = nodePath['normalize'](filename);
  68. var ret = nodeFS['readFileSync'](filename);
  69. return binary ? ret : ret.toString();
  70. };
  71. Module['readBinary'] = function readBinary(filename) {
  72. var ret = Module['read'](filename, true);
  73. if (!ret.buffer) {
  74. ret = new Uint8Array(ret);
  75. }
  76. assert(ret.buffer);
  77. return ret;
  78. };
  79. Module['load'] = function load(f) {
  80. globalEval(read(f));
  81. };
  82. if (!Module['thisProgram']) {
  83. if (process['argv'].length > 1) {
  84. Module['thisProgram'] = process['argv'][1].replace(/\\/g, '/');
  85. } else {
  86. Module['thisProgram'] = 'unknown-program';
  87. }
  88. }
  89. Module['arguments'] = process['argv'].slice(2);
  90. if (typeof module !== 'undefined') {
  91. module['exports'] = Module;
  92. }
  93. process['on']('uncaughtException', function (ex) {
  94. // suppress ExitStatus exceptions from showing an error
  95. if (!(ex instanceof ExitStatus)) {
  96. throw ex;
  97. }
  98. });
  99. Module['inspect'] = function () { return '[Emscripten Module object]'; };
  100. }
  101. else if (ENVIRONMENT_IS_SHELL) {
  102. if (!Module['print']) Module['print'] = print;
  103. if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not present in v8 or older sm
  104. if (typeof read != 'undefined') {
  105. Module['read'] = read;
  106. } else {
  107. Module['read'] = function shell_read() { throw 'no read() available' };
  108. }
  109. Module['readBinary'] = function readBinary(f) {
  110. if (typeof readbuffer === 'function') {
  111. return new Uint8Array(readbuffer(f));
  112. }
  113. var data = read(f, 'binary');
  114. assert(typeof data === 'object');
  115. return data;
  116. };
  117. if (typeof scriptArgs != 'undefined') {
  118. Module['arguments'] = scriptArgs;
  119. } else if (typeof arguments != 'undefined') {
  120. Module['arguments'] = arguments;
  121. }
  122. if (typeof quit === 'function') {
  123. Module['quit'] = function (status, toThrow) {
  124. quit(status);
  125. }
  126. }
  127. }
  128. else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  129. Module['read'] = function shell_read(url) {
  130. var xhr = new XMLHttpRequest();
  131. xhr.open('GET', url, false);
  132. xhr.send(null);
  133. return xhr.responseText;
  134. };
  135. if (ENVIRONMENT_IS_WORKER) {
  136. Module['readBinary'] = function readBinary(url) {
  137. var xhr = new XMLHttpRequest();
  138. xhr.open('GET', url, false);
  139. xhr.responseType = 'arraybuffer';
  140. xhr.send(null);
  141. return new Uint8Array(xhr.response);
  142. };
  143. }
  144. Module['readAsync'] = function readAsync(url, onload, onerror) {
  145. var xhr = new XMLHttpRequest();
  146. xhr.open('GET', url, true);
  147. xhr.responseType = 'arraybuffer';
  148. xhr.onload = function xhr_onload() {
  149. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  150. onload(xhr.response);
  151. } else {
  152. onerror();
  153. }
  154. };
  155. xhr.onerror = onerror;
  156. xhr.send(null);
  157. };
  158. if (typeof arguments != 'undefined') {
  159. Module['arguments'] = arguments;
  160. }
  161. if (typeof console !== 'undefined') {
  162. if (!Module['print']) Module['print'] = function shell_print(x) {
  163. console.log(x);
  164. };
  165. if (!Module['printErr']) Module['printErr'] = function shell_printErr(x) {
  166. console.warn(x);
  167. };
  168. } else {
  169. // Probably a worker, and without console.log. We can do very little here...
  170. var TRY_USE_DUMP = false;
  171. if (!Module['print']) Module['print'] = (TRY_USE_DUMP && (typeof (dump) !== "undefined") ? (function (x) {
  172. dump(x);
  173. }) : (function (x) {
  174. // self.postMessage(x); // enable this if you want stdout to be sent as messages
  175. }));
  176. }
  177. if (ENVIRONMENT_IS_WORKER) {
  178. Module['load'] = importScripts;
  179. }
  180. if (typeof Module['setWindowTitle'] === 'undefined') {
  181. Module['setWindowTitle'] = function (title) { document.title = title };
  182. }
  183. }
  184. else {
  185. // Unreachable because SHELL is dependant on the others
  186. throw 'Unknown runtime environment. Where are we?';
  187. }
  188. function globalEval(x) {
  189. eval.call(null, x);
  190. }
  191. if (!Module['load'] && Module['read']) {
  192. Module['load'] = function load(f) {
  193. globalEval(Module['read'](f));
  194. };
  195. }
  196. if (!Module['print']) {
  197. Module['print'] = function () { };
  198. }
  199. if (!Module['printErr']) {
  200. Module['printErr'] = Module['print'];
  201. }
  202. if (!Module['arguments']) {
  203. Module['arguments'] = [];
  204. }
  205. if (!Module['thisProgram']) {
  206. Module['thisProgram'] = './this.program';
  207. }
  208. if (!Module['quit']) {
  209. Module['quit'] = function (status, toThrow) {
  210. throw toThrow;
  211. }
  212. }
  213. // *** Environment setup code ***
  214. // Closure helpers
  215. Module.print = Module['print'];
  216. Module.printErr = Module['printErr'];
  217. // Callbacks
  218. Module['preRun'] = [];
  219. Module['postRun'] = [];
  220. // Merge back in the overrides
  221. for (var key in moduleOverrides) {
  222. if (moduleOverrides.hasOwnProperty(key)) {
  223. Module[key] = moduleOverrides[key];
  224. }
  225. }
  226. // Free the object hierarchy contained in the overrides, this lets the GC
  227. // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
  228. moduleOverrides = undefined;
  229. // {{PREAMBLE_ADDITIONS}}
  230. // === Preamble library stuff ===
  231. // Documentation for the public APIs defined in this file must be updated in:
  232. // site/source/docs/api_reference/preamble.js.rst
  233. // A prebuilt local version of the documentation is available at:
  234. // site/build/text/docs/api_reference/preamble.js.txt
  235. // You can also build docs locally as HTML or other formats in site/
  236. // An online HTML version (which may be of a different version of Emscripten)
  237. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  238. //========================================
  239. // Runtime code shared with compiler
  240. //========================================
  241. var Runtime = {
  242. setTempRet0: function (value) {
  243. tempRet0 = value;
  244. return value;
  245. },
  246. getTempRet0: function () {
  247. return tempRet0;
  248. },
  249. stackSave: function () {
  250. return STACKTOP;
  251. },
  252. stackRestore: function (stackTop) {
  253. STACKTOP = stackTop;
  254. },
  255. getNativeTypeSize: function (type) {
  256. switch (type) {
  257. case 'i1': case 'i8': return 1;
  258. case 'i16': return 2;
  259. case 'i32': return 4;
  260. case 'i64': return 8;
  261. case 'float': return 4;
  262. case 'double': return 8;
  263. default: {
  264. if (type[type.length - 1] === '*') {
  265. return Runtime.QUANTUM_SIZE; // A pointer
  266. } else if (type[0] === 'i') {
  267. var bits = parseInt(type.substr(1));
  268. assert(bits % 8 === 0);
  269. return bits / 8;
  270. } else {
  271. return 0;
  272. }
  273. }
  274. }
  275. },
  276. getNativeFieldSize: function (type) {
  277. return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
  278. },
  279. STACK_ALIGN: 16,
  280. prepVararg: function (ptr, type) {
  281. if (type === 'double' || type === 'i64') {
  282. // move so the load is aligned
  283. if (ptr & 7) {
  284. assert((ptr & 7) === 4);
  285. ptr += 4;
  286. }
  287. } else {
  288. assert((ptr & 3) === 0);
  289. }
  290. return ptr;
  291. },
  292. getAlignSize: function (type, size, vararg) {
  293. // we align i64s and doubles on 64-bit boundaries, unlike x86
  294. if (!vararg && (type == 'i64' || type == 'double')) return 8;
  295. if (!type) return Math.min(size, 8); // align structures internally to 64 bits
  296. return Math.min(size || (type ? Runtime.getNativeFieldSize(type) : 0), Runtime.QUANTUM_SIZE);
  297. },
  298. dynCall: function (sig, ptr, args) {
  299. if (args && args.length) {
  300. return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
  301. } else {
  302. return Module['dynCall_' + sig].call(null, ptr);
  303. }
  304. },
  305. functionPointers: [],
  306. addFunction: function (func) {
  307. for (var i = 0; i < Runtime.functionPointers.length; i++) {
  308. if (!Runtime.functionPointers[i]) {
  309. Runtime.functionPointers[i] = func;
  310. return 2 * (1 + i);
  311. }
  312. }
  313. throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
  314. },
  315. removeFunction: function (index) {
  316. Runtime.functionPointers[(index - 2) / 2] = null;
  317. },
  318. warnOnce: function (text) {
  319. if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
  320. if (!Runtime.warnOnce.shown[text]) {
  321. Runtime.warnOnce.shown[text] = 1;
  322. Module.printErr(text);
  323. }
  324. },
  325. funcWrappers: {},
  326. getFuncWrapper: function (func, sig) {
  327. assert(sig);
  328. if (!Runtime.funcWrappers[sig]) {
  329. Runtime.funcWrappers[sig] = {};
  330. }
  331. var sigCache = Runtime.funcWrappers[sig];
  332. if (!sigCache[func]) {
  333. // optimize away arguments usage in common cases
  334. if (sig.length === 1) {
  335. sigCache[func] = function dynCall_wrapper() {
  336. return Runtime.dynCall(sig, func);
  337. };
  338. } else if (sig.length === 2) {
  339. sigCache[func] = function dynCall_wrapper(arg) {
  340. return Runtime.dynCall(sig, func, [arg]);
  341. };
  342. } else {
  343. // general case
  344. sigCache[func] = function dynCall_wrapper() {
  345. return Runtime.dynCall(sig, func, Array.prototype.slice.call(arguments));
  346. };
  347. }
  348. }
  349. return sigCache[func];
  350. },
  351. getCompilerSetting: function (name) {
  352. throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work';
  353. },
  354. stackAlloc: function (size) { var ret = STACKTOP; STACKTOP = (STACKTOP + size) | 0; STACKTOP = (((STACKTOP) + 15) & -16); return ret; },
  355. staticAlloc: function (size) { var ret = STATICTOP; STATICTOP = (STATICTOP + size) | 0; STATICTOP = (((STATICTOP) + 15) & -16); return ret; },
  356. dynamicAlloc: function (size) { var ret = HEAP32[DYNAMICTOP_PTR >> 2]; var end = (((ret + size + 15) | 0) & -16); HEAP32[DYNAMICTOP_PTR >> 2] = end; if (end >= TOTAL_MEMORY) { var success = enlargeMemory(); if (!success) { HEAP32[DYNAMICTOP_PTR >> 2] = ret; return 0; } } return ret; },
  357. alignMemory: function (size, quantum) { var ret = size = Math.ceil((size) / (quantum ? quantum : 16)) * (quantum ? quantum : 16); return ret; },
  358. makeBigInt: function (low, high, unsigned) { var ret = (unsigned ? ((+((low >>> 0))) + ((+((high >>> 0))) * 4294967296.0)) : ((+((low >>> 0))) + ((+((high | 0))) * 4294967296.0))); return ret; },
  359. GLOBAL_BASE: 1024,
  360. QUANTUM_SIZE: 4,
  361. __dummy__: 0
  362. }
  363. Module["Runtime"] = Runtime;
  364. //========================================
  365. // Runtime essentials
  366. //========================================
  367. var ABORT = 0; // whether we are quitting the application. no code should run after this. set in exit() and abort()
  368. var EXITSTATUS = 0;
  369. /** @type {function(*, string=)} */
  370. function assert(condition, text) {
  371. if (!condition) {
  372. abort('Assertion failed: ' + text);
  373. }
  374. }
  375. var globalScope = this;
  376. // Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
  377. function getCFunc(ident) {
  378. var func = Module['_' + ident]; // closure exported function
  379. if (!func) {
  380. try { func = eval('_' + ident); } catch (e) { }
  381. }
  382. assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
  383. return func;
  384. }
  385. var cwrap, ccall;
  386. (function () {
  387. var JSfuncs = {
  388. // Helpers for cwrap -- it can't refer to Runtime directly because it might
  389. // be renamed by closure, instead it calls JSfuncs['stackSave'].body to find
  390. // out what the minified function name is.
  391. 'stackSave': function () {
  392. Runtime.stackSave()
  393. },
  394. 'stackRestore': function () {
  395. Runtime.stackRestore()
  396. },
  397. // type conversion from js to c
  398. 'arrayToC': function (arr) {
  399. var ret = Runtime.stackAlloc(arr.length);
  400. writeArrayToMemory(arr, ret);
  401. return ret;
  402. },
  403. 'stringToC': function (str) {
  404. var ret = 0;
  405. if (str !== null && str !== undefined && str !== 0) { // null string
  406. // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
  407. var len = (str.length << 2) + 1;
  408. ret = Runtime.stackAlloc(len);
  409. stringToUTF8(str, ret, len);
  410. }
  411. return ret;
  412. }
  413. };
  414. // For fast lookup of conversion functions
  415. var toC = { 'string': JSfuncs['stringToC'], 'array': JSfuncs['arrayToC'] };
  416. // C calling interface.
  417. ccall = function ccallFunc(ident, returnType, argTypes, args, opts) {
  418. var func = getCFunc(ident);
  419. var cArgs = [];
  420. var stack = 0;
  421. if (args) {
  422. for (var i = 0; i < args.length; i++) {
  423. var converter = toC[argTypes[i]];
  424. if (converter) {
  425. if (stack === 0) stack = Runtime.stackSave();
  426. cArgs[i] = converter(args[i]);
  427. } else {
  428. cArgs[i] = args[i];
  429. }
  430. }
  431. }
  432. var ret = func.apply(null, cArgs);
  433. if (returnType === 'string') ret = Pointer_stringify(ret);
  434. if (stack !== 0) {
  435. if (opts && opts.async) {
  436. EmterpreterAsync.asyncFinalizers.push(function () {
  437. Runtime.stackRestore(stack);
  438. });
  439. return;
  440. }
  441. Runtime.stackRestore(stack);
  442. }
  443. return ret;
  444. }
  445. var sourceRegex = /^function\s*[a-zA-Z$_0-9]*\s*\(([^)]*)\)\s*{\s*([^*]*?)[\s;]*(?:return\s*(.*?)[;\s]*)?}$/;
  446. function parseJSFunc(jsfunc) {
  447. // Match the body and the return value of a javascript function source
  448. var parsed = jsfunc.toString().match(sourceRegex).slice(1);
  449. return { arguments: parsed[0], body: parsed[1], returnValue: parsed[2] }
  450. }
  451. // sources of useful functions. we create this lazily as it can trigger a source decompression on this entire file
  452. var JSsource = null;
  453. function ensureJSsource() {
  454. if (!JSsource) {
  455. JSsource = {};
  456. for (var fun in JSfuncs) {
  457. if (JSfuncs.hasOwnProperty(fun)) {
  458. // Elements of toCsource are arrays of three items:
  459. // the code, and the return value
  460. JSsource[fun] = parseJSFunc(JSfuncs[fun]);
  461. }
  462. }
  463. }
  464. }
  465. cwrap = function cwrap(ident, returnType, argTypes) {
  466. argTypes = argTypes || [];
  467. var cfunc = getCFunc(ident);
  468. // When the function takes numbers and returns a number, we can just return
  469. // the original function
  470. var numericArgs = argTypes.every(function (type) { return type === 'number' });
  471. var numericRet = (returnType !== 'string');
  472. if (numericRet && numericArgs) {
  473. return cfunc;
  474. }
  475. // Creation of the arguments list (["$1","$2",...,"$nargs"])
  476. var argNames = argTypes.map(function (x, i) { return '$' + i });
  477. var funcstr = "(function(" + argNames.join(',') + ") {";
  478. var nargs = argTypes.length;
  479. if (!numericArgs) {
  480. // Generate the code needed to convert the arguments from javascript
  481. // values to pointers
  482. ensureJSsource();
  483. funcstr += 'var stack = ' + JSsource['stackSave'].body + ';';
  484. for (var i = 0; i < nargs; i++) {
  485. var arg = argNames[i], type = argTypes[i];
  486. if (type === 'number') continue;
  487. var convertCode = JSsource[type + 'ToC']; // [code, return]
  488. funcstr += 'var ' + convertCode.arguments + ' = ' + arg + ';';
  489. funcstr += convertCode.body + ';';
  490. funcstr += arg + '=(' + convertCode.returnValue + ');';
  491. }
  492. }
  493. // When the code is compressed, the name of cfunc is not literally 'cfunc' anymore
  494. var cfuncname = parseJSFunc(function () { return cfunc }).returnValue;
  495. // Call the function
  496. funcstr += 'var ret = ' + cfuncname + '(' + argNames.join(',') + ');';
  497. if (!numericRet) { // Return type can only by 'string' or 'number'
  498. // Convert the result to a string
  499. var strgfy = parseJSFunc(function () { return Pointer_stringify }).returnValue;
  500. funcstr += 'ret = ' + strgfy + '(ret);';
  501. }
  502. if (!numericArgs) {
  503. // If we had a stack, restore it
  504. ensureJSsource();
  505. funcstr += JSsource['stackRestore'].body.replace('()', '(stack)') + ';';
  506. }
  507. funcstr += 'return ret})';
  508. return eval(funcstr);
  509. };
  510. })();
  511. Module["ccall"] = ccall;
  512. Module["cwrap"] = cwrap;
  513. /** @type {function(number, number, string, boolean=)} */
  514. function setValue(ptr, value, type, noSafe) {
  515. type = type || 'i8';
  516. if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
  517. switch (type) {
  518. case 'i1': HEAP8[((ptr) >> 0)] = value; break;
  519. case 'i8': HEAP8[((ptr) >> 0)] = value; break;
  520. case 'i16': HEAP16[((ptr) >> 1)] = value; break;
  521. case 'i32': HEAP32[((ptr) >> 2)] = value; break;
  522. case 'i64': (tempI64 = [value >>> 0, (tempDouble = value, (+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble) / 4294967296.0))), 4294967295.0)) | 0) >>> 0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296.0))))) >>> 0) : 0)], HEAP32[((ptr) >> 2)] = tempI64[0], HEAP32[(((ptr) + (4)) >> 2)] = tempI64[1]); break;
  523. case 'float': HEAPF32[((ptr) >> 2)] = value; break;
  524. case 'double': HEAPF64[((ptr) >> 3)] = value; break;
  525. default: abort('invalid type for setValue: ' + type);
  526. }
  527. }
  528. Module["setValue"] = setValue;
  529. /** @type {function(number, string, boolean=)} */
  530. function getValue(ptr, type, noSafe) {
  531. type = type || 'i8';
  532. if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
  533. switch (type) {
  534. case 'i1': return HEAP8[((ptr) >> 0)];
  535. case 'i8': return HEAP8[((ptr) >> 0)];
  536. case 'i16': return HEAP16[((ptr) >> 1)];
  537. case 'i32': return HEAP32[((ptr) >> 2)];
  538. case 'i64': return HEAP32[((ptr) >> 2)];
  539. case 'float': return HEAPF32[((ptr) >> 2)];
  540. case 'double': return HEAPF64[((ptr) >> 3)];
  541. default: abort('invalid type for setValue: ' + type);
  542. }
  543. return null;
  544. }
  545. Module["getValue"] = getValue;
  546. var ALLOC_NORMAL = 0; // Tries to use _malloc()
  547. var ALLOC_STACK = 1; // Lives for the duration of the current function call
  548. var ALLOC_STATIC = 2; // Cannot be freed
  549. var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
  550. var ALLOC_NONE = 4; // Do not allocate
  551. Module["ALLOC_NORMAL"] = ALLOC_NORMAL;
  552. Module["ALLOC_STACK"] = ALLOC_STACK;
  553. Module["ALLOC_STATIC"] = ALLOC_STATIC;
  554. Module["ALLOC_DYNAMIC"] = ALLOC_DYNAMIC;
  555. Module["ALLOC_NONE"] = ALLOC_NONE;
  556. // allocate(): This is for internal use. You can use it yourself as well, but the interface
  557. // is a little tricky (see docs right below). The reason is that it is optimized
  558. // for multiple syntaxes to save space in generated code. So you should
  559. // normally not use allocate(), and instead allocate memory using _malloc(),
  560. // initialize it with setValue(), and so forth.
  561. // @slab: An array of data, or a number. If a number, then the size of the block to allocate,
  562. // in *bytes* (note that this is sometimes confusing: the next parameter does not
  563. // affect this!)
  564. // @types: Either an array of types, one for each byte (or 0 if no type at that position),
  565. // or a single type which is used for the entire block. This only matters if there
  566. // is initial data - if @slab is a number, then this does not matter at all and is
  567. // ignored.
  568. // @allocator: How to allocate memory, see ALLOC_*
  569. /** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
  570. function allocate(slab, types, allocator, ptr) {
  571. var zeroinit, size;
  572. if (typeof slab === 'number') {
  573. zeroinit = true;
  574. size = slab;
  575. } else {
  576. zeroinit = false;
  577. size = slab.length;
  578. }
  579. var singleType = typeof types === 'string' ? types : null;
  580. var ret;
  581. if (allocator == ALLOC_NONE) {
  582. ret = ptr;
  583. } else {
  584. ret = [typeof _malloc === 'function' ? _malloc : Runtime.staticAlloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
  585. }
  586. if (zeroinit) {
  587. var ptr = ret, stop;
  588. assert((ret & 3) == 0);
  589. stop = ret + (size & ~3);
  590. for (; ptr < stop; ptr += 4) {
  591. HEAP32[((ptr) >> 2)] = 0;
  592. }
  593. stop = ret + size;
  594. while (ptr < stop) {
  595. HEAP8[((ptr++) >> 0)] = 0;
  596. }
  597. return ret;
  598. }
  599. if (singleType === 'i8') {
  600. if (slab.subarray || slab.slice) {
  601. HEAPU8.set(/** @type {!Uint8Array} */(slab), ret);
  602. } else {
  603. HEAPU8.set(new Uint8Array(slab), ret);
  604. }
  605. return ret;
  606. }
  607. var i = 0, type, typeSize, previousType;
  608. while (i < size) {
  609. var curr = slab[i];
  610. if (typeof curr === 'function') {
  611. curr = Runtime.getFunctionIndex(curr);
  612. }
  613. type = singleType || types[i];
  614. if (type === 0) {
  615. i++;
  616. continue;
  617. }
  618. if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
  619. setValue(ret + i, curr, type);
  620. // no need to look up size unless type changes, so cache it
  621. if (previousType !== type) {
  622. typeSize = Runtime.getNativeTypeSize(type);
  623. previousType = type;
  624. }
  625. i += typeSize;
  626. }
  627. return ret;
  628. }
  629. Module["allocate"] = allocate;
  630. // Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
  631. function getMemory(size) {
  632. if (!staticSealed) return Runtime.staticAlloc(size);
  633. if (!runtimeInitialized) return Runtime.dynamicAlloc(size);
  634. return _malloc(size);
  635. }
  636. Module["getMemory"] = getMemory;
  637. /** @type {function(number, number=)} */
  638. function Pointer_stringify(ptr, length) {
  639. if (length === 0 || !ptr) return '';
  640. // TODO: use TextDecoder
  641. // Find the length, and check for UTF while doing so
  642. var hasUtf = 0;
  643. var t;
  644. var i = 0;
  645. while (1) {
  646. t = HEAPU8[(((ptr) + (i)) >> 0)];
  647. hasUtf |= t;
  648. if (t == 0 && !length) break;
  649. i++;
  650. if (length && i == length) break;
  651. }
  652. if (!length) length = i;
  653. var ret = '';
  654. if (hasUtf < 128) {
  655. var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
  656. var curr;
  657. while (length > 0) {
  658. curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
  659. ret = ret ? ret + curr : curr;
  660. ptr += MAX_CHUNK;
  661. length -= MAX_CHUNK;
  662. }
  663. return ret;
  664. }
  665. return Module['UTF8ToString'](ptr);
  666. }
  667. Module["Pointer_stringify"] = Pointer_stringify;
  668. // Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
  669. // a copy of that string as a Javascript String object.
  670. function AsciiToString(ptr) {
  671. var str = '';
  672. while (1) {
  673. var ch = HEAP8[((ptr++) >> 0)];
  674. if (!ch) return str;
  675. str += String.fromCharCode(ch);
  676. }
  677. }
  678. Module["AsciiToString"] = AsciiToString;
  679. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  680. // null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
  681. function stringToAscii(str, outPtr) {
  682. return writeAsciiToMemory(str, outPtr, false);
  683. }
  684. Module["stringToAscii"] = stringToAscii;
  685. // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
  686. // a copy of that string as a Javascript String object.
  687. var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
  688. function UTF8ArrayToString(u8Array, idx) {
  689. var endPtr = idx;
  690. // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
  691. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
  692. while (u8Array[endPtr])++endPtr;
  693. if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
  694. return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
  695. } else {
  696. var u0, u1, u2, u3, u4, u5;
  697. var str = '';
  698. while (1) {
  699. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
  700. u0 = u8Array[idx++];
  701. if (!u0) return str;
  702. if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
  703. u1 = u8Array[idx++] & 63;
  704. if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
  705. u2 = u8Array[idx++] & 63;
  706. if ((u0 & 0xF0) == 0xE0) {
  707. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  708. } else {
  709. u3 = u8Array[idx++] & 63;
  710. if ((u0 & 0xF8) == 0xF0) {
  711. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | u3;
  712. } else {
  713. u4 = u8Array[idx++] & 63;
  714. if ((u0 & 0xFC) == 0xF8) {
  715. u0 = ((u0 & 3) << 24) | (u1 << 18) | (u2 << 12) | (u3 << 6) | u4;
  716. } else {
  717. u5 = u8Array[idx++] & 63;
  718. u0 = ((u0 & 1) << 30) | (u1 << 24) | (u2 << 18) | (u3 << 12) | (u4 << 6) | u5;
  719. }
  720. }
  721. }
  722. if (u0 < 0x10000) {
  723. str += String.fromCharCode(u0);
  724. } else {
  725. var ch = u0 - 0x10000;
  726. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  727. }
  728. }
  729. }
  730. }
  731. Module["UTF8ArrayToString"] = UTF8ArrayToString;
  732. // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns
  733. // a copy of that string as a Javascript String object.
  734. function UTF8ToString(ptr) {
  735. return UTF8ArrayToString(HEAPU8, ptr);
  736. }
  737. Module["UTF8ToString"] = UTF8ToString;
  738. // Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
  739. // encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
  740. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
  741. // Parameters:
  742. // str: the Javascript string to copy.
  743. // outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element.
  744. // outIdx: The starting offset in the array to begin the copying.
  745. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
  746. // terminator, i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
  747. // maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
  748. // Returns the number of bytes written, EXCLUDING the null terminator.
  749. function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) {
  750. if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
  751. return 0;
  752. var startIdx = outIdx;
  753. var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
  754. for (var i = 0; i < str.length; ++i) {
  755. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
  756. // See http://unicode.org/faq/utf_bom.html#utf16-3
  757. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
  758. var u = str.charCodeAt(i); // possibly a lead surrogate
  759. if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
  760. if (u <= 0x7F) {
  761. if (outIdx >= endIdx) break;
  762. outU8Array[outIdx++] = u;
  763. } else if (u <= 0x7FF) {
  764. if (outIdx + 1 >= endIdx) break;
  765. outU8Array[outIdx++] = 0xC0 | (u >> 6);
  766. outU8Array[outIdx++] = 0x80 | (u & 63);
  767. } else if (u <= 0xFFFF) {
  768. if (outIdx + 2 >= endIdx) break;
  769. outU8Array[outIdx++] = 0xE0 | (u >> 12);
  770. outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
  771. outU8Array[outIdx++] = 0x80 | (u & 63);
  772. } else if (u <= 0x1FFFFF) {
  773. if (outIdx + 3 >= endIdx) break;
  774. outU8Array[outIdx++] = 0xF0 | (u >> 18);
  775. outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
  776. outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
  777. outU8Array[outIdx++] = 0x80 | (u & 63);
  778. } else if (u <= 0x3FFFFFF) {
  779. if (outIdx + 4 >= endIdx) break;
  780. outU8Array[outIdx++] = 0xF8 | (u >> 24);
  781. outU8Array[outIdx++] = 0x80 | ((u >> 18) & 63);
  782. outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
  783. outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
  784. outU8Array[outIdx++] = 0x80 | (u & 63);
  785. } else {
  786. if (outIdx + 5 >= endIdx) break;
  787. outU8Array[outIdx++] = 0xFC | (u >> 30);
  788. outU8Array[outIdx++] = 0x80 | ((u >> 24) & 63);
  789. outU8Array[outIdx++] = 0x80 | ((u >> 18) & 63);
  790. outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
  791. outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
  792. outU8Array[outIdx++] = 0x80 | (u & 63);
  793. }
  794. }
  795. // Null-terminate the pointer to the buffer.
  796. outU8Array[outIdx] = 0;
  797. return outIdx - startIdx;
  798. }
  799. Module["stringToUTF8Array"] = stringToUTF8Array;
  800. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  801. // null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
  802. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
  803. // Returns the number of bytes written, EXCLUDING the null terminator.
  804. function stringToUTF8(str, outPtr, maxBytesToWrite) {
  805. return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
  806. }
  807. Module["stringToUTF8"] = stringToUTF8;
  808. // Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
  809. function lengthBytesUTF8(str) {
  810. var len = 0;
  811. for (var i = 0; i < str.length; ++i) {
  812. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
  813. // See http://unicode.org/faq/utf_bom.html#utf16-3
  814. var u = str.charCodeAt(i); // possibly a lead surrogate
  815. if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
  816. if (u <= 0x7F) {
  817. ++len;
  818. } else if (u <= 0x7FF) {
  819. len += 2;
  820. } else if (u <= 0xFFFF) {
  821. len += 3;
  822. } else if (u <= 0x1FFFFF) {
  823. len += 4;
  824. } else if (u <= 0x3FFFFFF) {
  825. len += 5;
  826. } else {
  827. len += 6;
  828. }
  829. }
  830. return len;
  831. }
  832. Module["lengthBytesUTF8"] = lengthBytesUTF8;
  833. // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
  834. // a copy of that string as a Javascript String object.
  835. var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
  836. function UTF16ToString(ptr) {
  837. var endPtr = ptr;
  838. // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
  839. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
  840. var idx = endPtr >> 1;
  841. while (HEAP16[idx])++idx;
  842. endPtr = idx << 1;
  843. if (endPtr - ptr > 32 && UTF16Decoder) {
  844. return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
  845. } else {
  846. var i = 0;
  847. var str = '';
  848. while (1) {
  849. var codeUnit = HEAP16[(((ptr) + (i * 2)) >> 1)];
  850. if (codeUnit == 0) return str;
  851. ++i;
  852. // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
  853. str += String.fromCharCode(codeUnit);
  854. }
  855. }
  856. }
  857. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  858. // null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
  859. // Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
  860. // Parameters:
  861. // str: the Javascript string to copy.
  862. // outPtr: Byte address in Emscripten HEAP where to write the string to.
  863. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
  864. // terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
  865. // maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
  866. // Returns the number of bytes written, EXCLUDING the null terminator.
  867. function stringToUTF16(str, outPtr, maxBytesToWrite) {
  868. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  869. if (maxBytesToWrite === undefined) {
  870. maxBytesToWrite = 0x7FFFFFFF;
  871. }
  872. if (maxBytesToWrite < 2) return 0;
  873. maxBytesToWrite -= 2; // Null terminator.
  874. var startPtr = outPtr;
  875. var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length;
  876. for (var i = 0; i < numCharsToWrite; ++i) {
  877. // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
  878. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  879. HEAP16[((outPtr) >> 1)] = codeUnit;
  880. outPtr += 2;
  881. }
  882. // Null-terminate the pointer to the HEAP.
  883. HEAP16[((outPtr) >> 1)] = 0;
  884. return outPtr - startPtr;
  885. }
  886. // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
  887. function lengthBytesUTF16(str) {
  888. return str.length * 2;
  889. }
  890. function UTF32ToString(ptr) {
  891. var i = 0;
  892. var str = '';
  893. while (1) {
  894. var utf32 = HEAP32[(((ptr) + (i * 4)) >> 2)];
  895. if (utf32 == 0)
  896. return str;
  897. ++i;
  898. // 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.
  899. // See http://unicode.org/faq/utf_bom.html#utf16-3
  900. if (utf32 >= 0x10000) {
  901. var ch = utf32 - 0x10000;
  902. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  903. } else {
  904. str += String.fromCharCode(utf32);
  905. }
  906. }
  907. }
  908. // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
  909. // null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
  910. // Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
  911. // Parameters:
  912. // str: the Javascript string to copy.
  913. // outPtr: Byte address in Emscripten HEAP where to write the string to.
  914. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
  915. // terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
  916. // maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
  917. // Returns the number of bytes written, EXCLUDING the null terminator.
  918. function stringToUTF32(str, outPtr, maxBytesToWrite) {
  919. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  920. if (maxBytesToWrite === undefined) {
  921. maxBytesToWrite = 0x7FFFFFFF;
  922. }
  923. if (maxBytesToWrite < 4) return 0;
  924. var startPtr = outPtr;
  925. var endPtr = startPtr + maxBytesToWrite - 4;
  926. for (var i = 0; i < str.length; ++i) {
  927. // 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.
  928. // See http://unicode.org/faq/utf_bom.html#utf16-3
  929. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  930. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
  931. var trailSurrogate = str.charCodeAt(++i);
  932. codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
  933. }
  934. HEAP32[((outPtr) >> 2)] = codeUnit;
  935. outPtr += 4;
  936. if (outPtr + 4 > endPtr) break;
  937. }
  938. // Null-terminate the pointer to the HEAP.
  939. HEAP32[((outPtr) >> 2)] = 0;
  940. return outPtr - startPtr;
  941. }
  942. // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
  943. function lengthBytesUTF32(str) {
  944. var len = 0;
  945. for (var i = 0; i < str.length; ++i) {
  946. // 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.
  947. // See http://unicode.org/faq/utf_bom.html#utf16-3
  948. var codeUnit = str.charCodeAt(i);
  949. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF)++i; // possibly a lead surrogate, so skip over the tail surrogate.
  950. len += 4;
  951. }
  952. return len;
  953. }
  954. function demangle(func) {
  955. var __cxa_demangle_func = Module['___cxa_demangle'] || Module['__cxa_demangle'];
  956. if (__cxa_demangle_func) {
  957. try {
  958. var s =
  959. func.substr(1);
  960. var len = lengthBytesUTF8(s) + 1;
  961. var buf = _malloc(len);
  962. stringToUTF8(s, buf, len);
  963. var status = _malloc(4);
  964. var ret = __cxa_demangle_func(buf, 0, 0, status);
  965. if (getValue(status, 'i32') === 0 && ret) {
  966. return Pointer_stringify(ret);
  967. }
  968. // otherwise, libcxxabi failed
  969. } catch (e) {
  970. // ignore problems here
  971. } finally {
  972. if (buf) _free(buf);
  973. if (status) _free(status);
  974. if (ret) _free(ret);
  975. }
  976. // failure when using libcxxabi, don't demangle
  977. return func;
  978. }
  979. Runtime.warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
  980. return func;
  981. }
  982. function demangleAll(text) {
  983. var regex =
  984. /__Z[\w\d_]+/g;
  985. return text.replace(regex,
  986. function (x) {
  987. var y = demangle(x);
  988. return x === y ? x : (x + ' [' + y + ']');
  989. });
  990. }
  991. function jsStackTrace() {
  992. var err = new Error();
  993. if (!err.stack) {
  994. // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
  995. // so try that as a special-case.
  996. try {
  997. throw new Error(0);
  998. } catch (e) {
  999. err = e;
  1000. }
  1001. if (!err.stack) {
  1002. return '(no stack trace available)';
  1003. }
  1004. }
  1005. return err.stack.toString();
  1006. }
  1007. function stackTrace() {
  1008. var js = jsStackTrace();
  1009. if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
  1010. return demangleAll(js);
  1011. }
  1012. Module["stackTrace"] = stackTrace;
  1013. // Memory management
  1014. var PAGE_SIZE = 16384;
  1015. var WASM_PAGE_SIZE = 65536;
  1016. var ASMJS_PAGE_SIZE = 16777216;
  1017. var MIN_TOTAL_MEMORY = 16777216;
  1018. function alignUp(x, multiple) {
  1019. if (x % multiple > 0) {
  1020. x += multiple - (x % multiple);
  1021. }
  1022. return x;
  1023. }
  1024. var HEAP,
  1025. /** @type {ArrayBuffer} */
  1026. buffer,
  1027. /** @type {Int8Array} */
  1028. HEAP8,
  1029. /** @type {Uint8Array} */
  1030. HEAPU8,
  1031. /** @type {Int16Array} */
  1032. HEAP16,
  1033. /** @type {Uint16Array} */
  1034. HEAPU16,
  1035. /** @type {Int32Array} */
  1036. HEAP32,
  1037. /** @type {Uint32Array} */
  1038. HEAPU32,
  1039. /** @type {Float32Array} */
  1040. HEAPF32,
  1041. /** @type {Float64Array} */
  1042. HEAPF64;
  1043. function updateGlobalBuffer(buf) {
  1044. Module['buffer'] = buffer = buf;
  1045. }
  1046. function updateGlobalBufferViews() {
  1047. Module['HEAP8'] = HEAP8 = new Int8Array(buffer);
  1048. Module['HEAP16'] = HEAP16 = new Int16Array(buffer);
  1049. Module['HEAP32'] = HEAP32 = new Int32Array(buffer);
  1050. Module['HEAPU8'] = HEAPU8 = new Uint8Array(buffer);
  1051. Module['HEAPU16'] = HEAPU16 = new Uint16Array(buffer);
  1052. Module['HEAPU32'] = HEAPU32 = new Uint32Array(buffer);
  1053. Module['HEAPF32'] = HEAPF32 = new Float32Array(buffer);
  1054. Module['HEAPF64'] = HEAPF64 = new Float64Array(buffer);
  1055. }
  1056. var STATIC_BASE, STATICTOP, staticSealed; // static area
  1057. var STACK_BASE, STACKTOP, STACK_MAX; // stack area
  1058. var DYNAMIC_BASE, DYNAMICTOP_PTR; // dynamic area handled by sbrk
  1059. STATIC_BASE = STATICTOP = STACK_BASE = STACKTOP = STACK_MAX = DYNAMIC_BASE = DYNAMICTOP_PTR = 0;
  1060. staticSealed = false;
  1061. function abortOnCannotGrowMemory() {
  1062. 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 -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
  1063. }
  1064. if (!Module['reallocBuffer']) Module['reallocBuffer'] = function (size) {
  1065. var ret;
  1066. try {
  1067. if (ArrayBuffer.transfer) {
  1068. ret = ArrayBuffer.transfer(buffer, size);
  1069. } else {
  1070. var oldHEAP8 = HEAP8;
  1071. ret = new ArrayBuffer(size);
  1072. var temp = new Int8Array(ret);
  1073. temp.set(oldHEAP8);
  1074. }
  1075. } catch (e) {
  1076. return false;
  1077. }
  1078. var success = _emscripten_replace_memory(ret);
  1079. if (!success) return false;
  1080. return ret;
  1081. };
  1082. function enlargeMemory() {
  1083. // TOTAL_MEMORY is the current size of the actual array, and DYNAMICTOP is the new top.
  1084. var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; // In wasm, heap size must be a multiple of 64KB. In asm.js, they need to be multiples of 16MB.
  1085. var LIMIT = 2147483648 - PAGE_MULTIPLE; // We can do one page short of 2GB as theoretical maximum.
  1086. if (HEAP32[DYNAMICTOP_PTR >> 2] > LIMIT) {
  1087. return false;
  1088. }
  1089. var OLD_TOTAL_MEMORY = TOTAL_MEMORY;
  1090. TOTAL_MEMORY = Math.max(TOTAL_MEMORY, MIN_TOTAL_MEMORY); // So the loop below will not be infinite, and minimum asm.js memory size is 16MB.
  1091. while (TOTAL_MEMORY < HEAP32[DYNAMICTOP_PTR >> 2]) { // Keep incrementing the heap size as long as it's less than what is requested.
  1092. if (TOTAL_MEMORY <= 536870912) {
  1093. TOTAL_MEMORY = alignUp(2 * TOTAL_MEMORY, PAGE_MULTIPLE); // Simple heuristic: double until 1GB...
  1094. } else {
  1095. TOTAL_MEMORY = Math.min(alignUp((3 * TOTAL_MEMORY + 2147483648) / 4, PAGE_MULTIPLE), LIMIT); // ..., but after that, add smaller increments towards 2GB, which we cannot reach
  1096. }
  1097. }
  1098. var replacement = Module['reallocBuffer'](TOTAL_MEMORY);
  1099. if (!replacement || replacement.byteLength != TOTAL_MEMORY) {
  1100. // restore the state to before this call, we failed
  1101. TOTAL_MEMORY = OLD_TOTAL_MEMORY;
  1102. return false;
  1103. }
  1104. // everything worked
  1105. updateGlobalBuffer(replacement);
  1106. updateGlobalBufferViews();
  1107. return true;
  1108. }
  1109. var byteLength;
  1110. try {
  1111. byteLength = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get);
  1112. byteLength(new ArrayBuffer(4)); // can fail on older ie
  1113. } catch (e) { // can fail on older node/v8
  1114. byteLength = function (buffer) { return buffer.byteLength; };
  1115. }
  1116. var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
  1117. var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216;
  1118. if (TOTAL_MEMORY < TOTAL_STACK) Module.printErr('TOTAL_MEMORY should be larger than TOTAL_STACK, was ' + TOTAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
  1119. // Initialize the runtime's memory
  1120. // Use a provided buffer, if there is one, or else allocate a new one
  1121. if (Module['buffer']) {
  1122. buffer = Module['buffer'];
  1123. } else {
  1124. // Use a WebAssembly memory where available
  1125. if (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function') {
  1126. Module['wasmMemory'] = new WebAssembly.Memory({ 'initial': TOTAL_MEMORY / WASM_PAGE_SIZE });
  1127. buffer = Module['wasmMemory'].buffer;
  1128. } else {
  1129. buffer = new ArrayBuffer(TOTAL_MEMORY);
  1130. }
  1131. }
  1132. updateGlobalBufferViews();
  1133. function getTotalMemory() {
  1134. return TOTAL_MEMORY;
  1135. }
  1136. // Endianness check (note: assumes compiler arch was little-endian)
  1137. HEAP32[0] = 0x63736d65; /* 'emsc' */
  1138. HEAP16[1] = 0x6373;
  1139. if (HEAPU8[2] !== 0x73 || HEAPU8[3] !== 0x63) throw 'Runtime error: expected the system to be little-endian!';
  1140. Module['HEAP'] = HEAP;
  1141. Module['buffer'] = buffer;
  1142. Module['HEAP8'] = HEAP8;
  1143. Module['HEAP16'] = HEAP16;
  1144. Module['HEAP32'] = HEAP32;
  1145. Module['HEAPU8'] = HEAPU8;
  1146. Module['HEAPU16'] = HEAPU16;
  1147. Module['HEAPU32'] = HEAPU32;
  1148. Module['HEAPF32'] = HEAPF32;
  1149. Module['HEAPF64'] = HEAPF64;
  1150. function callRuntimeCallbacks(callbacks) {
  1151. while (callbacks.length > 0) {
  1152. var callback = callbacks.shift();
  1153. if (typeof callback == 'function') {
  1154. callback();
  1155. continue;
  1156. }
  1157. var func = callback.func;
  1158. if (typeof func === 'number') {
  1159. if (callback.arg === undefined) {
  1160. Module['dynCall_v'](func);
  1161. } else {
  1162. Module['dynCall_vi'](func, callback.arg);
  1163. }
  1164. } else {
  1165. func(callback.arg === undefined ? null : callback.arg);
  1166. }
  1167. }
  1168. }
  1169. var __ATPRERUN__ = []; // functions called before the runtime is initialized
  1170. var __ATINIT__ = []; // functions called during startup
  1171. var __ATMAIN__ = []; // functions called when main() is to be run
  1172. var __ATEXIT__ = []; // functions called during shutdown
  1173. var __ATPOSTRUN__ = []; // functions called after the runtime has exited
  1174. var runtimeInitialized = false;
  1175. var runtimeExited = false;
  1176. function preRun() {
  1177. // compatibility - merge in anything from Module['preRun'] at this time
  1178. if (Module['preRun']) {
  1179. if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  1180. while (Module['preRun'].length) {
  1181. addOnPreRun(Module['preRun'].shift());
  1182. }
  1183. }
  1184. callRuntimeCallbacks(__ATPRERUN__);
  1185. }
  1186. function ensureInitRuntime() {
  1187. if (runtimeInitialized) return;
  1188. runtimeInitialized = true;
  1189. callRuntimeCallbacks(__ATINIT__);
  1190. }
  1191. function preMain() {
  1192. callRuntimeCallbacks(__ATMAIN__);
  1193. }
  1194. function exitRuntime() {
  1195. callRuntimeCallbacks(__ATEXIT__);
  1196. runtimeExited = true;
  1197. }
  1198. function postRun() {
  1199. // compatibility - merge in anything from Module['postRun'] at this time
  1200. if (Module['postRun']) {
  1201. if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  1202. while (Module['postRun'].length) {
  1203. addOnPostRun(Module['postRun'].shift());
  1204. }
  1205. }
  1206. callRuntimeCallbacks(__ATPOSTRUN__);
  1207. }
  1208. function addOnPreRun(cb) {
  1209. __ATPRERUN__.unshift(cb);
  1210. }
  1211. Module["addOnPreRun"] = addOnPreRun;
  1212. function addOnInit(cb) {
  1213. __ATINIT__.unshift(cb);
  1214. }
  1215. Module["addOnInit"] = addOnInit;
  1216. function addOnPreMain(cb) {
  1217. __ATMAIN__.unshift(cb);
  1218. }
  1219. Module["addOnPreMain"] = addOnPreMain;
  1220. function addOnExit(cb) {
  1221. __ATEXIT__.unshift(cb);
  1222. }
  1223. Module["addOnExit"] = addOnExit;
  1224. function addOnPostRun(cb) {
  1225. __ATPOSTRUN__.unshift(cb);
  1226. }
  1227. Module["addOnPostRun"] = addOnPostRun;
  1228. // Tools
  1229. /** @type {function(string, boolean=, number=)} */
  1230. function intArrayFromString(stringy, dontAddNull, length) {
  1231. var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
  1232. var u8array = new Array(len);
  1233. var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
  1234. if (dontAddNull) u8array.length = numBytesWritten;
  1235. return u8array;
  1236. }
  1237. Module["intArrayFromString"] = intArrayFromString;
  1238. function intArrayToString(array) {
  1239. var ret = [];
  1240. for (var i = 0; i < array.length; i++) {
  1241. var chr = array[i];
  1242. if (chr > 0xFF) {
  1243. chr &= 0xFF;
  1244. }
  1245. ret.push(String.fromCharCode(chr));
  1246. }
  1247. return ret.join('');
  1248. }
  1249. Module["intArrayToString"] = intArrayToString;
  1250. // Deprecated: This function should not be called because it is unsafe and does not provide
  1251. // a maximum length limit of how many bytes it is allowed to write. Prefer calling the
  1252. // function stringToUTF8Array() instead, which takes in a maximum length that can be used
  1253. // to be secure from out of bounds writes.
  1254. /** @deprecated */
  1255. function writeStringToMemory(string, buffer, dontAddNull) {
  1256. Runtime.warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
  1257. var /** @type {number} */ lastChar, /** @type {number} */ end;
  1258. if (dontAddNull) {
  1259. // stringToUTF8Array always appends null. If we don't want to do that, remember the
  1260. // character that existed at the location where the null will be placed, and restore
  1261. // that after the write (below).
  1262. end = buffer + lengthBytesUTF8(string);
  1263. lastChar = HEAP8[end];
  1264. }
  1265. stringToUTF8(string, buffer, Infinity);
  1266. if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
  1267. }
  1268. Module["writeStringToMemory"] = writeStringToMemory;
  1269. function writeArrayToMemory(array, buffer) {
  1270. HEAP8.set(array, buffer);
  1271. }
  1272. Module["writeArrayToMemory"] = writeArrayToMemory;
  1273. function writeAsciiToMemory(str, buffer, dontAddNull) {
  1274. for (var i = 0; i < str.length; ++i) {
  1275. HEAP8[((buffer++) >> 0)] = str.charCodeAt(i);
  1276. }
  1277. // Null-terminate the pointer to the HEAP.
  1278. if (!dontAddNull) HEAP8[((buffer) >> 0)] = 0;
  1279. }
  1280. Module["writeAsciiToMemory"] = writeAsciiToMemory;
  1281. function unSign(value, bits, ignore) {
  1282. if (value >= 0) {
  1283. return value;
  1284. }
  1285. 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
  1286. : Math.pow(2, bits) + value;
  1287. }
  1288. function reSign(value, bits, ignore) {
  1289. if (value <= 0) {
  1290. return value;
  1291. }
  1292. var half = bits <= 32 ? Math.abs(1 << (bits - 1)) // abs is needed if bits == 32
  1293. : Math.pow(2, bits - 1);
  1294. 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
  1295. // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
  1296. // TODO: In i64 mode 1, resign the two parts separately and safely
  1297. value = -2 * half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
  1298. }
  1299. return value;
  1300. }
  1301. // check for imul support, and also for correctness ( https://bugs.webkit.org/show_bug.cgi?id=126345 )
  1302. if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
  1303. var ah = a >>> 16;
  1304. var al = a & 0xffff;
  1305. var bh = b >>> 16;
  1306. var bl = b & 0xffff;
  1307. return (al * bl + ((ah * bl + al * bh) << 16)) | 0;
  1308. };
  1309. Math.imul = Math['imul'];
  1310. if (!Math['fround']) {
  1311. var froundBuffer = new Float32Array(1);
  1312. Math['fround'] = function (x) { froundBuffer[0] = x; return froundBuffer[0] };
  1313. }
  1314. Math.fround = Math['fround'];
  1315. if (!Math['clz32']) Math['clz32'] = function (x) {
  1316. x = x >>> 0;
  1317. for (var i = 0; i < 32; i++) {
  1318. if (x & (1 << (31 - i))) return i;
  1319. }
  1320. return 32;
  1321. };
  1322. Math.clz32 = Math['clz32']
  1323. if (!Math['trunc']) Math['trunc'] = function (x) {
  1324. return x < 0 ? Math.ceil(x) : Math.floor(x);
  1325. };
  1326. Math.trunc = Math['trunc'];
  1327. var Math_abs = Math.abs;
  1328. var Math_cos = Math.cos;
  1329. var Math_sin = Math.sin;
  1330. var Math_tan = Math.tan;
  1331. var Math_acos = Math.acos;
  1332. var Math_asin = Math.asin;
  1333. var Math_atan = Math.atan;
  1334. var Math_atan2 = Math.atan2;
  1335. var Math_exp = Math.exp;
  1336. var Math_log = Math.log;
  1337. var Math_sqrt = Math.sqrt;
  1338. var Math_ceil = Math.ceil;
  1339. var Math_floor = Math.floor;
  1340. var Math_pow = Math.pow;
  1341. var Math_imul = Math.imul;
  1342. var Math_fround = Math.fround;
  1343. var Math_round = Math.round;
  1344. var Math_min = Math.min;
  1345. var Math_clz32 = Math.clz32;
  1346. var Math_trunc = Math.trunc;
  1347. // A counter of dependencies for calling run(). If we need to
  1348. // do asynchronous work before running, increment this and
  1349. // decrement it. Incrementing must happen in a place like
  1350. // PRE_RUN_ADDITIONS (used by emcc to add file preloading).
  1351. // Note that you can add dependencies in preRun, even though
  1352. // it happens right before run - run will be postponed until
  1353. // the dependencies are met.
  1354. var runDependencies = 0;
  1355. var runDependencyWatcher = null;
  1356. var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
  1357. function getUniqueRunDependency(id) {
  1358. return id;
  1359. }
  1360. function addRunDependency(id) {
  1361. runDependencies++;
  1362. if (Module['monitorRunDependencies']) {
  1363. Module['monitorRunDependencies'](runDependencies);
  1364. }
  1365. }
  1366. Module["addRunDependency"] = addRunDependency;
  1367. function removeRunDependency(id) {
  1368. runDependencies--;
  1369. if (Module['monitorRunDependencies']) {
  1370. Module['monitorRunDependencies'](runDependencies);
  1371. }
  1372. if (runDependencies == 0) {
  1373. if (runDependencyWatcher !== null) {
  1374. clearInterval(runDependencyWatcher);
  1375. runDependencyWatcher = null;
  1376. }
  1377. if (dependenciesFulfilled) {
  1378. var callback = dependenciesFulfilled;
  1379. dependenciesFulfilled = null;
  1380. callback(); // can add another dependenciesFulfilled
  1381. }
  1382. }
  1383. }
  1384. Module["removeRunDependency"] = removeRunDependency;
  1385. Module["preloadedImages"] = {}; // maps url to image data
  1386. Module["preloadedAudios"] = {}; // maps url to audio data
  1387. var memoryInitializer = null;
  1388. function integrateWasmJS(Module) {
  1389. // wasm.js has several methods for creating the compiled code module here:
  1390. // * 'native-wasm' : use native WebAssembly support in the browser
  1391. // * 'interpret-s-expr': load s-expression code from a .wast and interpret
  1392. // * 'interpret-binary': load binary wasm and interpret
  1393. // * 'interpret-asm2wasm': load asm.js code, translate to wasm, and interpret
  1394. // * 'asmjs': no wasm, just load the asm.js code and use that (good for testing)
  1395. // The method can be set at compile time (BINARYEN_METHOD), or runtime by setting Module['wasmJSMethod'].
  1396. // The method can be a comma-separated list, in which case, we will try the
  1397. // options one by one. Some of them can fail gracefully, and then we can try
  1398. // the next.
  1399. // inputs
  1400. var method = Module['wasmJSMethod'] || 'native-wasm';
  1401. Module['wasmJSMethod'] = method;
  1402. var wasmTextFile = Module['wasmTextFile'] || 'shaderc.wast';
  1403. var wasmBinaryFile = Module['wasmBinaryFile'] || 'shaderc.wasm';
  1404. var asmjsCodeFile = Module['asmjsCodeFile'] || 'shaderc.temp.asm.js';
  1405. if (typeof Module['locateFile'] === 'function') {
  1406. wasmTextFile = Module['locateFile'](wasmTextFile);
  1407. wasmBinaryFile = Module['locateFile'](wasmBinaryFile);
  1408. asmjsCodeFile = Module['locateFile'](asmjsCodeFile);
  1409. }
  1410. // utilities
  1411. var wasmPageSize = 64 * 1024;
  1412. var asm2wasmImports = { // special asm2wasm imports
  1413. "f64-rem": function (x, y) {
  1414. return x % y;
  1415. },
  1416. "f64-to-int": function (x) {
  1417. return x | 0;
  1418. },
  1419. "i32s-div": function (x, y) {
  1420. return ((x | 0) / (y | 0)) | 0;
  1421. },
  1422. "i32u-div": function (x, y) {
  1423. return ((x >>> 0) / (y >>> 0)) >>> 0;
  1424. },
  1425. "i32s-rem": function (x, y) {
  1426. return ((x | 0) % (y | 0)) | 0;
  1427. },
  1428. "i32u-rem": function (x, y) {
  1429. return ((x >>> 0) % (y >>> 0)) >>> 0;
  1430. },
  1431. "debugger": function () {
  1432. debugger;
  1433. },
  1434. };
  1435. var info = {
  1436. 'global': null,
  1437. 'env': null,
  1438. 'asm2wasm': asm2wasmImports,
  1439. 'parent': Module // Module inside wasm-js.cpp refers to wasm-js.cpp; this allows access to the outside program.
  1440. };
  1441. var exports = null;
  1442. function lookupImport(mod, base) {
  1443. var lookup = info;
  1444. if (mod.indexOf('.') < 0) {
  1445. lookup = (lookup || {})[mod];
  1446. } else {
  1447. var parts = mod.split('.');
  1448. lookup = (lookup || {})[parts[0]];
  1449. lookup = (lookup || {})[parts[1]];
  1450. }
  1451. if (base) {
  1452. lookup = (lookup || {})[base];
  1453. }
  1454. if (lookup === undefined) {
  1455. abort('bad lookupImport to (' + mod + ').' + base);
  1456. }
  1457. return lookup;
  1458. }
  1459. function mergeMemory(newBuffer) {
  1460. // The wasm instance creates its memory. But static init code might have written to
  1461. // buffer already, including the mem init file, and we must copy it over in a proper merge.
  1462. // TODO: avoid this copy, by avoiding such static init writes
  1463. // TODO: in shorter term, just copy up to the last static init write
  1464. var oldBuffer = Module['buffer'];
  1465. if (newBuffer.byteLength < oldBuffer.byteLength) {
  1466. Module['printErr']('the new buffer in mergeMemory is smaller than the previous one. in native wasm, we should grow memory here');
  1467. }
  1468. var oldView = new Int8Array(oldBuffer);
  1469. var newView = new Int8Array(newBuffer);
  1470. // If we have a mem init file, do not trample it
  1471. if (!memoryInitializer) {
  1472. oldView.set(newView.subarray(Module['STATIC_BASE'], Module['STATIC_BASE'] + Module['STATIC_BUMP']), Module['STATIC_BASE']);
  1473. }
  1474. newView.set(oldView);
  1475. updateGlobalBuffer(newBuffer);
  1476. updateGlobalBufferViews();
  1477. }
  1478. var WasmTypes = {
  1479. none: 0,
  1480. i32: 1,
  1481. i64: 2,
  1482. f32: 3,
  1483. f64: 4
  1484. };
  1485. function fixImports(imports) {
  1486. if (!0) return imports;
  1487. var ret = {};
  1488. for (var i in imports) {
  1489. var fixed = i;
  1490. if (fixed[0] == '_') fixed = fixed.substr(1);
  1491. ret[fixed] = imports[i];
  1492. }
  1493. return ret;
  1494. }
  1495. function getBinary() {
  1496. try {
  1497. var binary;
  1498. if (Module['wasmBinary']) {
  1499. binary = Module['wasmBinary'];
  1500. binary = new Uint8Array(binary);
  1501. } else if (Module['readBinary']) {
  1502. binary = Module['readBinary'](wasmBinaryFile);
  1503. } else {
  1504. throw "on the web, we need the wasm binary to be preloaded and set on Module['wasmBinary']. emcc.py will do that for you when generating HTML (but not JS)";
  1505. }
  1506. return binary;
  1507. }
  1508. catch (err) {
  1509. abort(err);
  1510. }
  1511. }
  1512. function getBinaryPromise() {
  1513. // if we don't have the binary yet, and have the Fetch api, use that
  1514. if (!Module['wasmBinary'] && typeof fetch === 'function') {
  1515. return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
  1516. if (!response['ok']) {
  1517. throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
  1518. }
  1519. return response['arrayBuffer']();
  1520. });
  1521. }
  1522. // Otherwise, getBinary should be able to get it synchronously
  1523. return new Promise(function (resolve, reject) {
  1524. resolve(getBinary());
  1525. });
  1526. }
  1527. // do-method functions
  1528. function doJustAsm(global, env, providedBuffer) {
  1529. // if no Module.asm, or it's the method handler helper (see below), then apply
  1530. // the asmjs
  1531. if (typeof Module['asm'] !== 'function' || Module['asm'] === methodHandler) {
  1532. if (!Module['asmPreload']) {
  1533. // you can load the .asm.js file before this, to avoid this sync xhr and eval
  1534. eval(Module['read'](asmjsCodeFile)); // set Module.asm
  1535. } else {
  1536. Module['asm'] = Module['asmPreload'];
  1537. }
  1538. }
  1539. if (typeof Module['asm'] !== 'function') {
  1540. Module['printErr']('asm evalling did not set the module properly');
  1541. return false;
  1542. }
  1543. return Module['asm'](global, env, providedBuffer);
  1544. }
  1545. function doNativeWasm(global, env, providedBuffer) {
  1546. if (typeof WebAssembly !== 'object') {
  1547. Module['printErr']('no native wasm support detected');
  1548. return false;
  1549. }
  1550. // prepare memory import
  1551. if (!(Module['wasmMemory'] instanceof WebAssembly.Memory)) {
  1552. Module['printErr']('no native wasm Memory in use');
  1553. return false;
  1554. }
  1555. env['memory'] = Module['wasmMemory'];
  1556. // Load the wasm module and create an instance of using native support in the JS engine.
  1557. info['global'] = {
  1558. 'NaN': NaN,
  1559. 'Infinity': Infinity
  1560. };
  1561. info['global.Math'] = global.Math;
  1562. info['env'] = env;
  1563. // handle a generated wasm instance, receiving its exports and
  1564. // performing other necessary setup
  1565. function receiveInstance(instance) {
  1566. exports = instance.exports;
  1567. if (exports.memory) mergeMemory(exports.memory);
  1568. Module['asm'] = exports;
  1569. Module["usingWasm"] = true;
  1570. removeRunDependency('wasm-instantiate');
  1571. }
  1572. addRunDependency('wasm-instantiate'); // we can't run yet
  1573. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  1574. // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
  1575. // to any other async startup actions they are performing.
  1576. if (Module['instantiateWasm']) {
  1577. try {
  1578. return Module['instantiateWasm'](info, receiveInstance);
  1579. } catch (e) {
  1580. Module['printErr']('Module.instantiateWasm callback failed with error: ' + e);
  1581. return false;
  1582. }
  1583. }
  1584. getBinaryPromise().then(function (binary) {
  1585. return WebAssembly.instantiate(binary, info)
  1586. }).then(function (output) {
  1587. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  1588. receiveInstance(output['instance']);
  1589. }).catch(function (reason) {
  1590. Module['printErr']('failed to asynchronously prepare wasm: ' + reason);
  1591. abort(reason);
  1592. });
  1593. return {}; // no exports yet; we'll fill them in later
  1594. }
  1595. function doWasmPolyfill(global, env, providedBuffer, method) {
  1596. if (typeof WasmJS !== 'function') {
  1597. Module['printErr']('WasmJS not detected - polyfill not bundled?');
  1598. return false;
  1599. }
  1600. // Use wasm.js to polyfill and execute code in a wasm interpreter.
  1601. var wasmJS = WasmJS({});
  1602. // XXX don't be confused. Module here is in the outside program. wasmJS is the inner wasm-js.cpp.
  1603. wasmJS['outside'] = Module; // Inside wasm-js.cpp, Module['outside'] reaches the outside module.
  1604. // Information for the instance of the module.
  1605. wasmJS['info'] = info;
  1606. wasmJS['lookupImport'] = lookupImport;
  1607. assert(providedBuffer === Module['buffer']); // we should not even need to pass it as a 3rd arg for wasm, but that's the asm.js way.
  1608. info.global = global;
  1609. info.env = env;
  1610. // polyfill interpreter expects an ArrayBuffer
  1611. assert(providedBuffer === Module['buffer']);
  1612. env['memory'] = providedBuffer;
  1613. assert(env['memory'] instanceof ArrayBuffer);
  1614. wasmJS['providedTotalMemory'] = Module['buffer'].byteLength;
  1615. // Prepare to generate wasm, using either asm2wasm or s-exprs
  1616. var code;
  1617. if (method === 'interpret-binary') {
  1618. code = getBinary();
  1619. } else {
  1620. code = Module['read'](method == 'interpret-asm2wasm' ? asmjsCodeFile : wasmTextFile);
  1621. }
  1622. var temp;
  1623. if (method == 'interpret-asm2wasm') {
  1624. temp = wasmJS['_malloc'](code.length + 1);
  1625. wasmJS['writeAsciiToMemory'](code, temp);
  1626. wasmJS['_load_asm2wasm'](temp);
  1627. } else if (method === 'interpret-s-expr') {
  1628. temp = wasmJS['_malloc'](code.length + 1);
  1629. wasmJS['writeAsciiToMemory'](code, temp);
  1630. wasmJS['_load_s_expr2wasm'](temp);
  1631. } else if (method === 'interpret-binary') {
  1632. temp = wasmJS['_malloc'](code.length);
  1633. wasmJS['HEAPU8'].set(code, temp);
  1634. wasmJS['_load_binary2wasm'](temp, code.length);
  1635. } else {
  1636. throw 'what? ' + method;
  1637. }
  1638. wasmJS['_free'](temp);
  1639. wasmJS['_instantiate'](temp);
  1640. if (Module['newBuffer']) {
  1641. mergeMemory(Module['newBuffer']);
  1642. Module['newBuffer'] = null;
  1643. }
  1644. exports = wasmJS['asmExports'];
  1645. return exports;
  1646. }
  1647. // We may have a preloaded value in Module.asm, save it
  1648. Module['asmPreload'] = Module['asm'];
  1649. // Memory growth integration code
  1650. var asmjsReallocBuffer = Module['reallocBuffer'];
  1651. var wasmReallocBuffer = function (size) {
  1652. var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; // In wasm, heap size must be a multiple of 64KB. In asm.js, they need to be multiples of 16MB.
  1653. size = alignUp(size, PAGE_MULTIPLE); // round up to wasm page size
  1654. var old = Module['buffer'];
  1655. var oldSize = old.byteLength;
  1656. if (Module["usingWasm"]) {
  1657. // native wasm support
  1658. try {
  1659. var result = Module['wasmMemory'].grow((size - oldSize) / wasmPageSize); // .grow() takes a delta compared to the previous size
  1660. if (result !== (-1 | 0)) {
  1661. // success in native wasm memory growth, get the buffer from the memory
  1662. return Module['buffer'] = Module['wasmMemory'].buffer;
  1663. } else {
  1664. return null;
  1665. }
  1666. } catch (e) {
  1667. return null;
  1668. }
  1669. } else {
  1670. // wasm interpreter support
  1671. exports['__growWasmMemory']((size - oldSize) / wasmPageSize); // tiny wasm method that just does grow_memory
  1672. // in interpreter, we replace Module.buffer if we allocate
  1673. return Module['buffer'] !== old ? Module['buffer'] : null; // if it was reallocated, it changed
  1674. }
  1675. };
  1676. Module['reallocBuffer'] = function (size) {
  1677. if (finalMethod === 'asmjs') {
  1678. return asmjsReallocBuffer(size);
  1679. } else {
  1680. return wasmReallocBuffer(size);
  1681. }
  1682. };
  1683. // we may try more than one; this is the final one, that worked and we are using
  1684. var finalMethod = '';
  1685. // Provide an "asm.js function" for the application, called to "link" the asm.js module. We instantiate
  1686. // the wasm module at that time, and it receives imports and provides exports and so forth, the app
  1687. // doesn't need to care that it is wasm or olyfilled wasm or asm.js.
  1688. Module['asm'] = function (global, env, providedBuffer) {
  1689. global = fixImports(global);
  1690. env = fixImports(env);
  1691. // import table
  1692. if (!env['table']) {
  1693. var TABLE_SIZE = Module['wasmTableSize'];
  1694. if (TABLE_SIZE === undefined) TABLE_SIZE = 1024; // works in binaryen interpreter at least
  1695. var MAX_TABLE_SIZE = Module['wasmMaxTableSize'];
  1696. if (typeof WebAssembly === 'object' && typeof WebAssembly.Table === 'function') {
  1697. if (MAX_TABLE_SIZE !== undefined) {
  1698. env['table'] = new WebAssembly.Table({ 'initial': TABLE_SIZE, 'maximum': MAX_TABLE_SIZE, 'element': 'anyfunc' });
  1699. } else {
  1700. env['table'] = new WebAssembly.Table({ 'initial': TABLE_SIZE, element: 'anyfunc' });
  1701. }
  1702. } else {
  1703. env['table'] = new Array(TABLE_SIZE); // works in binaryen interpreter at least
  1704. }
  1705. Module['wasmTable'] = env['table'];
  1706. }
  1707. if (!env['memoryBase']) {
  1708. env['memoryBase'] = Module['STATIC_BASE']; // tell the memory segments where to place themselves
  1709. }
  1710. if (!env['tableBase']) {
  1711. env['tableBase'] = 0; // table starts at 0 by default, in dynamic linking this will change
  1712. }
  1713. // try the methods. each should return the exports if it succeeded
  1714. var exports;
  1715. exports = doNativeWasm(global, env, providedBuffer);
  1716. return exports;
  1717. };
  1718. var methodHandler = Module['asm']; // note our method handler, as we may modify Module['asm'] later
  1719. }
  1720. integrateWasmJS(Module);
  1721. // === Body ===
  1722. var ASM_CONSTS = [];
  1723. STATIC_BASE = Runtime.GLOBAL_BASE;
  1724. STATICTOP = STATIC_BASE + 4533776;
  1725. /* global initializers */ __ATINIT__.push({ func: function () { __GLOBAL__I_000101() } }, { func: function () { __GLOBAL__sub_I_shaderc_js_cpp() } }, { func: function () { __GLOBAL__sub_I_SPVRemapper_cpp() } }, { func: function () { __GLOBAL__sub_I_doc_cpp() } }, { func: function () { __GLOBAL__sub_I_bind_cpp() } }, { func: function () { __GLOBAL__sub_I_iostream_cpp() } });
  1726. memoryInitializer = Module["wasmJSMethod"].indexOf("asmjs") >= 0 || Module["wasmJSMethod"].indexOf("interpret-asm2wasm") >= 0 ? "shaderc.js.mem" : null;
  1727. var STATIC_BUMP = 4533776;
  1728. Module["STATIC_BASE"] = STATIC_BASE;
  1729. Module["STATIC_BUMP"] = STATIC_BUMP;
  1730. /* no memory initializer */
  1731. var tempDoublePtr = STATICTOP; STATICTOP += 16;
  1732. function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
  1733. HEAP8[tempDoublePtr] = HEAP8[ptr];
  1734. HEAP8[tempDoublePtr + 1] = HEAP8[ptr + 1];
  1735. HEAP8[tempDoublePtr + 2] = HEAP8[ptr + 2];
  1736. HEAP8[tempDoublePtr + 3] = HEAP8[ptr + 3];
  1737. }
  1738. function copyTempDouble(ptr) {
  1739. HEAP8[tempDoublePtr] = HEAP8[ptr];
  1740. HEAP8[tempDoublePtr + 1] = HEAP8[ptr + 1];
  1741. HEAP8[tempDoublePtr + 2] = HEAP8[ptr + 2];
  1742. HEAP8[tempDoublePtr + 3] = HEAP8[ptr + 3];
  1743. HEAP8[tempDoublePtr + 4] = HEAP8[ptr + 4];
  1744. HEAP8[tempDoublePtr + 5] = HEAP8[ptr + 5];
  1745. HEAP8[tempDoublePtr + 6] = HEAP8[ptr + 6];
  1746. HEAP8[tempDoublePtr + 7] = HEAP8[ptr + 7];
  1747. }
  1748. // {{PRE_LIBRARY}}
  1749. function _atexit(func, arg) {
  1750. __ATEXIT__.unshift({ func: func, arg: arg });
  1751. } function ___cxa_atexit() {
  1752. return _atexit.apply(null, arguments)
  1753. }
  1754. function __ZSt18uncaught_exceptionv() { // std::uncaught_exception()
  1755. return !!__ZSt18uncaught_exceptionv.uncaught_exception;
  1756. }
  1757. var EXCEPTIONS = {
  1758. last: 0, caught: [], infos: {}, deAdjust: function (adjusted) {
  1759. if (!adjusted || EXCEPTIONS.infos[adjusted]) return adjusted;
  1760. for (var ptr in EXCEPTIONS.infos) {
  1761. var info = EXCEPTIONS.infos[ptr];
  1762. if (info.adjusted === adjusted) {
  1763. return ptr;
  1764. }
  1765. }
  1766. return adjusted;
  1767. }, addRef: function (ptr) {
  1768. if (!ptr) return;
  1769. var info = EXCEPTIONS.infos[ptr];
  1770. info.refcount++;
  1771. }, decRef: function (ptr) {
  1772. if (!ptr) return;
  1773. var info = EXCEPTIONS.infos[ptr];
  1774. assert(info.refcount > 0);
  1775. info.refcount--;
  1776. // A rethrown exception can reach refcount 0; it must not be discarded
  1777. // Its next handler will clear the rethrown flag and addRef it, prior to
  1778. // final decRef and destruction here
  1779. if (info.refcount === 0 && !info.rethrown) {
  1780. if (info.destructor) {
  1781. Module['dynCall_vi'](info.destructor, ptr);
  1782. }
  1783. delete EXCEPTIONS.infos[ptr];
  1784. ___cxa_free_exception(ptr);
  1785. }
  1786. }, clearRef: function (ptr) {
  1787. if (!ptr) return;
  1788. var info = EXCEPTIONS.infos[ptr];
  1789. info.refcount = 0;
  1790. }
  1791. };
  1792. function ___resumeException(ptr) {
  1793. if (!EXCEPTIONS.last) { EXCEPTIONS.last = ptr; }
  1794. throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch.";
  1795. } function ___cxa_find_matching_catch() {
  1796. var thrown = EXCEPTIONS.last;
  1797. if (!thrown) {
  1798. // just pass through the null ptr
  1799. return ((Runtime.setTempRet0(0), 0) | 0);
  1800. }
  1801. var info = EXCEPTIONS.infos[thrown];
  1802. var throwntype = info.type;
  1803. if (!throwntype) {
  1804. // just pass through the thrown ptr
  1805. return ((Runtime.setTempRet0(0), thrown) | 0);
  1806. }
  1807. var typeArray = Array.prototype.slice.call(arguments);
  1808. var pointer = Module['___cxa_is_pointer_type'](throwntype);
  1809. // can_catch receives a **, add indirection
  1810. if (!___cxa_find_matching_catch.buffer) ___cxa_find_matching_catch.buffer = _malloc(4);
  1811. HEAP32[((___cxa_find_matching_catch.buffer) >> 2)] = thrown;
  1812. thrown = ___cxa_find_matching_catch.buffer;
  1813. // The different catch blocks are denoted by different types.
  1814. // Due to inheritance, those types may not precisely match the
  1815. // type of the thrown object. Find one which matches, and
  1816. // return the type of the catch block which should be called.
  1817. for (var i = 0; i < typeArray.length; i++) {
  1818. if (typeArray[i] && Module['___cxa_can_catch'](typeArray[i], throwntype, thrown)) {
  1819. thrown = HEAP32[((thrown) >> 2)]; // undo indirection
  1820. info.adjusted = thrown;
  1821. return ((Runtime.setTempRet0(typeArray[i]), thrown) | 0);
  1822. }
  1823. }
  1824. // Shouldn't happen unless we have bogus data in typeArray
  1825. // or encounter a type for which emscripten doesn't have suitable
  1826. // typeinfo defined. Best-efforts match just in case.
  1827. thrown = HEAP32[((thrown) >> 2)]; // undo indirection
  1828. return ((Runtime.setTempRet0(throwntype), thrown) | 0);
  1829. } function ___cxa_throw(ptr, type, destructor) {
  1830. EXCEPTIONS.infos[ptr] = {
  1831. ptr: ptr,
  1832. adjusted: ptr,
  1833. type: type,
  1834. destructor: destructor,
  1835. refcount: 0,
  1836. caught: false,
  1837. rethrown: false
  1838. };
  1839. EXCEPTIONS.last = ptr;
  1840. if (!("uncaught_exception" in __ZSt18uncaught_exceptionv)) {
  1841. __ZSt18uncaught_exceptionv.uncaught_exception = 1;
  1842. } else {
  1843. __ZSt18uncaught_exceptionv.uncaught_exception++;
  1844. }
  1845. throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch.";
  1846. }
  1847. function getShiftFromSize(size) {
  1848. switch (size) {
  1849. case 1: return 0;
  1850. case 2: return 1;
  1851. case 4: return 2;
  1852. case 8: return 3;
  1853. default:
  1854. throw new TypeError('Unknown type size: ' + size);
  1855. }
  1856. }
  1857. function embind_init_charCodes() {
  1858. var codes = new Array(256);
  1859. for (var i = 0; i < 256; ++i) {
  1860. codes[i] = String.fromCharCode(i);
  1861. }
  1862. embind_charCodes = codes;
  1863. } var embind_charCodes = undefined; function readLatin1String(ptr) {
  1864. var ret = "";
  1865. var c = ptr;
  1866. while (HEAPU8[c]) {
  1867. ret += embind_charCodes[HEAPU8[c++]];
  1868. }
  1869. return ret;
  1870. }
  1871. var awaitingDependencies = {};
  1872. var registeredTypes = {};
  1873. var typeDependencies = {};
  1874. var char_0 = 48;
  1875. var char_9 = 57; function makeLegalFunctionName(name) {
  1876. if (undefined === name) {
  1877. return '_unknown';
  1878. }
  1879. name = name.replace(/[^a-zA-Z0-9_]/g, '$');
  1880. var f = name.charCodeAt(0);
  1881. if (f >= char_0 && f <= char_9) {
  1882. return '_' + name;
  1883. } else {
  1884. return name;
  1885. }
  1886. } function createNamedFunction(name, body) {
  1887. name = makeLegalFunctionName(name);
  1888. /*jshint evil:true*/
  1889. return new Function(
  1890. "body",
  1891. "return function " + name + "() {\n" +
  1892. " \"use strict\";" +
  1893. " return body.apply(this, arguments);\n" +
  1894. "};\n"
  1895. )(body);
  1896. } function extendError(baseErrorType, errorName) {
  1897. var errorClass = createNamedFunction(errorName, function (message) {
  1898. this.name = errorName;
  1899. this.message = message;
  1900. var stack = (new Error(message)).stack;
  1901. if (stack !== undefined) {
  1902. this.stack = this.toString() + '\n' +
  1903. stack.replace(/^Error(:[^\n]*)?\n/, '');
  1904. }
  1905. });
  1906. errorClass.prototype = Object.create(baseErrorType.prototype);
  1907. errorClass.prototype.constructor = errorClass;
  1908. errorClass.prototype.toString = function () {
  1909. if (this.message === undefined) {
  1910. return this.name;
  1911. } else {
  1912. return this.name + ': ' + this.message;
  1913. }
  1914. };
  1915. return errorClass;
  1916. } var BindingError = undefined; function throwBindingError(message) {
  1917. throw new BindingError(message);
  1918. }
  1919. var InternalError = undefined; function throwInternalError(message) {
  1920. throw new InternalError(message);
  1921. } function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) {
  1922. myTypes.forEach(function (type) {
  1923. typeDependencies[type] = dependentTypes;
  1924. });
  1925. function onComplete(typeConverters) {
  1926. var myTypeConverters = getTypeConverters(typeConverters);
  1927. if (myTypeConverters.length !== myTypes.length) {
  1928. throwInternalError('Mismatched type converter count');
  1929. }
  1930. for (var i = 0; i < myTypes.length; ++i) {
  1931. registerType(myTypes[i], myTypeConverters[i]);
  1932. }
  1933. }
  1934. var typeConverters = new Array(dependentTypes.length);
  1935. var unregisteredTypes = [];
  1936. var registered = 0;
  1937. dependentTypes.forEach(function (dt, i) {
  1938. if (registeredTypes.hasOwnProperty(dt)) {
  1939. typeConverters[i] = registeredTypes[dt];
  1940. } else {
  1941. unregisteredTypes.push(dt);
  1942. if (!awaitingDependencies.hasOwnProperty(dt)) {
  1943. awaitingDependencies[dt] = [];
  1944. }
  1945. awaitingDependencies[dt].push(function () {
  1946. typeConverters[i] = registeredTypes[dt];
  1947. ++registered;
  1948. if (registered === unregisteredTypes.length) {
  1949. onComplete(typeConverters);
  1950. }
  1951. });
  1952. }
  1953. });
  1954. if (0 === unregisteredTypes.length) {
  1955. onComplete(typeConverters);
  1956. }
  1957. } function registerType(rawType, registeredInstance, options) {
  1958. options = options || {};
  1959. if (!('argPackAdvance' in registeredInstance)) {
  1960. throw new TypeError('registerType registeredInstance requires argPackAdvance');
  1961. }
  1962. var name = registeredInstance.name;
  1963. if (!rawType) {
  1964. throwBindingError('type "' + name + '" must have a positive integer typeid pointer');
  1965. }
  1966. if (registeredTypes.hasOwnProperty(rawType)) {
  1967. if (options.ignoreDuplicateRegistrations) {
  1968. return;
  1969. } else {
  1970. throwBindingError("Cannot register type '" + name + "' twice");
  1971. }
  1972. }
  1973. registeredTypes[rawType] = registeredInstance;
  1974. delete typeDependencies[rawType];
  1975. if (awaitingDependencies.hasOwnProperty(rawType)) {
  1976. var callbacks = awaitingDependencies[rawType];
  1977. delete awaitingDependencies[rawType];
  1978. callbacks.forEach(function (cb) {
  1979. cb();
  1980. });
  1981. }
  1982. } function __embind_register_bool(rawType, name, size, trueValue, falseValue) {
  1983. var shift = getShiftFromSize(size);
  1984. name = readLatin1String(name);
  1985. registerType(rawType, {
  1986. name: name,
  1987. 'fromWireType': function (wt) {
  1988. // ambiguous emscripten ABI: sometimes return values are
  1989. // true or false, and sometimes integers (0 or 1)
  1990. return !!wt;
  1991. },
  1992. 'toWireType': function (destructors, o) {
  1993. return o ? trueValue : falseValue;
  1994. },
  1995. 'argPackAdvance': 8,
  1996. 'readValueFromPointer': function (pointer) {
  1997. // TODO: if heap is fixed (like in asm.js) this could be executed outside
  1998. var heap;
  1999. if (size === 1) {
  2000. heap = HEAP8;
  2001. } else if (size === 2) {
  2002. heap = HEAP16;
  2003. } else if (size === 4) {
  2004. heap = HEAP32;
  2005. } else {
  2006. throw new TypeError("Unknown boolean type size: " + name);
  2007. }
  2008. return this['fromWireType'](heap[pointer >> shift]);
  2009. },
  2010. destructorFunction: null, // This type does not need a destructor
  2011. });
  2012. }
  2013. function simpleReadValueFromPointer(pointer) {
  2014. return this['fromWireType'](HEAPU32[pointer >> 2]);
  2015. } function __embind_register_std_string(rawType, name) {
  2016. name = readLatin1String(name);
  2017. registerType(rawType, {
  2018. name: name,
  2019. 'fromWireType': function (value) {
  2020. var length = HEAPU32[value >> 2];
  2021. var a = new Array(length);
  2022. for (var i = 0; i < length; ++i) {
  2023. a[i] = String.fromCharCode(HEAPU8[value + 4 + i]);
  2024. }
  2025. _free(value);
  2026. return a.join('');
  2027. },
  2028. 'toWireType': function (destructors, value) {
  2029. if (value instanceof ArrayBuffer) {
  2030. value = new Uint8Array(value);
  2031. }
  2032. function getTAElement(ta, index) {
  2033. return ta[index];
  2034. }
  2035. function getStringElement(string, index) {
  2036. return string.charCodeAt(index);
  2037. }
  2038. var getElement;
  2039. if (value instanceof Uint8Array) {
  2040. getElement = getTAElement;
  2041. } else if (value instanceof Uint8ClampedArray) {
  2042. getElement = getTAElement;
  2043. } else if (value instanceof Int8Array) {
  2044. getElement = getTAElement;
  2045. } else if (typeof value === 'string') {
  2046. getElement = getStringElement;
  2047. } else {
  2048. throwBindingError('Cannot pass non-string to std::string');
  2049. }
  2050. // assumes 4-byte alignment
  2051. var length = value.length;
  2052. var ptr = _malloc(4 + length);
  2053. HEAPU32[ptr >> 2] = length;
  2054. for (var i = 0; i < length; ++i) {
  2055. var charCode = getElement(value, i);
  2056. if (charCode > 255) {
  2057. _free(ptr);
  2058. throwBindingError('String has UTF-16 code units that do not fit in 8 bits');
  2059. }
  2060. HEAPU8[ptr + 4 + i] = charCode;
  2061. }
  2062. if (destructors !== null) {
  2063. destructors.push(_free, ptr);
  2064. }
  2065. return ptr;
  2066. },
  2067. 'argPackAdvance': 8,
  2068. 'readValueFromPointer': simpleReadValueFromPointer,
  2069. destructorFunction: function (ptr) { _free(ptr); },
  2070. });
  2071. }
  2072. function _embind_repr(v) {
  2073. if (v === null) {
  2074. return 'null';
  2075. }
  2076. var t = typeof v;
  2077. if (t === 'object' || t === 'array' || t === 'function') {
  2078. return v.toString();
  2079. } else {
  2080. return '' + v;
  2081. }
  2082. }
  2083. function integerReadValueFromPointer(name, shift, signed) {
  2084. // integers are quite common, so generate very specialized functions
  2085. switch (shift) {
  2086. case 0: return signed ?
  2087. function readS8FromPointer(pointer) { return HEAP8[pointer]; } :
  2088. function readU8FromPointer(pointer) { return HEAPU8[pointer]; };
  2089. case 1: return signed ?
  2090. function readS16FromPointer(pointer) { return HEAP16[pointer >> 1]; } :
  2091. function readU16FromPointer(pointer) { return HEAPU16[pointer >> 1]; };
  2092. case 2: return signed ?
  2093. function readS32FromPointer(pointer) { return HEAP32[pointer >> 2]; } :
  2094. function readU32FromPointer(pointer) { return HEAPU32[pointer >> 2]; };
  2095. default:
  2096. throw new TypeError("Unknown integer type: " + name);
  2097. }
  2098. } function __embind_register_integer(primitiveType, name, size, minRange, maxRange) {
  2099. name = readLatin1String(name);
  2100. if (maxRange === -1) { // LLVM doesn't have signed and unsigned 32-bit types, so u32 literals come out as 'i32 -1'. Always treat those as max u32.
  2101. maxRange = 4294967295;
  2102. }
  2103. var shift = getShiftFromSize(size);
  2104. var fromWireType = function (value) {
  2105. return value;
  2106. };
  2107. if (minRange === 0) {
  2108. var bitshift = 32 - 8 * size;
  2109. fromWireType = function (value) {
  2110. return (value << bitshift) >>> bitshift;
  2111. };
  2112. }
  2113. var isUnsignedType = (name.indexOf('unsigned') != -1);
  2114. registerType(primitiveType, {
  2115. name: name,
  2116. 'fromWireType': fromWireType,
  2117. 'toWireType': function (destructors, value) {
  2118. // todo: Here we have an opportunity for -O3 level "unsafe" optimizations: we could
  2119. // avoid the following two if()s and assume value is of proper type.
  2120. if (typeof value !== "number" && typeof value !== "boolean") {
  2121. throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name);
  2122. }
  2123. if (value < minRange || value > maxRange) {
  2124. throw new TypeError('Passing a number "' + _embind_repr(value) + '" from JS side to C/C++ side to an argument of type "' + name + '", which is outside the valid range [' + minRange + ', ' + maxRange + ']!');
  2125. }
  2126. return isUnsignedType ? (value >>> 0) : (value | 0);
  2127. },
  2128. 'argPackAdvance': 8,
  2129. 'readValueFromPointer': integerReadValueFromPointer(name, shift, minRange !== 0),
  2130. destructorFunction: null, // This type does not need a destructor
  2131. });
  2132. }
  2133. function _pthread_mutex_init() { }
  2134. var emval_free_list = [];
  2135. var emval_handle_array = [{}, { value: undefined }, { value: null }, { value: true }, { value: false }]; function __emval_decref(handle) {
  2136. if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
  2137. emval_handle_array[handle] = undefined;
  2138. emval_free_list.push(handle);
  2139. }
  2140. }
  2141. var PTHREAD_SPECIFIC = {};
  2142. var PTHREAD_SPECIFIC_NEXT_KEY = 1;
  2143. var ERRNO_CODES = { EPERM: 1, ENOENT: 2, ESRCH: 3, EINTR: 4, EIO: 5, ENXIO: 6, E2BIG: 7, ENOEXEC: 8, EBADF: 9, ECHILD: 10, EAGAIN: 11, EWOULDBLOCK: 11, ENOMEM: 12, EACCES: 13, EFAULT: 14, ENOTBLK: 15, EBUSY: 16, EEXIST: 17, EXDEV: 18, ENODEV: 19, ENOTDIR: 20, EISDIR: 21, EINVAL: 22, ENFILE: 23, EMFILE: 24, ENOTTY: 25, ETXTBSY: 26, EFBIG: 27, ENOSPC: 28, ESPIPE: 29, EROFS: 30, EMLINK: 31, EPIPE: 32, EDOM: 33, ERANGE: 34, ENOMSG: 42, EIDRM: 43, ECHRNG: 44, EL2NSYNC: 45, EL3HLT: 46, EL3RST: 47, ELNRNG: 48, EUNATCH: 49, ENOCSI: 50, EL2HLT: 51, EDEADLK: 35, ENOLCK: 37, EBADE: 52, EBADR: 53, EXFULL: 54, ENOANO: 55, EBADRQC: 56, EBADSLT: 57, EDEADLOCK: 35, EBFONT: 59, ENOSTR: 60, ENODATA: 61, ETIME: 62, ENOSR: 63, ENONET: 64, ENOPKG: 65, EREMOTE: 66, ENOLINK: 67, EADV: 68, ESRMNT: 69, ECOMM: 70, EPROTO: 71, EMULTIHOP: 72, EDOTDOT: 73, EBADMSG: 74, ENOTUNIQ: 76, EBADFD: 77, EREMCHG: 78, ELIBACC: 79, ELIBBAD: 80, ELIBSCN: 81, ELIBMAX: 82, ELIBEXEC: 83, ENOSYS: 38, ENOTEMPTY: 39, ENAMETOOLONG: 36, ELOOP: 40, EOPNOTSUPP: 95, EPFNOSUPPORT: 96, ECONNRESET: 104, ENOBUFS: 105, EAFNOSUPPORT: 97, EPROTOTYPE: 91, ENOTSOCK: 88, ENOPROTOOPT: 92, ESHUTDOWN: 108, ECONNREFUSED: 111, EADDRINUSE: 98, ECONNABORTED: 103, ENETUNREACH: 101, ENETDOWN: 100, ETIMEDOUT: 110, EHOSTDOWN: 112, EHOSTUNREACH: 113, EINPROGRESS: 115, EALREADY: 114, EDESTADDRREQ: 89, EMSGSIZE: 90, EPROTONOSUPPORT: 93, ESOCKTNOSUPPORT: 94, EADDRNOTAVAIL: 99, ENETRESET: 102, EISCONN: 106, ENOTCONN: 107, ETOOMANYREFS: 109, EUSERS: 87, EDQUOT: 122, ESTALE: 116, ENOTSUP: 95, ENOMEDIUM: 123, EILSEQ: 84, EOVERFLOW: 75, ECANCELED: 125, ENOTRECOVERABLE: 131, EOWNERDEAD: 130, ESTRPIPE: 86 }; function _pthread_key_create(key, destructor) {
  2144. if (key == 0) {
  2145. return ERRNO_CODES.EINVAL;
  2146. }
  2147. HEAP32[((key) >> 2)] = PTHREAD_SPECIFIC_NEXT_KEY;
  2148. // values start at 0
  2149. PTHREAD_SPECIFIC[PTHREAD_SPECIFIC_NEXT_KEY] = 0;
  2150. PTHREAD_SPECIFIC_NEXT_KEY++;
  2151. return 0;
  2152. }
  2153. function count_emval_handles() {
  2154. var count = 0;
  2155. for (var i = 5; i < emval_handle_array.length; ++i) {
  2156. if (emval_handle_array[i] !== undefined) {
  2157. ++count;
  2158. }
  2159. }
  2160. return count;
  2161. }
  2162. function get_first_emval() {
  2163. for (var i = 5; i < emval_handle_array.length; ++i) {
  2164. if (emval_handle_array[i] !== undefined) {
  2165. return emval_handle_array[i];
  2166. }
  2167. }
  2168. return null;
  2169. } function init_emval() {
  2170. Module['count_emval_handles'] = count_emval_handles;
  2171. Module['get_first_emval'] = get_first_emval;
  2172. } function __emval_register(value) {
  2173. switch (value) {
  2174. case undefined: { return 1; }
  2175. case null: { return 2; }
  2176. case true: { return 3; }
  2177. case false: { return 4; }
  2178. default: {
  2179. var handle = emval_free_list.length ?
  2180. emval_free_list.pop() :
  2181. emval_handle_array.length;
  2182. emval_handle_array[handle] = { refcount: 1, value: value };
  2183. return handle;
  2184. }
  2185. }
  2186. }
  2187. function getTypeName(type) {
  2188. var ptr = ___getTypeName(type);
  2189. var rv = readLatin1String(ptr);
  2190. _free(ptr);
  2191. return rv;
  2192. } function requireRegisteredType(rawType, humanName) {
  2193. var impl = registeredTypes[rawType];
  2194. if (undefined === impl) {
  2195. throwBindingError(humanName + " has unknown type " + getTypeName(rawType));
  2196. }
  2197. return impl;
  2198. } function __emval_take_value(type, argv) {
  2199. type = requireRegisteredType(type, '_emval_take_value');
  2200. var v = type['readValueFromPointer'](argv);
  2201. return __emval_register(v);
  2202. }
  2203. var ERRNO_MESSAGES = { 0: "Success", 1: "Not super-user", 2: "No such file or directory", 3: "No such process", 4: "Interrupted system call", 5: "I/O error", 6: "No such device or address", 7: "Arg list too long", 8: "Exec format error", 9: "Bad file number", 10: "No children", 11: "No more processes", 12: "Not enough core", 13: "Permission denied", 14: "Bad address", 15: "Block device required", 16: "Mount device busy", 17: "File exists", 18: "Cross-device link", 19: "No such device", 20: "Not a directory", 21: "Is a directory", 22: "Invalid argument", 23: "Too many open files in system", 24: "Too many open files", 25: "Not a typewriter", 26: "Text file busy", 27: "File too large", 28: "No space left on device", 29: "Illegal seek", 30: "Read only file system", 31: "Too many links", 32: "Broken pipe", 33: "Math arg out of domain of func", 34: "Math result not representable", 35: "File locking deadlock error", 36: "File or path name too long", 37: "No record locks available", 38: "Function not implemented", 39: "Directory not empty", 40: "Too many symbolic links", 42: "No message of desired type", 43: "Identifier removed", 44: "Channel number out of range", 45: "Level 2 not synchronized", 46: "Level 3 halted", 47: "Level 3 reset", 48: "Link number out of range", 49: "Protocol driver not attached", 50: "No CSI structure available", 51: "Level 2 halted", 52: "Invalid exchange", 53: "Invalid request descriptor", 54: "Exchange full", 55: "No anode", 56: "Invalid request code", 57: "Invalid slot", 59: "Bad font file fmt", 60: "Device not a stream", 61: "No data (for no delay io)", 62: "Timer expired", 63: "Out of streams resources", 64: "Machine is not on the network", 65: "Package not installed", 66: "The object is remote", 67: "The link has been severed", 68: "Advertise error", 69: "Srmount error", 70: "Communication error on send", 71: "Protocol error", 72: "Multihop attempted", 73: "Cross mount point (not really error)", 74: "Trying to read unreadable message", 75: "Value too large for defined data type", 76: "Given log. name not unique", 77: "f.d. invalid for this operation", 78: "Remote address changed", 79: "Can access a needed shared lib", 80: "Accessing a corrupted shared lib", 81: ".lib section in a.out corrupted", 82: "Attempting to link in too many libs", 83: "Attempting to exec a shared library", 84: "Illegal byte sequence", 86: "Streams pipe error", 87: "Too many users", 88: "Socket operation on non-socket", 89: "Destination address required", 90: "Message too long", 91: "Protocol wrong type for socket", 92: "Protocol not available", 93: "Unknown protocol", 94: "Socket type not supported", 95: "Not supported", 96: "Protocol family not supported", 97: "Address family not supported by protocol family", 98: "Address already in use", 99: "Address not available", 100: "Network interface is not configured", 101: "Network is unreachable", 102: "Connection reset by network", 103: "Connection aborted", 104: "Connection reset by peer", 105: "No buffer space available", 106: "Socket is already connected", 107: "Socket is not connected", 108: "Can't send after socket shutdown", 109: "Too many references", 110: "Connection timed out", 111: "Connection refused", 112: "Host is down", 113: "Host is unreachable", 114: "Socket already connected", 115: "Connection already in progress", 116: "Stale file handle", 122: "Quota exceeded", 123: "No medium (in tape drive)", 125: "Operation canceled", 130: "Previous owner died", 131: "State not recoverable" };
  2204. function ___setErrNo(value) {
  2205. if (Module['___errno_location']) HEAP32[((Module['___errno_location']()) >> 2)] = value;
  2206. return value;
  2207. }
  2208. var PATH = {
  2209. splitPath: function (filename) {
  2210. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  2211. return splitPathRe.exec(filename).slice(1);
  2212. }, normalizeArray: function (parts, allowAboveRoot) {
  2213. // if the path tries to go above the root, `up` ends up > 0
  2214. var up = 0;
  2215. for (var i = parts.length - 1; i >= 0; i--) {
  2216. var last = parts[i];
  2217. if (last === '.') {
  2218. parts.splice(i, 1);
  2219. } else if (last === '..') {
  2220. parts.splice(i, 1);
  2221. up++;
  2222. } else if (up) {
  2223. parts.splice(i, 1);
  2224. up--;
  2225. }
  2226. }
  2227. // if the path is allowed to go above the root, restore leading ..s
  2228. if (allowAboveRoot) {
  2229. for (; up; up--) {
  2230. parts.unshift('..');
  2231. }
  2232. }
  2233. return parts;
  2234. }, normalize: function (path) {
  2235. var isAbsolute = path.charAt(0) === '/',
  2236. trailingSlash = path.substr(-1) === '/';
  2237. // Normalize the path
  2238. path = PATH.normalizeArray(path.split('/').filter(function (p) {
  2239. return !!p;
  2240. }), !isAbsolute).join('/');
  2241. if (!path && !isAbsolute) {
  2242. path = '.';
  2243. }
  2244. if (path && trailingSlash) {
  2245. path += '/';
  2246. }
  2247. return (isAbsolute ? '/' : '') + path;
  2248. }, dirname: function (path) {
  2249. var result = PATH.splitPath(path),
  2250. root = result[0],
  2251. dir = result[1];
  2252. if (!root && !dir) {
  2253. // No dirname whatsoever
  2254. return '.';
  2255. }
  2256. if (dir) {
  2257. // It has a dirname, strip trailing slash
  2258. dir = dir.substr(0, dir.length - 1);
  2259. }
  2260. return root + dir;
  2261. }, basename: function (path) {
  2262. // EMSCRIPTEN return '/'' for '/', not an empty string
  2263. if (path === '/') return '/';
  2264. var lastSlash = path.lastIndexOf('/');
  2265. if (lastSlash === -1) return path;
  2266. return path.substr(lastSlash + 1);
  2267. }, extname: function (path) {
  2268. return PATH.splitPath(path)[3];
  2269. }, join: function () {
  2270. var paths = Array.prototype.slice.call(arguments, 0);
  2271. return PATH.normalize(paths.join('/'));
  2272. }, join2: function (l, r) {
  2273. return PATH.normalize(l + '/' + r);
  2274. }, resolve: function () {
  2275. var resolvedPath = '',
  2276. resolvedAbsolute = false;
  2277. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  2278. var path = (i >= 0) ? arguments[i] : FS.cwd();
  2279. // Skip empty and invalid entries
  2280. if (typeof path !== 'string') {
  2281. throw new TypeError('Arguments to path.resolve must be strings');
  2282. } else if (!path) {
  2283. return ''; // an invalid portion invalidates the whole thing
  2284. }
  2285. resolvedPath = path + '/' + resolvedPath;
  2286. resolvedAbsolute = path.charAt(0) === '/';
  2287. }
  2288. // At this point the path should be resolved to a full absolute path, but
  2289. // handle relative paths to be safe (might happen when process.cwd() fails)
  2290. resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function (p) {
  2291. return !!p;
  2292. }), !resolvedAbsolute).join('/');
  2293. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  2294. }, relative: function (from, to) {
  2295. from = PATH.resolve(from).substr(1);
  2296. to = PATH.resolve(to).substr(1);
  2297. function trim(arr) {
  2298. var start = 0;
  2299. for (; start < arr.length; start++) {
  2300. if (arr[start] !== '') break;
  2301. }
  2302. var end = arr.length - 1;
  2303. for (; end >= 0; end--) {
  2304. if (arr[end] !== '') break;
  2305. }
  2306. if (start > end) return [];
  2307. return arr.slice(start, end - start + 1);
  2308. }
  2309. var fromParts = trim(from.split('/'));
  2310. var toParts = trim(to.split('/'));
  2311. var length = Math.min(fromParts.length, toParts.length);
  2312. var samePartsLength = length;
  2313. for (var i = 0; i < length; i++) {
  2314. if (fromParts[i] !== toParts[i]) {
  2315. samePartsLength = i;
  2316. break;
  2317. }
  2318. }
  2319. var outputParts = [];
  2320. for (var i = samePartsLength; i < fromParts.length; i++) {
  2321. outputParts.push('..');
  2322. }
  2323. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  2324. return outputParts.join('/');
  2325. }
  2326. };
  2327. var TTY = {
  2328. ttys: [], init: function () {
  2329. // https://github.com/kripken/emscripten/pull/1555
  2330. // if (ENVIRONMENT_IS_NODE) {
  2331. // // currently, FS.init does not distinguish if process.stdin is a file or TTY
  2332. // // device, it always assumes it's a TTY device. because of this, we're forcing
  2333. // // process.stdin to UTF8 encoding to at least make stdin reading compatible
  2334. // // with text files until FS.init can be refactored.
  2335. // process['stdin']['setEncoding']('utf8');
  2336. // }
  2337. }, shutdown: function () {
  2338. // https://github.com/kripken/emscripten/pull/1555
  2339. // if (ENVIRONMENT_IS_NODE) {
  2340. // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
  2341. // // 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
  2342. // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
  2343. // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
  2344. // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
  2345. // process['stdin']['pause']();
  2346. // }
  2347. }, register: function (dev, ops) {
  2348. TTY.ttys[dev] = { input: [], output: [], ops: ops };
  2349. FS.registerDevice(dev, TTY.stream_ops);
  2350. }, stream_ops: {
  2351. open: function (stream) {
  2352. var tty = TTY.ttys[stream.node.rdev];
  2353. if (!tty) {
  2354. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  2355. }
  2356. stream.tty = tty;
  2357. stream.seekable = false;
  2358. }, close: function (stream) {
  2359. // flush any pending line data
  2360. stream.tty.ops.flush(stream.tty);
  2361. }, flush: function (stream) {
  2362. stream.tty.ops.flush(stream.tty);
  2363. }, read: function (stream, buffer, offset, length, pos /* ignored */) {
  2364. if (!stream.tty || !stream.tty.ops.get_char) {
  2365. throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
  2366. }
  2367. var bytesRead = 0;
  2368. for (var i = 0; i < length; i++) {
  2369. var result;
  2370. try {
  2371. result = stream.tty.ops.get_char(stream.tty);
  2372. } catch (e) {
  2373. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  2374. }
  2375. if (result === undefined && bytesRead === 0) {
  2376. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  2377. }
  2378. if (result === null || result === undefined) break;
  2379. bytesRead++;
  2380. buffer[offset + i] = result;
  2381. }
  2382. if (bytesRead) {
  2383. stream.node.timestamp = Date.now();
  2384. }
  2385. return bytesRead;
  2386. }, write: function (stream, buffer, offset, length, pos) {
  2387. if (!stream.tty || !stream.tty.ops.put_char) {
  2388. throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
  2389. }
  2390. for (var i = 0; i < length; i++) {
  2391. try {
  2392. stream.tty.ops.put_char(stream.tty, buffer[offset + i]);
  2393. } catch (e) {
  2394. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  2395. }
  2396. }
  2397. if (length) {
  2398. stream.node.timestamp = Date.now();
  2399. }
  2400. return i;
  2401. }
  2402. }, default_tty_ops: {
  2403. get_char: function (tty) {
  2404. if (!tty.input.length) {
  2405. var result = null;
  2406. if (ENVIRONMENT_IS_NODE) {
  2407. // we will read data by chunks of BUFSIZE
  2408. var BUFSIZE = 256;
  2409. var buf = new Buffer(BUFSIZE);
  2410. var bytesRead = 0;
  2411. var isPosixPlatform = (process.platform != 'win32'); // Node doesn't offer a direct check, so test by exclusion
  2412. var fd = process.stdin.fd;
  2413. if (isPosixPlatform) {
  2414. // Linux and Mac cannot use process.stdin.fd (which isn't set up as sync)
  2415. var usingDevice = false;
  2416. try {
  2417. fd = fs.openSync('/dev/stdin', 'r');
  2418. usingDevice = true;
  2419. } catch (e) { }
  2420. }
  2421. try {
  2422. bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null);
  2423. } catch (e) {
  2424. // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
  2425. // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
  2426. if (e.toString().indexOf('EOF') != -1) bytesRead = 0;
  2427. else throw e;
  2428. }
  2429. if (usingDevice) { fs.closeSync(fd); }
  2430. if (bytesRead > 0) {
  2431. result = buf.slice(0, bytesRead).toString('utf-8');
  2432. } else {
  2433. result = null;
  2434. }
  2435. } else if (typeof window != 'undefined' &&
  2436. typeof window.prompt == 'function') {
  2437. // Browser.
  2438. result = window.prompt('Input: '); // returns null on cancel
  2439. if (result !== null) {
  2440. result += '\n';
  2441. }
  2442. } else if (typeof readline == 'function') {
  2443. // Command line.
  2444. result = readline();
  2445. if (result !== null) {
  2446. result += '\n';
  2447. }
  2448. }
  2449. if (!result) {
  2450. return null;
  2451. }
  2452. tty.input = intArrayFromString(result, true);
  2453. }
  2454. return tty.input.shift();
  2455. }, put_char: function (tty, val) {
  2456. if (val === null || val === 10) {
  2457. Module['print'](UTF8ArrayToString(tty.output, 0));
  2458. tty.output = [];
  2459. } else {
  2460. if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
  2461. }
  2462. }, flush: function (tty) {
  2463. if (tty.output && tty.output.length > 0) {
  2464. Module['print'](UTF8ArrayToString(tty.output, 0));
  2465. tty.output = [];
  2466. }
  2467. }
  2468. }, default_tty1_ops: {
  2469. put_char: function (tty, val) {
  2470. if (val === null || val === 10) {
  2471. Module['printErr'](UTF8ArrayToString(tty.output, 0));
  2472. tty.output = [];
  2473. } else {
  2474. if (val != 0) tty.output.push(val);
  2475. }
  2476. }, flush: function (tty) {
  2477. if (tty.output && tty.output.length > 0) {
  2478. Module['printErr'](UTF8ArrayToString(tty.output, 0));
  2479. tty.output = [];
  2480. }
  2481. }
  2482. }
  2483. };
  2484. var MEMFS = {
  2485. ops_table: null, mount: function (mount) {
  2486. return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  2487. }, createNode: function (parent, name, mode, dev) {
  2488. if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
  2489. // no supported
  2490. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  2491. }
  2492. if (!MEMFS.ops_table) {
  2493. MEMFS.ops_table = {
  2494. dir: {
  2495. node: {
  2496. getattr: MEMFS.node_ops.getattr,
  2497. setattr: MEMFS.node_ops.setattr,
  2498. lookup: MEMFS.node_ops.lookup,
  2499. mknod: MEMFS.node_ops.mknod,
  2500. rename: MEMFS.node_ops.rename,
  2501. unlink: MEMFS.node_ops.unlink,
  2502. rmdir: MEMFS.node_ops.rmdir,
  2503. readdir: MEMFS.node_ops.readdir,
  2504. symlink: MEMFS.node_ops.symlink
  2505. },
  2506. stream: {
  2507. llseek: MEMFS.stream_ops.llseek
  2508. }
  2509. },
  2510. file: {
  2511. node: {
  2512. getattr: MEMFS.node_ops.getattr,
  2513. setattr: MEMFS.node_ops.setattr
  2514. },
  2515. stream: {
  2516. llseek: MEMFS.stream_ops.llseek,
  2517. read: MEMFS.stream_ops.read,
  2518. write: MEMFS.stream_ops.write,
  2519. allocate: MEMFS.stream_ops.allocate,
  2520. mmap: MEMFS.stream_ops.mmap,
  2521. msync: MEMFS.stream_ops.msync
  2522. }
  2523. },
  2524. link: {
  2525. node: {
  2526. getattr: MEMFS.node_ops.getattr,
  2527. setattr: MEMFS.node_ops.setattr,
  2528. readlink: MEMFS.node_ops.readlink
  2529. },
  2530. stream: {}
  2531. },
  2532. chrdev: {
  2533. node: {
  2534. getattr: MEMFS.node_ops.getattr,
  2535. setattr: MEMFS.node_ops.setattr
  2536. },
  2537. stream: FS.chrdev_stream_ops
  2538. }
  2539. };
  2540. }
  2541. var node = FS.createNode(parent, name, mode, dev);
  2542. if (FS.isDir(node.mode)) {
  2543. node.node_ops = MEMFS.ops_table.dir.node;
  2544. node.stream_ops = MEMFS.ops_table.dir.stream;
  2545. node.contents = {};
  2546. } else if (FS.isFile(node.mode)) {
  2547. node.node_ops = MEMFS.ops_table.file.node;
  2548. node.stream_ops = MEMFS.ops_table.file.stream;
  2549. node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
  2550. // When the byte data of the file is populated, this will point to either a typed array, or a normal JS array. Typed arrays are preferred
  2551. // for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
  2552. // penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
  2553. node.contents = null;
  2554. } else if (FS.isLink(node.mode)) {
  2555. node.node_ops = MEMFS.ops_table.link.node;
  2556. node.stream_ops = MEMFS.ops_table.link.stream;
  2557. } else if (FS.isChrdev(node.mode)) {
  2558. node.node_ops = MEMFS.ops_table.chrdev.node;
  2559. node.stream_ops = MEMFS.ops_table.chrdev.stream;
  2560. }
  2561. node.timestamp = Date.now();
  2562. // add the new node to the parent
  2563. if (parent) {
  2564. parent.contents[name] = node;
  2565. }
  2566. return node;
  2567. }, getFileDataAsRegularArray: function (node) {
  2568. if (node.contents && node.contents.subarray) {
  2569. var arr = [];
  2570. for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]);
  2571. return arr; // Returns a copy of the original data.
  2572. }
  2573. return node.contents; // No-op, the file contents are already in a JS array. Return as-is.
  2574. }, getFileDataAsTypedArray: function (node) {
  2575. if (!node.contents) return new Uint8Array;
  2576. if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
  2577. return new Uint8Array(node.contents);
  2578. }, expandFileStorage: function (node, newCapacity) {
  2579. // If we are asked to expand the size of a file that already exists, revert to using a standard JS array to store the file
  2580. // instead of a typed array. This makes resizing the array more flexible because we can just .push() elements at the back to
  2581. // increase the size.
  2582. if (node.contents && node.contents.subarray && newCapacity > node.contents.length) {
  2583. node.contents = MEMFS.getFileDataAsRegularArray(node);
  2584. node.usedBytes = node.contents.length; // We might be writing to a lazy-loaded file which had overridden this property, so force-reset it.
  2585. }
  2586. if (!node.contents || node.contents.subarray) { // Keep using a typed array if creating a new storage, or if old one was a typed array as well.
  2587. var prevCapacity = node.contents ? node.contents.length : 0;
  2588. if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
  2589. // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
  2590. // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
  2591. // avoid overshooting the allocation cap by a very large margin.
  2592. var CAPACITY_DOUBLING_MAX = 1024 * 1024;
  2593. newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) | 0);
  2594. if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
  2595. var oldContents = node.contents;
  2596. node.contents = new Uint8Array(newCapacity); // Allocate new storage.
  2597. if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
  2598. return;
  2599. }
  2600. // Not using a typed array to back the file storage. Use a standard JS array instead.
  2601. if (!node.contents && newCapacity > 0) node.contents = [];
  2602. while (node.contents.length < newCapacity) node.contents.push(0);
  2603. }, resizeFileStorage: function (node, newSize) {
  2604. if (node.usedBytes == newSize) return;
  2605. if (newSize == 0) {
  2606. node.contents = null; // Fully decommit when requesting a resize to zero.
  2607. node.usedBytes = 0;
  2608. return;
  2609. }
  2610. if (!node.contents || node.contents.subarray) { // Resize a typed array if that is being used as the backing store.
  2611. var oldContents = node.contents;
  2612. node.contents = new Uint8Array(new ArrayBuffer(newSize)); // Allocate new storage.
  2613. if (oldContents) {
  2614. node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
  2615. }
  2616. node.usedBytes = newSize;
  2617. return;
  2618. }
  2619. // Backing with a JS array.
  2620. if (!node.contents) node.contents = [];
  2621. if (node.contents.length > newSize) node.contents.length = newSize;
  2622. else while (node.contents.length < newSize) node.contents.push(0);
  2623. node.usedBytes = newSize;
  2624. }, node_ops: {
  2625. getattr: function (node) {
  2626. var attr = {};
  2627. // device numbers reuse inode numbers.
  2628. attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
  2629. attr.ino = node.id;
  2630. attr.mode = node.mode;
  2631. attr.nlink = 1;
  2632. attr.uid = 0;
  2633. attr.gid = 0;
  2634. attr.rdev = node.rdev;
  2635. if (FS.isDir(node.mode)) {
  2636. attr.size = 4096;
  2637. } else if (FS.isFile(node.mode)) {
  2638. attr.size = node.usedBytes;
  2639. } else if (FS.isLink(node.mode)) {
  2640. attr.size = node.link.length;
  2641. } else {
  2642. attr.size = 0;
  2643. }
  2644. attr.atime = new Date(node.timestamp);
  2645. attr.mtime = new Date(node.timestamp);
  2646. attr.ctime = new Date(node.timestamp);
  2647. // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
  2648. // but this is not required by the standard.
  2649. attr.blksize = 4096;
  2650. attr.blocks = Math.ceil(attr.size / attr.blksize);
  2651. return attr;
  2652. }, setattr: function (node, attr) {
  2653. if (attr.mode !== undefined) {
  2654. node.mode = attr.mode;
  2655. }
  2656. if (attr.timestamp !== undefined) {
  2657. node.timestamp = attr.timestamp;
  2658. }
  2659. if (attr.size !== undefined) {
  2660. MEMFS.resizeFileStorage(node, attr.size);
  2661. }
  2662. }, lookup: function (parent, name) {
  2663. throw FS.genericErrors[ERRNO_CODES.ENOENT];
  2664. }, mknod: function (parent, name, mode, dev) {
  2665. return MEMFS.createNode(parent, name, mode, dev);
  2666. }, rename: function (old_node, new_dir, new_name) {
  2667. // if we're overwriting a directory at new_name, make sure it's empty.
  2668. if (FS.isDir(old_node.mode)) {
  2669. var new_node;
  2670. try {
  2671. new_node = FS.lookupNode(new_dir, new_name);
  2672. } catch (e) {
  2673. }
  2674. if (new_node) {
  2675. for (var i in new_node.contents) {
  2676. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  2677. }
  2678. }
  2679. }
  2680. // do the internal rewiring
  2681. delete old_node.parent.contents[old_node.name];
  2682. old_node.name = new_name;
  2683. new_dir.contents[new_name] = old_node;
  2684. old_node.parent = new_dir;
  2685. }, unlink: function (parent, name) {
  2686. delete parent.contents[name];
  2687. }, rmdir: function (parent, name) {
  2688. var node = FS.lookupNode(parent, name);
  2689. for (var i in node.contents) {
  2690. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  2691. }
  2692. delete parent.contents[name];
  2693. }, readdir: function (node) {
  2694. var entries = ['.', '..']
  2695. for (var key in node.contents) {
  2696. if (!node.contents.hasOwnProperty(key)) {
  2697. continue;
  2698. }
  2699. entries.push(key);
  2700. }
  2701. return entries;
  2702. }, symlink: function (parent, newname, oldpath) {
  2703. var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
  2704. node.link = oldpath;
  2705. return node;
  2706. }, readlink: function (node) {
  2707. if (!FS.isLink(node.mode)) {
  2708. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2709. }
  2710. return node.link;
  2711. }
  2712. }, stream_ops: {
  2713. read: function (stream, buffer, offset, length, position) {
  2714. var contents = stream.node.contents;
  2715. if (position >= stream.node.usedBytes) return 0;
  2716. var size = Math.min(stream.node.usedBytes - position, length);
  2717. assert(size >= 0);
  2718. if (size > 8 && contents.subarray) { // non-trivial, and typed array
  2719. buffer.set(contents.subarray(position, position + size), offset);
  2720. } else {
  2721. for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
  2722. }
  2723. return size;
  2724. }, write: function (stream, buffer, offset, length, position, canOwn) {
  2725. if (!length) return 0;
  2726. var node = stream.node;
  2727. node.timestamp = Date.now();
  2728. if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
  2729. if (canOwn) {
  2730. node.contents = buffer.subarray(offset, offset + length);
  2731. node.usedBytes = length;
  2732. return length;
  2733. } else if (node.usedBytes === 0 && position === 0) { // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
  2734. node.contents = new Uint8Array(buffer.subarray(offset, offset + length));
  2735. node.usedBytes = length;
  2736. return length;
  2737. } else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
  2738. node.contents.set(buffer.subarray(offset, offset + length), position);
  2739. return length;
  2740. }
  2741. }
  2742. // Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
  2743. MEMFS.expandFileStorage(node, position + length);
  2744. if (node.contents.subarray && buffer.subarray) node.contents.set(buffer.subarray(offset, offset + length), position); // Use typed array write if available.
  2745. else {
  2746. for (var i = 0; i < length; i++) {
  2747. node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
  2748. }
  2749. }
  2750. node.usedBytes = Math.max(node.usedBytes, position + length);
  2751. return length;
  2752. }, llseek: function (stream, offset, whence) {
  2753. var position = offset;
  2754. if (whence === 1) { // SEEK_CUR.
  2755. position += stream.position;
  2756. } else if (whence === 2) { // SEEK_END.
  2757. if (FS.isFile(stream.node.mode)) {
  2758. position += stream.node.usedBytes;
  2759. }
  2760. }
  2761. if (position < 0) {
  2762. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  2763. }
  2764. return position;
  2765. }, allocate: function (stream, offset, length) {
  2766. MEMFS.expandFileStorage(stream.node, offset + length);
  2767. stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
  2768. }, mmap: function (stream, buffer, offset, length, position, prot, flags) {
  2769. if (!FS.isFile(stream.node.mode)) {
  2770. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  2771. }
  2772. var ptr;
  2773. var allocated;
  2774. var contents = stream.node.contents;
  2775. // Only make a new copy when MAP_PRIVATE is specified.
  2776. if (!(flags & 2) &&
  2777. (contents.buffer === buffer || contents.buffer === buffer.buffer)) {
  2778. // We can't emulate MAP_SHARED when the file is not backed by the buffer
  2779. // we're mapping to (e.g. the HEAP buffer).
  2780. allocated = false;
  2781. ptr = contents.byteOffset;
  2782. } else {
  2783. // Try to avoid unnecessary slices.
  2784. if (position > 0 || position + length < stream.node.usedBytes) {
  2785. if (contents.subarray) {
  2786. contents = contents.subarray(position, position + length);
  2787. } else {
  2788. contents = Array.prototype.slice.call(contents, position, position + length);
  2789. }
  2790. }
  2791. allocated = true;
  2792. ptr = _malloc(length);
  2793. if (!ptr) {
  2794. throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
  2795. }
  2796. buffer.set(contents, ptr);
  2797. }
  2798. return { ptr: ptr, allocated: allocated };
  2799. }, msync: function (stream, buffer, offset, length, mmapFlags) {
  2800. if (!FS.isFile(stream.node.mode)) {
  2801. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  2802. }
  2803. if (mmapFlags & 2) {
  2804. // MAP_PRIVATE calls need not to be synced back to underlying fs
  2805. return 0;
  2806. }
  2807. var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
  2808. // should we check if bytesWritten and length are the same?
  2809. return 0;
  2810. }
  2811. }
  2812. };
  2813. var IDBFS = {
  2814. dbs: {}, indexedDB: function () {
  2815. if (typeof indexedDB !== 'undefined') return indexedDB;
  2816. var ret = null;
  2817. if (typeof window === 'object') ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  2818. assert(ret, 'IDBFS used, but indexedDB not supported');
  2819. return ret;
  2820. }, DB_VERSION: 21, DB_STORE_NAME: "FILE_DATA", mount: function (mount) {
  2821. // reuse all of the core MEMFS functionality
  2822. return MEMFS.mount.apply(null, arguments);
  2823. }, syncfs: function (mount, populate, callback) {
  2824. IDBFS.getLocalSet(mount, function (err, local) {
  2825. if (err) return callback(err);
  2826. IDBFS.getRemoteSet(mount, function (err, remote) {
  2827. if (err) return callback(err);
  2828. var src = populate ? remote : local;
  2829. var dst = populate ? local : remote;
  2830. IDBFS.reconcile(src, dst, callback);
  2831. });
  2832. });
  2833. }, getDB: function (name, callback) {
  2834. // check the cache first
  2835. var db = IDBFS.dbs[name];
  2836. if (db) {
  2837. return callback(null, db);
  2838. }
  2839. var req;
  2840. try {
  2841. req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
  2842. } catch (e) {
  2843. return callback(e);
  2844. }
  2845. if (!req) {
  2846. return callback("Unable to connect to IndexedDB");
  2847. }
  2848. req.onupgradeneeded = function (e) {
  2849. var db = e.target.result;
  2850. var transaction = e.target.transaction;
  2851. var fileStore;
  2852. if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
  2853. fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
  2854. } else {
  2855. fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
  2856. }
  2857. if (!fileStore.indexNames.contains('timestamp')) {
  2858. fileStore.createIndex('timestamp', 'timestamp', { unique: false });
  2859. }
  2860. };
  2861. req.onsuccess = function () {
  2862. db = req.result;
  2863. // add to the cache
  2864. IDBFS.dbs[name] = db;
  2865. callback(null, db);
  2866. };
  2867. req.onerror = function (e) {
  2868. callback(this.error);
  2869. e.preventDefault();
  2870. };
  2871. }, getLocalSet: function (mount, callback) {
  2872. var entries = {};
  2873. function isRealDir(p) {
  2874. return p !== '.' && p !== '..';
  2875. };
  2876. function toAbsolute(root) {
  2877. return function (p) {
  2878. return PATH.join2(root, p);
  2879. }
  2880. };
  2881. var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
  2882. while (check.length) {
  2883. var path = check.pop();
  2884. var stat;
  2885. try {
  2886. stat = FS.stat(path);
  2887. } catch (e) {
  2888. return callback(e);
  2889. }
  2890. if (FS.isDir(stat.mode)) {
  2891. check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
  2892. }
  2893. entries[path] = { timestamp: stat.mtime };
  2894. }
  2895. return callback(null, { type: 'local', entries: entries });
  2896. }, getRemoteSet: function (mount, callback) {
  2897. var entries = {};
  2898. IDBFS.getDB(mount.mountpoint, function (err, db) {
  2899. if (err) return callback(err);
  2900. var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
  2901. transaction.onerror = function (e) {
  2902. callback(this.error);
  2903. e.preventDefault();
  2904. };
  2905. var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
  2906. var index = store.index('timestamp');
  2907. index.openKeyCursor().onsuccess = function (event) {
  2908. var cursor = event.target.result;
  2909. if (!cursor) {
  2910. return callback(null, { type: 'remote', db: db, entries: entries });
  2911. }
  2912. entries[cursor.primaryKey] = { timestamp: cursor.key };
  2913. cursor.continue();
  2914. };
  2915. });
  2916. }, loadLocalEntry: function (path, callback) {
  2917. var stat, node;
  2918. try {
  2919. var lookup = FS.lookupPath(path);
  2920. node = lookup.node;
  2921. stat = FS.stat(path);
  2922. } catch (e) {
  2923. return callback(e);
  2924. }
  2925. if (FS.isDir(stat.mode)) {
  2926. return callback(null, { timestamp: stat.mtime, mode: stat.mode });
  2927. } else if (FS.isFile(stat.mode)) {
  2928. // Performance consideration: storing a normal JavaScript array to a IndexedDB is much slower than storing a typed array.
  2929. // Therefore always convert the file contents to a typed array first before writing the data to IndexedDB.
  2930. node.contents = MEMFS.getFileDataAsTypedArray(node);
  2931. return callback(null, { timestamp: stat.mtime, mode: stat.mode, contents: node.contents });
  2932. } else {
  2933. return callback(new Error('node type not supported'));
  2934. }
  2935. }, storeLocalEntry: function (path, entry, callback) {
  2936. try {
  2937. if (FS.isDir(entry.mode)) {
  2938. FS.mkdir(path, entry.mode);
  2939. } else if (FS.isFile(entry.mode)) {
  2940. FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: true });
  2941. } else {
  2942. return callback(new Error('node type not supported'));
  2943. }
  2944. FS.chmod(path, entry.mode);
  2945. FS.utime(path, entry.timestamp, entry.timestamp);
  2946. } catch (e) {
  2947. return callback(e);
  2948. }
  2949. callback(null);
  2950. }, removeLocalEntry: function (path, callback) {
  2951. try {
  2952. var lookup = FS.lookupPath(path);
  2953. var stat = FS.stat(path);
  2954. if (FS.isDir(stat.mode)) {
  2955. FS.rmdir(path);
  2956. } else if (FS.isFile(stat.mode)) {
  2957. FS.unlink(path);
  2958. }
  2959. } catch (e) {
  2960. return callback(e);
  2961. }
  2962. callback(null);
  2963. }, loadRemoteEntry: function (store, path, callback) {
  2964. var req = store.get(path);
  2965. req.onsuccess = function (event) { callback(null, event.target.result); };
  2966. req.onerror = function (e) {
  2967. callback(this.error);
  2968. e.preventDefault();
  2969. };
  2970. }, storeRemoteEntry: function (store, path, entry, callback) {
  2971. var req = store.put(entry, path);
  2972. req.onsuccess = function () { callback(null); };
  2973. req.onerror = function (e) {
  2974. callback(this.error);
  2975. e.preventDefault();
  2976. };
  2977. }, removeRemoteEntry: function (store, path, callback) {
  2978. var req = store.delete(path);
  2979. req.onsuccess = function () { callback(null); };
  2980. req.onerror = function (e) {
  2981. callback(this.error);
  2982. e.preventDefault();
  2983. };
  2984. }, reconcile: function (src, dst, callback) {
  2985. var total = 0;
  2986. var create = [];
  2987. Object.keys(src.entries).forEach(function (key) {
  2988. var e = src.entries[key];
  2989. var e2 = dst.entries[key];
  2990. if (!e2 || e.timestamp > e2.timestamp) {
  2991. create.push(key);
  2992. total++;
  2993. }
  2994. });
  2995. var remove = [];
  2996. Object.keys(dst.entries).forEach(function (key) {
  2997. var e = dst.entries[key];
  2998. var e2 = src.entries[key];
  2999. if (!e2) {
  3000. remove.push(key);
  3001. total++;
  3002. }
  3003. });
  3004. if (!total) {
  3005. return callback(null);
  3006. }
  3007. var errored = false;
  3008. var completed = 0;
  3009. var db = src.type === 'remote' ? src.db : dst.db;
  3010. var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
  3011. var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
  3012. function done(err) {
  3013. if (err) {
  3014. if (!done.errored) {
  3015. done.errored = true;
  3016. return callback(err);
  3017. }
  3018. return;
  3019. }
  3020. if (++completed >= total) {
  3021. return callback(null);
  3022. }
  3023. };
  3024. transaction.onerror = function (e) {
  3025. done(this.error);
  3026. e.preventDefault();
  3027. };
  3028. // sort paths in ascending order so directory entries are created
  3029. // before the files inside them
  3030. create.sort().forEach(function (path) {
  3031. if (dst.type === 'local') {
  3032. IDBFS.loadRemoteEntry(store, path, function (err, entry) {
  3033. if (err) return done(err);
  3034. IDBFS.storeLocalEntry(path, entry, done);
  3035. });
  3036. } else {
  3037. IDBFS.loadLocalEntry(path, function (err, entry) {
  3038. if (err) return done(err);
  3039. IDBFS.storeRemoteEntry(store, path, entry, done);
  3040. });
  3041. }
  3042. });
  3043. // sort paths in descending order so files are deleted before their
  3044. // parent directories
  3045. remove.sort().reverse().forEach(function (path) {
  3046. if (dst.type === 'local') {
  3047. IDBFS.removeLocalEntry(path, done);
  3048. } else {
  3049. IDBFS.removeRemoteEntry(store, path, done);
  3050. }
  3051. });
  3052. }
  3053. };
  3054. var NODEFS = {
  3055. isWindows: false, staticInit: function () {
  3056. NODEFS.isWindows = !!process.platform.match(/^win/);
  3057. }, mount: function (mount) {
  3058. assert(ENVIRONMENT_IS_NODE);
  3059. return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
  3060. }, createNode: function (parent, name, mode, dev) {
  3061. if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
  3062. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3063. }
  3064. var node = FS.createNode(parent, name, mode);
  3065. node.node_ops = NODEFS.node_ops;
  3066. node.stream_ops = NODEFS.stream_ops;
  3067. return node;
  3068. }, getMode: function (path) {
  3069. var stat;
  3070. try {
  3071. stat = fs.lstatSync(path);
  3072. if (NODEFS.isWindows) {
  3073. // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
  3074. // propagate write bits to execute bits.
  3075. stat.mode = stat.mode | ((stat.mode & 146) >> 1);
  3076. }
  3077. } catch (e) {
  3078. if (!e.code) throw e;
  3079. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3080. }
  3081. return stat.mode;
  3082. }, realPath: function (node) {
  3083. var parts = [];
  3084. while (node.parent !== node) {
  3085. parts.push(node.name);
  3086. node = node.parent;
  3087. }
  3088. parts.push(node.mount.opts.root);
  3089. parts.reverse();
  3090. return PATH.join.apply(null, parts);
  3091. }, flagsToPermissionStringMap: { 0: "r", 1: "r+", 2: "r+", 64: "r", 65: "r+", 66: "r+", 129: "rx+", 193: "rx+", 514: "w+", 577: "w", 578: "w+", 705: "wx", 706: "wx+", 1024: "a", 1025: "a", 1026: "a+", 1089: "a", 1090: "a+", 1153: "ax", 1154: "ax+", 1217: "ax", 1218: "ax+", 4096: "rs", 4098: "rs+" }, flagsToPermissionString: function (flags) {
  3092. flags &= ~0x200000 /*O_PATH*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
  3093. flags &= ~0x800 /*O_NONBLOCK*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
  3094. flags &= ~0x8000 /*O_LARGEFILE*/; // Ignore this flag from musl, otherwise node.js fails to open the file.
  3095. flags &= ~0x80000 /*O_CLOEXEC*/; // Some applications may pass it; it makes no sense for a single process.
  3096. if (flags in NODEFS.flagsToPermissionStringMap) {
  3097. return NODEFS.flagsToPermissionStringMap[flags];
  3098. } else {
  3099. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3100. }
  3101. }, node_ops: {
  3102. getattr: function (node) {
  3103. var path = NODEFS.realPath(node);
  3104. var stat;
  3105. try {
  3106. stat = fs.lstatSync(path);
  3107. } catch (e) {
  3108. if (!e.code) throw e;
  3109. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3110. }
  3111. // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
  3112. // See http://support.microsoft.com/kb/140365
  3113. if (NODEFS.isWindows && !stat.blksize) {
  3114. stat.blksize = 4096;
  3115. }
  3116. if (NODEFS.isWindows && !stat.blocks) {
  3117. stat.blocks = (stat.size + stat.blksize - 1) / stat.blksize | 0;
  3118. }
  3119. return {
  3120. dev: stat.dev,
  3121. ino: stat.ino,
  3122. mode: stat.mode,
  3123. nlink: stat.nlink,
  3124. uid: stat.uid,
  3125. gid: stat.gid,
  3126. rdev: stat.rdev,
  3127. size: stat.size,
  3128. atime: stat.atime,
  3129. mtime: stat.mtime,
  3130. ctime: stat.ctime,
  3131. blksize: stat.blksize,
  3132. blocks: stat.blocks
  3133. };
  3134. }, setattr: function (node, attr) {
  3135. var path = NODEFS.realPath(node);
  3136. try {
  3137. if (attr.mode !== undefined) {
  3138. fs.chmodSync(path, attr.mode);
  3139. // update the common node structure mode as well
  3140. node.mode = attr.mode;
  3141. }
  3142. if (attr.timestamp !== undefined) {
  3143. var date = new Date(attr.timestamp);
  3144. fs.utimesSync(path, date, date);
  3145. }
  3146. if (attr.size !== undefined) {
  3147. fs.truncateSync(path, attr.size);
  3148. }
  3149. } catch (e) {
  3150. if (!e.code) throw e;
  3151. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3152. }
  3153. }, lookup: function (parent, name) {
  3154. var path = PATH.join2(NODEFS.realPath(parent), name);
  3155. var mode = NODEFS.getMode(path);
  3156. return NODEFS.createNode(parent, name, mode);
  3157. }, mknod: function (parent, name, mode, dev) {
  3158. var node = NODEFS.createNode(parent, name, mode, dev);
  3159. // create the backing node for this in the fs root as well
  3160. var path = NODEFS.realPath(node);
  3161. try {
  3162. if (FS.isDir(node.mode)) {
  3163. fs.mkdirSync(path, node.mode);
  3164. } else {
  3165. fs.writeFileSync(path, '', { mode: node.mode });
  3166. }
  3167. } catch (e) {
  3168. if (!e.code) throw e;
  3169. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3170. }
  3171. return node;
  3172. }, rename: function (oldNode, newDir, newName) {
  3173. var oldPath = NODEFS.realPath(oldNode);
  3174. var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
  3175. try {
  3176. fs.renameSync(oldPath, newPath);
  3177. } catch (e) {
  3178. if (!e.code) throw e;
  3179. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3180. }
  3181. }, unlink: function (parent, name) {
  3182. var path = PATH.join2(NODEFS.realPath(parent), name);
  3183. try {
  3184. fs.unlinkSync(path);
  3185. } catch (e) {
  3186. if (!e.code) throw e;
  3187. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3188. }
  3189. }, rmdir: function (parent, name) {
  3190. var path = PATH.join2(NODEFS.realPath(parent), name);
  3191. try {
  3192. fs.rmdirSync(path);
  3193. } catch (e) {
  3194. if (!e.code) throw e;
  3195. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3196. }
  3197. }, readdir: function (node) {
  3198. var path = NODEFS.realPath(node);
  3199. try {
  3200. return fs.readdirSync(path);
  3201. } catch (e) {
  3202. if (!e.code) throw e;
  3203. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3204. }
  3205. }, symlink: function (parent, newName, oldPath) {
  3206. var newPath = PATH.join2(NODEFS.realPath(parent), newName);
  3207. try {
  3208. fs.symlinkSync(oldPath, newPath);
  3209. } catch (e) {
  3210. if (!e.code) throw e;
  3211. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3212. }
  3213. }, readlink: function (node) {
  3214. var path = NODEFS.realPath(node);
  3215. try {
  3216. path = fs.readlinkSync(path);
  3217. path = NODEJS_PATH.relative(NODEJS_PATH.resolve(node.mount.opts.root), path);
  3218. return path;
  3219. } catch (e) {
  3220. if (!e.code) throw e;
  3221. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3222. }
  3223. }
  3224. }, stream_ops: {
  3225. open: function (stream) {
  3226. var path = NODEFS.realPath(stream.node);
  3227. try {
  3228. if (FS.isFile(stream.node.mode)) {
  3229. stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
  3230. }
  3231. } catch (e) {
  3232. if (!e.code) throw e;
  3233. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3234. }
  3235. }, close: function (stream) {
  3236. try {
  3237. if (FS.isFile(stream.node.mode) && stream.nfd) {
  3238. fs.closeSync(stream.nfd);
  3239. }
  3240. } catch (e) {
  3241. if (!e.code) throw e;
  3242. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3243. }
  3244. }, read: function (stream, buffer, offset, length, position) {
  3245. if (length === 0) return 0; // node errors on 0 length reads
  3246. // FIXME this is terrible.
  3247. var nbuffer = new Buffer(length);
  3248. var res;
  3249. try {
  3250. res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
  3251. } catch (e) {
  3252. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3253. }
  3254. if (res > 0) {
  3255. for (var i = 0; i < res; i++) {
  3256. buffer[offset + i] = nbuffer[i];
  3257. }
  3258. }
  3259. return res;
  3260. }, write: function (stream, buffer, offset, length, position) {
  3261. // FIXME this is terrible.
  3262. var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
  3263. var res;
  3264. try {
  3265. res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
  3266. } catch (e) {
  3267. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3268. }
  3269. return res;
  3270. }, llseek: function (stream, offset, whence) {
  3271. var position = offset;
  3272. if (whence === 1) { // SEEK_CUR.
  3273. position += stream.position;
  3274. } else if (whence === 2) { // SEEK_END.
  3275. if (FS.isFile(stream.node.mode)) {
  3276. try {
  3277. var stat = fs.fstatSync(stream.nfd);
  3278. position += stat.size;
  3279. } catch (e) {
  3280. throw new FS.ErrnoError(ERRNO_CODES[e.code]);
  3281. }
  3282. }
  3283. }
  3284. if (position < 0) {
  3285. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3286. }
  3287. return position;
  3288. }
  3289. }
  3290. };
  3291. var WORKERFS = {
  3292. DIR_MODE: 16895, FILE_MODE: 33279, reader: null, mount: function (mount) {
  3293. assert(ENVIRONMENT_IS_WORKER);
  3294. if (!WORKERFS.reader) WORKERFS.reader = new FileReaderSync();
  3295. var root = WORKERFS.createNode(null, '/', WORKERFS.DIR_MODE, 0);
  3296. var createdParents = {};
  3297. function ensureParent(path) {
  3298. // return the parent node, creating subdirs as necessary
  3299. var parts = path.split('/');
  3300. var parent = root;
  3301. for (var i = 0; i < parts.length - 1; i++) {
  3302. var curr = parts.slice(0, i + 1).join('/');
  3303. // Issue 4254: Using curr as a node name will prevent the node
  3304. // from being found in FS.nameTable when FS.open is called on
  3305. // a path which holds a child of this node,
  3306. // given that all FS functions assume node names
  3307. // are just their corresponding parts within their given path,
  3308. // rather than incremental aggregates which include their parent's
  3309. // directories.
  3310. if (!createdParents[curr]) {
  3311. createdParents[curr] = WORKERFS.createNode(parent, parts[i], WORKERFS.DIR_MODE, 0);
  3312. }
  3313. parent = createdParents[curr];
  3314. }
  3315. return parent;
  3316. }
  3317. function base(path) {
  3318. var parts = path.split('/');
  3319. return parts[parts.length - 1];
  3320. }
  3321. // We also accept FileList here, by using Array.prototype
  3322. Array.prototype.forEach.call(mount.opts["files"] || [], function (file) {
  3323. WORKERFS.createNode(ensureParent(file.name), base(file.name), WORKERFS.FILE_MODE, 0, file, file.lastModifiedDate);
  3324. });
  3325. (mount.opts["blobs"] || []).forEach(function (obj) {
  3326. WORKERFS.createNode(ensureParent(obj["name"]), base(obj["name"]), WORKERFS.FILE_MODE, 0, obj["data"]);
  3327. });
  3328. (mount.opts["packages"] || []).forEach(function (pack) {
  3329. pack['metadata'].files.forEach(function (file) {
  3330. var name = file.filename.substr(1); // remove initial slash
  3331. WORKERFS.createNode(ensureParent(name), base(name), WORKERFS.FILE_MODE, 0, pack['blob'].slice(file.start, file.end));
  3332. });
  3333. });
  3334. return root;
  3335. }, createNode: function (parent, name, mode, dev, contents, mtime) {
  3336. var node = FS.createNode(parent, name, mode);
  3337. node.mode = mode;
  3338. node.node_ops = WORKERFS.node_ops;
  3339. node.stream_ops = WORKERFS.stream_ops;
  3340. node.timestamp = (mtime || new Date).getTime();
  3341. assert(WORKERFS.FILE_MODE !== WORKERFS.DIR_MODE);
  3342. if (mode === WORKERFS.FILE_MODE) {
  3343. node.size = contents.size;
  3344. node.contents = contents;
  3345. } else {
  3346. node.size = 4096;
  3347. node.contents = {};
  3348. }
  3349. if (parent) {
  3350. parent.contents[name] = node;
  3351. }
  3352. return node;
  3353. }, node_ops: {
  3354. getattr: function (node) {
  3355. return {
  3356. dev: 1,
  3357. ino: undefined,
  3358. mode: node.mode,
  3359. nlink: 1,
  3360. uid: 0,
  3361. gid: 0,
  3362. rdev: undefined,
  3363. size: node.size,
  3364. atime: new Date(node.timestamp),
  3365. mtime: new Date(node.timestamp),
  3366. ctime: new Date(node.timestamp),
  3367. blksize: 4096,
  3368. blocks: Math.ceil(node.size / 4096),
  3369. };
  3370. }, setattr: function (node, attr) {
  3371. if (attr.mode !== undefined) {
  3372. node.mode = attr.mode;
  3373. }
  3374. if (attr.timestamp !== undefined) {
  3375. node.timestamp = attr.timestamp;
  3376. }
  3377. }, lookup: function (parent, name) {
  3378. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  3379. }, mknod: function (parent, name, mode, dev) {
  3380. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3381. }, rename: function (oldNode, newDir, newName) {
  3382. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3383. }, unlink: function (parent, name) {
  3384. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3385. }, rmdir: function (parent, name) {
  3386. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3387. }, readdir: function (node) {
  3388. var entries = ['.', '..'];
  3389. for (var key in node.contents) {
  3390. if (!node.contents.hasOwnProperty(key)) {
  3391. continue;
  3392. }
  3393. entries.push(key);
  3394. }
  3395. return entries;
  3396. }, symlink: function (parent, newName, oldPath) {
  3397. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3398. }, readlink: function (node) {
  3399. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3400. }
  3401. }, stream_ops: {
  3402. read: function (stream, buffer, offset, length, position) {
  3403. if (position >= stream.node.size) return 0;
  3404. var chunk = stream.node.contents.slice(position, position + length);
  3405. var ab = WORKERFS.reader.readAsArrayBuffer(chunk);
  3406. buffer.set(new Uint8Array(ab), offset);
  3407. return chunk.size;
  3408. }, write: function (stream, buffer, offset, length, position) {
  3409. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  3410. }, llseek: function (stream, offset, whence) {
  3411. var position = offset;
  3412. if (whence === 1) { // SEEK_CUR.
  3413. position += stream.position;
  3414. } else if (whence === 2) { // SEEK_END.
  3415. if (FS.isFile(stream.node.mode)) {
  3416. position += stream.node.size;
  3417. }
  3418. }
  3419. if (position < 0) {
  3420. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3421. }
  3422. return position;
  3423. }
  3424. }
  3425. };
  3426. var _stdin = STATICTOP; STATICTOP += 16;;
  3427. var _stdout = STATICTOP; STATICTOP += 16;;
  3428. var _stderr = STATICTOP; STATICTOP += 16;; var FS = {
  3429. root: null, mounts: [], devices: [null], streams: [], nextInode: 1, nameTable: null, currentPath: "/", initialized: false, ignorePermissions: true, trackingDelegate: {}, tracking: { openFlags: { READ: 1, WRITE: 2 } }, ErrnoError: null, genericErrors: {}, filesystems: null, syncFSRequests: 0, handleFSError: function (e) {
  3430. if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
  3431. return ___setErrNo(e.errno);
  3432. }, lookupPath: function (path, opts) {
  3433. path = PATH.resolve(FS.cwd(), path);
  3434. opts = opts || {};
  3435. if (!path) return { path: '', node: null };
  3436. var defaults = {
  3437. follow_mount: true,
  3438. recurse_count: 0
  3439. };
  3440. for (var key in defaults) {
  3441. if (opts[key] === undefined) {
  3442. opts[key] = defaults[key];
  3443. }
  3444. }
  3445. if (opts.recurse_count > 8) { // max recursive lookup of 8
  3446. throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
  3447. }
  3448. // split the path
  3449. var parts = PATH.normalizeArray(path.split('/').filter(function (p) {
  3450. return !!p;
  3451. }), false);
  3452. // start at the root
  3453. var current = FS.root;
  3454. var current_path = '/';
  3455. for (var i = 0; i < parts.length; i++) {
  3456. var islast = (i === parts.length - 1);
  3457. if (islast && opts.parent) {
  3458. // stop resolving
  3459. break;
  3460. }
  3461. current = FS.lookupNode(current, parts[i]);
  3462. current_path = PATH.join2(current_path, parts[i]);
  3463. // jump to the mount's root node if this is a mountpoint
  3464. if (FS.isMountpoint(current)) {
  3465. if (!islast || (islast && opts.follow_mount)) {
  3466. current = current.mounted.root;
  3467. }
  3468. }
  3469. // by default, lookupPath will not follow a symlink if it is the final path component.
  3470. // setting opts.follow = true will override this behavior.
  3471. if (!islast || opts.follow) {
  3472. var count = 0;
  3473. while (FS.isLink(current.mode)) {
  3474. var link = FS.readlink(current_path);
  3475. current_path = PATH.resolve(PATH.dirname(current_path), link);
  3476. var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
  3477. current = lookup.node;
  3478. if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
  3479. throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
  3480. }
  3481. }
  3482. }
  3483. }
  3484. return { path: current_path, node: current };
  3485. }, getPath: function (node) {
  3486. var path;
  3487. while (true) {
  3488. if (FS.isRoot(node)) {
  3489. var mount = node.mount.mountpoint;
  3490. if (!path) return mount;
  3491. return mount[mount.length - 1] !== '/' ? mount + '/' + path : mount + path;
  3492. }
  3493. path = path ? node.name + '/' + path : node.name;
  3494. node = node.parent;
  3495. }
  3496. }, hashName: function (parentid, name) {
  3497. var hash = 0;
  3498. for (var i = 0; i < name.length; i++) {
  3499. hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
  3500. }
  3501. return ((parentid + hash) >>> 0) % FS.nameTable.length;
  3502. }, hashAddNode: function (node) {
  3503. var hash = FS.hashName(node.parent.id, node.name);
  3504. node.name_next = FS.nameTable[hash];
  3505. FS.nameTable[hash] = node;
  3506. }, hashRemoveNode: function (node) {
  3507. var hash = FS.hashName(node.parent.id, node.name);
  3508. if (FS.nameTable[hash] === node) {
  3509. FS.nameTable[hash] = node.name_next;
  3510. } else {
  3511. var current = FS.nameTable[hash];
  3512. while (current) {
  3513. if (current.name_next === node) {
  3514. current.name_next = node.name_next;
  3515. break;
  3516. }
  3517. current = current.name_next;
  3518. }
  3519. }
  3520. }, lookupNode: function (parent, name) {
  3521. var err = FS.mayLookup(parent);
  3522. if (err) {
  3523. throw new FS.ErrnoError(err, parent);
  3524. }
  3525. var hash = FS.hashName(parent.id, name);
  3526. for (var node = FS.nameTable[hash]; node; node = node.name_next) {
  3527. var nodeName = node.name;
  3528. if (node.parent.id === parent.id && nodeName === name) {
  3529. return node;
  3530. }
  3531. }
  3532. // if we failed to find it in the cache, call into the VFS
  3533. return FS.lookup(parent, name);
  3534. }, createNode: function (parent, name, mode, rdev) {
  3535. if (!FS.FSNode) {
  3536. FS.FSNode = function (parent, name, mode, rdev) {
  3537. if (!parent) {
  3538. parent = this; // root node sets parent to itself
  3539. }
  3540. this.parent = parent;
  3541. this.mount = parent.mount;
  3542. this.mounted = null;
  3543. this.id = FS.nextInode++;
  3544. this.name = name;
  3545. this.mode = mode;
  3546. this.node_ops = {};
  3547. this.stream_ops = {};
  3548. this.rdev = rdev;
  3549. };
  3550. FS.FSNode.prototype = {};
  3551. // compatibility
  3552. var readMode = 292 | 73;
  3553. var writeMode = 146;
  3554. // NOTE we must use Object.defineProperties instead of individual calls to
  3555. // Object.defineProperty in order to make closure compiler happy
  3556. Object.defineProperties(FS.FSNode.prototype, {
  3557. read: {
  3558. get: function () { return (this.mode & readMode) === readMode; },
  3559. set: function (val) { val ? this.mode |= readMode : this.mode &= ~readMode; }
  3560. },
  3561. write: {
  3562. get: function () { return (this.mode & writeMode) === writeMode; },
  3563. set: function (val) { val ? this.mode |= writeMode : this.mode &= ~writeMode; }
  3564. },
  3565. isFolder: {
  3566. get: function () { return FS.isDir(this.mode); }
  3567. },
  3568. isDevice: {
  3569. get: function () { return FS.isChrdev(this.mode); }
  3570. }
  3571. });
  3572. }
  3573. var node = new FS.FSNode(parent, name, mode, rdev);
  3574. FS.hashAddNode(node);
  3575. return node;
  3576. }, destroyNode: function (node) {
  3577. FS.hashRemoveNode(node);
  3578. }, isRoot: function (node) {
  3579. return node === node.parent;
  3580. }, isMountpoint: function (node) {
  3581. return !!node.mounted;
  3582. }, isFile: function (mode) {
  3583. return (mode & 61440) === 32768;
  3584. }, isDir: function (mode) {
  3585. return (mode & 61440) === 16384;
  3586. }, isLink: function (mode) {
  3587. return (mode & 61440) === 40960;
  3588. }, isChrdev: function (mode) {
  3589. return (mode & 61440) === 8192;
  3590. }, isBlkdev: function (mode) {
  3591. return (mode & 61440) === 24576;
  3592. }, isFIFO: function (mode) {
  3593. return (mode & 61440) === 4096;
  3594. }, isSocket: function (mode) {
  3595. return (mode & 49152) === 49152;
  3596. }, flagModes: { "r": 0, "rs": 1052672, "r+": 2, "w": 577, "wx": 705, "xw": 705, "w+": 578, "wx+": 706, "xw+": 706, "a": 1089, "ax": 1217, "xa": 1217, "a+": 1090, "ax+": 1218, "xa+": 1218 }, modeStringToFlags: function (str) {
  3597. var flags = FS.flagModes[str];
  3598. if (typeof flags === 'undefined') {
  3599. throw new Error('Unknown file open mode: ' + str);
  3600. }
  3601. return flags;
  3602. }, flagsToPermissionString: function (flag) {
  3603. var perms = ['r', 'w', 'rw'][flag & 3];
  3604. if ((flag & 512)) {
  3605. perms += 'w';
  3606. }
  3607. return perms;
  3608. }, nodePermissions: function (node, perms) {
  3609. if (FS.ignorePermissions) {
  3610. return 0;
  3611. }
  3612. // return 0 if any user, group or owner bits are set.
  3613. if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
  3614. return ERRNO_CODES.EACCES;
  3615. } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
  3616. return ERRNO_CODES.EACCES;
  3617. } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
  3618. return ERRNO_CODES.EACCES;
  3619. }
  3620. return 0;
  3621. }, mayLookup: function (dir) {
  3622. var err = FS.nodePermissions(dir, 'x');
  3623. if (err) return err;
  3624. if (!dir.node_ops.lookup) return ERRNO_CODES.EACCES;
  3625. return 0;
  3626. }, mayCreate: function (dir, name) {
  3627. try {
  3628. var node = FS.lookupNode(dir, name);
  3629. return ERRNO_CODES.EEXIST;
  3630. } catch (e) {
  3631. }
  3632. return FS.nodePermissions(dir, 'wx');
  3633. }, mayDelete: function (dir, name, isdir) {
  3634. var node;
  3635. try {
  3636. node = FS.lookupNode(dir, name);
  3637. } catch (e) {
  3638. return e.errno;
  3639. }
  3640. var err = FS.nodePermissions(dir, 'wx');
  3641. if (err) {
  3642. return err;
  3643. }
  3644. if (isdir) {
  3645. if (!FS.isDir(node.mode)) {
  3646. return ERRNO_CODES.ENOTDIR;
  3647. }
  3648. if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
  3649. return ERRNO_CODES.EBUSY;
  3650. }
  3651. } else {
  3652. if (FS.isDir(node.mode)) {
  3653. return ERRNO_CODES.EISDIR;
  3654. }
  3655. }
  3656. return 0;
  3657. }, mayOpen: function (node, flags) {
  3658. if (!node) {
  3659. return ERRNO_CODES.ENOENT;
  3660. }
  3661. if (FS.isLink(node.mode)) {
  3662. return ERRNO_CODES.ELOOP;
  3663. } else if (FS.isDir(node.mode)) {
  3664. if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
  3665. (flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
  3666. return ERRNO_CODES.EISDIR;
  3667. }
  3668. }
  3669. return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
  3670. }, MAX_OPEN_FDS: 4096, nextfd: function (fd_start, fd_end) {
  3671. fd_start = fd_start || 0;
  3672. fd_end = fd_end || FS.MAX_OPEN_FDS;
  3673. for (var fd = fd_start; fd <= fd_end; fd++) {
  3674. if (!FS.streams[fd]) {
  3675. return fd;
  3676. }
  3677. }
  3678. throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
  3679. }, getStream: function (fd) {
  3680. return FS.streams[fd];
  3681. }, createStream: function (stream, fd_start, fd_end) {
  3682. if (!FS.FSStream) {
  3683. FS.FSStream = function () { };
  3684. FS.FSStream.prototype = {};
  3685. // compatibility
  3686. Object.defineProperties(FS.FSStream.prototype, {
  3687. object: {
  3688. get: function () { return this.node; },
  3689. set: function (val) { this.node = val; }
  3690. },
  3691. isRead: {
  3692. get: function () { return (this.flags & 2097155) !== 1; }
  3693. },
  3694. isWrite: {
  3695. get: function () { return (this.flags & 2097155) !== 0; }
  3696. },
  3697. isAppend: {
  3698. get: function () { return (this.flags & 1024); }
  3699. }
  3700. });
  3701. }
  3702. // clone it, so we can return an instance of FSStream
  3703. var newStream = new FS.FSStream();
  3704. for (var p in stream) {
  3705. newStream[p] = stream[p];
  3706. }
  3707. stream = newStream;
  3708. var fd = FS.nextfd(fd_start, fd_end);
  3709. stream.fd = fd;
  3710. FS.streams[fd] = stream;
  3711. return stream;
  3712. }, closeStream: function (fd) {
  3713. FS.streams[fd] = null;
  3714. }, chrdev_stream_ops: {
  3715. open: function (stream) {
  3716. var device = FS.getDevice(stream.node.rdev);
  3717. // override node's stream ops with the device's
  3718. stream.stream_ops = device.stream_ops;
  3719. // forward the open call
  3720. if (stream.stream_ops.open) {
  3721. stream.stream_ops.open(stream);
  3722. }
  3723. }, llseek: function () {
  3724. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  3725. }
  3726. }, major: function (dev) {
  3727. return ((dev) >> 8);
  3728. }, minor: function (dev) {
  3729. return ((dev) & 0xff);
  3730. }, makedev: function (ma, mi) {
  3731. return ((ma) << 8 | (mi));
  3732. }, registerDevice: function (dev, ops) {
  3733. FS.devices[dev] = { stream_ops: ops };
  3734. }, getDevice: function (dev) {
  3735. return FS.devices[dev];
  3736. }, getMounts: function (mount) {
  3737. var mounts = [];
  3738. var check = [mount];
  3739. while (check.length) {
  3740. var m = check.pop();
  3741. mounts.push(m);
  3742. check.push.apply(check, m.mounts);
  3743. }
  3744. return mounts;
  3745. }, syncfs: function (populate, callback) {
  3746. if (typeof (populate) === 'function') {
  3747. callback = populate;
  3748. populate = false;
  3749. }
  3750. FS.syncFSRequests++;
  3751. if (FS.syncFSRequests > 1) {
  3752. console.log('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
  3753. }
  3754. var mounts = FS.getMounts(FS.root.mount);
  3755. var completed = 0;
  3756. function doCallback(err) {
  3757. assert(FS.syncFSRequests > 0);
  3758. FS.syncFSRequests--;
  3759. return callback(err);
  3760. }
  3761. function done(err) {
  3762. if (err) {
  3763. if (!done.errored) {
  3764. done.errored = true;
  3765. return doCallback(err);
  3766. }
  3767. return;
  3768. }
  3769. if (++completed >= mounts.length) {
  3770. doCallback(null);
  3771. }
  3772. };
  3773. // sync all mounts
  3774. mounts.forEach(function (mount) {
  3775. if (!mount.type.syncfs) {
  3776. return done(null);
  3777. }
  3778. mount.type.syncfs(mount, populate, done);
  3779. });
  3780. }, mount: function (type, opts, mountpoint) {
  3781. var root = mountpoint === '/';
  3782. var pseudo = !mountpoint;
  3783. var node;
  3784. if (root && FS.root) {
  3785. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  3786. } else if (!root && !pseudo) {
  3787. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  3788. mountpoint = lookup.path; // use the absolute path
  3789. node = lookup.node;
  3790. if (FS.isMountpoint(node)) {
  3791. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  3792. }
  3793. if (!FS.isDir(node.mode)) {
  3794. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  3795. }
  3796. }
  3797. var mount = {
  3798. type: type,
  3799. opts: opts,
  3800. mountpoint: mountpoint,
  3801. mounts: []
  3802. };
  3803. // create a root node for the fs
  3804. var mountRoot = type.mount(mount);
  3805. mountRoot.mount = mount;
  3806. mount.root = mountRoot;
  3807. if (root) {
  3808. FS.root = mountRoot;
  3809. } else if (node) {
  3810. // set as a mountpoint
  3811. node.mounted = mount;
  3812. // add the new mount to the current mount's children
  3813. if (node.mount) {
  3814. node.mount.mounts.push(mount);
  3815. }
  3816. }
  3817. return mountRoot;
  3818. }, unmount: function (mountpoint) {
  3819. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  3820. if (!FS.isMountpoint(lookup.node)) {
  3821. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3822. }
  3823. // destroy the nodes for this mount, and all its child mounts
  3824. var node = lookup.node;
  3825. var mount = node.mounted;
  3826. var mounts = FS.getMounts(mount);
  3827. Object.keys(FS.nameTable).forEach(function (hash) {
  3828. var current = FS.nameTable[hash];
  3829. while (current) {
  3830. var next = current.name_next;
  3831. if (mounts.indexOf(current.mount) !== -1) {
  3832. FS.destroyNode(current);
  3833. }
  3834. current = next;
  3835. }
  3836. });
  3837. // no longer a mountpoint
  3838. node.mounted = null;
  3839. // remove this mount from the child mounts
  3840. var idx = node.mount.mounts.indexOf(mount);
  3841. assert(idx !== -1);
  3842. node.mount.mounts.splice(idx, 1);
  3843. }, lookup: function (parent, name) {
  3844. return parent.node_ops.lookup(parent, name);
  3845. }, mknod: function (path, mode, dev) {
  3846. var lookup = FS.lookupPath(path, { parent: true });
  3847. var parent = lookup.node;
  3848. var name = PATH.basename(path);
  3849. if (!name || name === '.' || name === '..') {
  3850. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3851. }
  3852. var err = FS.mayCreate(parent, name);
  3853. if (err) {
  3854. throw new FS.ErrnoError(err);
  3855. }
  3856. if (!parent.node_ops.mknod) {
  3857. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3858. }
  3859. return parent.node_ops.mknod(parent, name, mode, dev);
  3860. }, create: function (path, mode) {
  3861. mode = mode !== undefined ? mode : 438 /* 0666 */;
  3862. mode &= 4095;
  3863. mode |= 32768;
  3864. return FS.mknod(path, mode, 0);
  3865. }, mkdir: function (path, mode) {
  3866. mode = mode !== undefined ? mode : 511 /* 0777 */;
  3867. mode &= 511 | 512;
  3868. mode |= 16384;
  3869. return FS.mknod(path, mode, 0);
  3870. }, mkdirTree: function (path, mode) {
  3871. var dirs = path.split('/');
  3872. var d = '';
  3873. for (var i = 0; i < dirs.length; ++i) {
  3874. if (!dirs[i]) continue;
  3875. d += '/' + dirs[i];
  3876. try {
  3877. FS.mkdir(d, mode);
  3878. } catch (e) {
  3879. if (e.errno != ERRNO_CODES.EEXIST) throw e;
  3880. }
  3881. }
  3882. }, mkdev: function (path, mode, dev) {
  3883. if (typeof (dev) === 'undefined') {
  3884. dev = mode;
  3885. mode = 438 /* 0666 */;
  3886. }
  3887. mode |= 8192;
  3888. return FS.mknod(path, mode, dev);
  3889. }, symlink: function (oldpath, newpath) {
  3890. if (!PATH.resolve(oldpath)) {
  3891. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  3892. }
  3893. var lookup = FS.lookupPath(newpath, { parent: true });
  3894. var parent = lookup.node;
  3895. if (!parent) {
  3896. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  3897. }
  3898. var newname = PATH.basename(newpath);
  3899. var err = FS.mayCreate(parent, newname);
  3900. if (err) {
  3901. throw new FS.ErrnoError(err);
  3902. }
  3903. if (!parent.node_ops.symlink) {
  3904. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3905. }
  3906. return parent.node_ops.symlink(parent, newname, oldpath);
  3907. }, rename: function (old_path, new_path) {
  3908. var old_dirname = PATH.dirname(old_path);
  3909. var new_dirname = PATH.dirname(new_path);
  3910. var old_name = PATH.basename(old_path);
  3911. var new_name = PATH.basename(new_path);
  3912. // parents must exist
  3913. var lookup, old_dir, new_dir;
  3914. try {
  3915. lookup = FS.lookupPath(old_path, { parent: true });
  3916. old_dir = lookup.node;
  3917. lookup = FS.lookupPath(new_path, { parent: true });
  3918. new_dir = lookup.node;
  3919. } catch (e) {
  3920. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  3921. }
  3922. if (!old_dir || !new_dir) throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  3923. // need to be part of the same mount
  3924. if (old_dir.mount !== new_dir.mount) {
  3925. throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
  3926. }
  3927. // source must exist
  3928. var old_node = FS.lookupNode(old_dir, old_name);
  3929. // old path should not be an ancestor of the new path
  3930. var relative = PATH.relative(old_path, new_dirname);
  3931. if (relative.charAt(0) !== '.') {
  3932. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  3933. }
  3934. // new path should not be an ancestor of the old path
  3935. relative = PATH.relative(new_path, old_dirname);
  3936. if (relative.charAt(0) !== '.') {
  3937. throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
  3938. }
  3939. // see if the new path already exists
  3940. var new_node;
  3941. try {
  3942. new_node = FS.lookupNode(new_dir, new_name);
  3943. } catch (e) {
  3944. // not fatal
  3945. }
  3946. // early out if nothing needs to change
  3947. if (old_node === new_node) {
  3948. return;
  3949. }
  3950. // we'll need to delete the old entry
  3951. var isdir = FS.isDir(old_node.mode);
  3952. var err = FS.mayDelete(old_dir, old_name, isdir);
  3953. if (err) {
  3954. throw new FS.ErrnoError(err);
  3955. }
  3956. // need delete permissions if we'll be overwriting.
  3957. // need create permissions if new doesn't already exist.
  3958. err = new_node ?
  3959. FS.mayDelete(new_dir, new_name, isdir) :
  3960. FS.mayCreate(new_dir, new_name);
  3961. if (err) {
  3962. throw new FS.ErrnoError(err);
  3963. }
  3964. if (!old_dir.node_ops.rename) {
  3965. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  3966. }
  3967. if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
  3968. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  3969. }
  3970. // if we are going to change the parent, check write permissions
  3971. if (new_dir !== old_dir) {
  3972. err = FS.nodePermissions(old_dir, 'w');
  3973. if (err) {
  3974. throw new FS.ErrnoError(err);
  3975. }
  3976. }
  3977. try {
  3978. if (FS.trackingDelegate['willMovePath']) {
  3979. FS.trackingDelegate['willMovePath'](old_path, new_path);
  3980. }
  3981. } catch (e) {
  3982. console.log("FS.trackingDelegate['willMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message);
  3983. }
  3984. // remove the node from the lookup hash
  3985. FS.hashRemoveNode(old_node);
  3986. // do the underlying fs rename
  3987. try {
  3988. old_dir.node_ops.rename(old_node, new_dir, new_name);
  3989. } catch (e) {
  3990. throw e;
  3991. } finally {
  3992. // add the node back to the hash (in case node_ops.rename
  3993. // changed its name)
  3994. FS.hashAddNode(old_node);
  3995. }
  3996. try {
  3997. if (FS.trackingDelegate['onMovePath']) FS.trackingDelegate['onMovePath'](old_path, new_path);
  3998. } catch (e) {
  3999. console.log("FS.trackingDelegate['onMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message);
  4000. }
  4001. }, rmdir: function (path) {
  4002. var lookup = FS.lookupPath(path, { parent: true });
  4003. var parent = lookup.node;
  4004. var name = PATH.basename(path);
  4005. var node = FS.lookupNode(parent, name);
  4006. var err = FS.mayDelete(parent, name, true);
  4007. if (err) {
  4008. throw new FS.ErrnoError(err);
  4009. }
  4010. if (!parent.node_ops.rmdir) {
  4011. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4012. }
  4013. if (FS.isMountpoint(node)) {
  4014. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  4015. }
  4016. try {
  4017. if (FS.trackingDelegate['willDeletePath']) {
  4018. FS.trackingDelegate['willDeletePath'](path);
  4019. }
  4020. } catch (e) {
  4021. console.log("FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message);
  4022. }
  4023. parent.node_ops.rmdir(parent, name);
  4024. FS.destroyNode(node);
  4025. try {
  4026. if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
  4027. } catch (e) {
  4028. console.log("FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message);
  4029. }
  4030. }, readdir: function (path) {
  4031. var lookup = FS.lookupPath(path, { follow: true });
  4032. var node = lookup.node;
  4033. if (!node.node_ops.readdir) {
  4034. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  4035. }
  4036. return node.node_ops.readdir(node);
  4037. }, unlink: function (path) {
  4038. var lookup = FS.lookupPath(path, { parent: true });
  4039. var parent = lookup.node;
  4040. var name = PATH.basename(path);
  4041. var node = FS.lookupNode(parent, name);
  4042. var err = FS.mayDelete(parent, name, false);
  4043. if (err) {
  4044. // According to POSIX, we should map EISDIR to EPERM, but
  4045. // we instead do what Linux does (and we must, as we use
  4046. // the musl linux libc).
  4047. throw new FS.ErrnoError(err);
  4048. }
  4049. if (!parent.node_ops.unlink) {
  4050. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4051. }
  4052. if (FS.isMountpoint(node)) {
  4053. throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
  4054. }
  4055. try {
  4056. if (FS.trackingDelegate['willDeletePath']) {
  4057. FS.trackingDelegate['willDeletePath'](path);
  4058. }
  4059. } catch (e) {
  4060. console.log("FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message);
  4061. }
  4062. parent.node_ops.unlink(parent, name);
  4063. FS.destroyNode(node);
  4064. try {
  4065. if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
  4066. } catch (e) {
  4067. console.log("FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message);
  4068. }
  4069. }, readlink: function (path) {
  4070. var lookup = FS.lookupPath(path);
  4071. var link = lookup.node;
  4072. if (!link) {
  4073. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  4074. }
  4075. if (!link.node_ops.readlink) {
  4076. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4077. }
  4078. return PATH.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
  4079. }, stat: function (path, dontFollow) {
  4080. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  4081. var node = lookup.node;
  4082. if (!node) {
  4083. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  4084. }
  4085. if (!node.node_ops.getattr) {
  4086. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4087. }
  4088. return node.node_ops.getattr(node);
  4089. }, lstat: function (path) {
  4090. return FS.stat(path, true);
  4091. }, chmod: function (path, mode, dontFollow) {
  4092. var node;
  4093. if (typeof path === 'string') {
  4094. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  4095. node = lookup.node;
  4096. } else {
  4097. node = path;
  4098. }
  4099. if (!node.node_ops.setattr) {
  4100. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4101. }
  4102. node.node_ops.setattr(node, {
  4103. mode: (mode & 4095) | (node.mode & ~4095),
  4104. timestamp: Date.now()
  4105. });
  4106. }, lchmod: function (path, mode) {
  4107. FS.chmod(path, mode, true);
  4108. }, fchmod: function (fd, mode) {
  4109. var stream = FS.getStream(fd);
  4110. if (!stream) {
  4111. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4112. }
  4113. FS.chmod(stream.node, mode);
  4114. }, chown: function (path, uid, gid, dontFollow) {
  4115. var node;
  4116. if (typeof path === 'string') {
  4117. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  4118. node = lookup.node;
  4119. } else {
  4120. node = path;
  4121. }
  4122. if (!node.node_ops.setattr) {
  4123. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4124. }
  4125. node.node_ops.setattr(node, {
  4126. timestamp: Date.now()
  4127. // we ignore the uid / gid for now
  4128. });
  4129. }, lchown: function (path, uid, gid) {
  4130. FS.chown(path, uid, gid, true);
  4131. }, fchown: function (fd, uid, gid) {
  4132. var stream = FS.getStream(fd);
  4133. if (!stream) {
  4134. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4135. }
  4136. FS.chown(stream.node, uid, gid);
  4137. }, truncate: function (path, len) {
  4138. if (len < 0) {
  4139. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4140. }
  4141. var node;
  4142. if (typeof path === 'string') {
  4143. var lookup = FS.lookupPath(path, { follow: true });
  4144. node = lookup.node;
  4145. } else {
  4146. node = path;
  4147. }
  4148. if (!node.node_ops.setattr) {
  4149. throw new FS.ErrnoError(ERRNO_CODES.EPERM);
  4150. }
  4151. if (FS.isDir(node.mode)) {
  4152. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  4153. }
  4154. if (!FS.isFile(node.mode)) {
  4155. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4156. }
  4157. var err = FS.nodePermissions(node, 'w');
  4158. if (err) {
  4159. throw new FS.ErrnoError(err);
  4160. }
  4161. node.node_ops.setattr(node, {
  4162. size: len,
  4163. timestamp: Date.now()
  4164. });
  4165. }, ftruncate: function (fd, len) {
  4166. var stream = FS.getStream(fd);
  4167. if (!stream) {
  4168. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4169. }
  4170. if ((stream.flags & 2097155) === 0) {
  4171. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4172. }
  4173. FS.truncate(stream.node, len);
  4174. }, utime: function (path, atime, mtime) {
  4175. var lookup = FS.lookupPath(path, { follow: true });
  4176. var node = lookup.node;
  4177. node.node_ops.setattr(node, {
  4178. timestamp: Math.max(atime, mtime)
  4179. });
  4180. }, open: function (path, flags, mode, fd_start, fd_end) {
  4181. if (path === "") {
  4182. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  4183. }
  4184. flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
  4185. mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
  4186. if ((flags & 64)) {
  4187. mode = (mode & 4095) | 32768;
  4188. } else {
  4189. mode = 0;
  4190. }
  4191. var node;
  4192. if (typeof path === 'object') {
  4193. node = path;
  4194. } else {
  4195. path = PATH.normalize(path);
  4196. try {
  4197. var lookup = FS.lookupPath(path, {
  4198. follow: !(flags & 131072)
  4199. });
  4200. node = lookup.node;
  4201. } catch (e) {
  4202. // ignore
  4203. }
  4204. }
  4205. // perhaps we need to create the node
  4206. var created = false;
  4207. if ((flags & 64)) {
  4208. if (node) {
  4209. // if O_CREAT and O_EXCL are set, error out if the node already exists
  4210. if ((flags & 128)) {
  4211. throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
  4212. }
  4213. } else {
  4214. // node doesn't exist, try to create it
  4215. node = FS.mknod(path, mode, 0);
  4216. created = true;
  4217. }
  4218. }
  4219. if (!node) {
  4220. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  4221. }
  4222. // can't truncate a device
  4223. if (FS.isChrdev(node.mode)) {
  4224. flags &= ~512;
  4225. }
  4226. // if asked only for a directory, then this must be one
  4227. if ((flags & 65536) && !FS.isDir(node.mode)) {
  4228. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  4229. }
  4230. // check permissions, if this is not a file we just created now (it is ok to
  4231. // create and write to a file with read-only permissions; it is read-only
  4232. // for later use)
  4233. if (!created) {
  4234. var err = FS.mayOpen(node, flags);
  4235. if (err) {
  4236. throw new FS.ErrnoError(err);
  4237. }
  4238. }
  4239. // do truncation if necessary
  4240. if ((flags & 512)) {
  4241. FS.truncate(node, 0);
  4242. }
  4243. // we've already handled these, don't pass down to the underlying vfs
  4244. flags &= ~(128 | 512);
  4245. // register the stream with the filesystem
  4246. var stream = FS.createStream({
  4247. node: node,
  4248. path: FS.getPath(node), // we want the absolute path to the node
  4249. flags: flags,
  4250. seekable: true,
  4251. position: 0,
  4252. stream_ops: node.stream_ops,
  4253. // used by the file family libc calls (fopen, fwrite, ferror, etc.)
  4254. ungotten: [],
  4255. error: false
  4256. }, fd_start, fd_end);
  4257. // call the new stream's open function
  4258. if (stream.stream_ops.open) {
  4259. stream.stream_ops.open(stream);
  4260. }
  4261. if (Module['logReadFiles'] && !(flags & 1)) {
  4262. if (!FS.readFiles) FS.readFiles = {};
  4263. if (!(path in FS.readFiles)) {
  4264. FS.readFiles[path] = 1;
  4265. Module['printErr']('read file: ' + path);
  4266. }
  4267. }
  4268. try {
  4269. if (FS.trackingDelegate['onOpenFile']) {
  4270. var trackingFlags = 0;
  4271. if ((flags & 2097155) !== 1) {
  4272. trackingFlags |= FS.tracking.openFlags.READ;
  4273. }
  4274. if ((flags & 2097155) !== 0) {
  4275. trackingFlags |= FS.tracking.openFlags.WRITE;
  4276. }
  4277. FS.trackingDelegate['onOpenFile'](path, trackingFlags);
  4278. }
  4279. } catch (e) {
  4280. console.log("FS.trackingDelegate['onOpenFile']('" + path + "', flags) threw an exception: " + e.message);
  4281. }
  4282. return stream;
  4283. }, close: function (stream) {
  4284. if (stream.getdents) stream.getdents = null; // free readdir state
  4285. try {
  4286. if (stream.stream_ops.close) {
  4287. stream.stream_ops.close(stream);
  4288. }
  4289. } catch (e) {
  4290. throw e;
  4291. } finally {
  4292. FS.closeStream(stream.fd);
  4293. }
  4294. }, llseek: function (stream, offset, whence) {
  4295. if (!stream.seekable || !stream.stream_ops.llseek) {
  4296. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  4297. }
  4298. stream.position = stream.stream_ops.llseek(stream, offset, whence);
  4299. stream.ungotten = [];
  4300. return stream.position;
  4301. }, read: function (stream, buffer, offset, length, position) {
  4302. if (length < 0 || position < 0) {
  4303. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4304. }
  4305. if ((stream.flags & 2097155) === 1) {
  4306. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4307. }
  4308. if (FS.isDir(stream.node.mode)) {
  4309. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  4310. }
  4311. if (!stream.stream_ops.read) {
  4312. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4313. }
  4314. var seeking = true;
  4315. if (typeof position === 'undefined') {
  4316. position = stream.position;
  4317. seeking = false;
  4318. } else if (!stream.seekable) {
  4319. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  4320. }
  4321. var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
  4322. if (!seeking) stream.position += bytesRead;
  4323. return bytesRead;
  4324. }, write: function (stream, buffer, offset, length, position, canOwn) {
  4325. if (length < 0 || position < 0) {
  4326. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4327. }
  4328. if ((stream.flags & 2097155) === 0) {
  4329. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4330. }
  4331. if (FS.isDir(stream.node.mode)) {
  4332. throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
  4333. }
  4334. if (!stream.stream_ops.write) {
  4335. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4336. }
  4337. if (stream.flags & 1024) {
  4338. // seek to the end before writing in append mode
  4339. FS.llseek(stream, 0, 2);
  4340. }
  4341. var seeking = true;
  4342. if (typeof position === 'undefined') {
  4343. position = stream.position;
  4344. seeking = false;
  4345. } else if (!stream.seekable) {
  4346. throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
  4347. }
  4348. var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
  4349. if (!seeking) stream.position += bytesWritten;
  4350. try {
  4351. if (stream.path && FS.trackingDelegate['onWriteToFile']) FS.trackingDelegate['onWriteToFile'](stream.path);
  4352. } catch (e) {
  4353. console.log("FS.trackingDelegate['onWriteToFile']('" + path + "') threw an exception: " + e.message);
  4354. }
  4355. return bytesWritten;
  4356. }, allocate: function (stream, offset, length) {
  4357. if (offset < 0 || length <= 0) {
  4358. throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
  4359. }
  4360. if ((stream.flags & 2097155) === 0) {
  4361. throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4362. }
  4363. if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
  4364. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  4365. }
  4366. if (!stream.stream_ops.allocate) {
  4367. throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
  4368. }
  4369. stream.stream_ops.allocate(stream, offset, length);
  4370. }, mmap: function (stream, buffer, offset, length, position, prot, flags) {
  4371. // TODO if PROT is PROT_WRITE, make sure we have write access
  4372. if ((stream.flags & 2097155) === 1) {
  4373. throw new FS.ErrnoError(ERRNO_CODES.EACCES);
  4374. }
  4375. if (!stream.stream_ops.mmap) {
  4376. throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
  4377. }
  4378. return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
  4379. }, msync: function (stream, buffer, offset, length, mmapFlags) {
  4380. if (!stream || !stream.stream_ops.msync) {
  4381. return 0;
  4382. }
  4383. return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
  4384. }, munmap: function (stream) {
  4385. return 0;
  4386. }, ioctl: function (stream, cmd, arg) {
  4387. if (!stream.stream_ops.ioctl) {
  4388. throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
  4389. }
  4390. return stream.stream_ops.ioctl(stream, cmd, arg);
  4391. }, readFile: function (path, opts) {
  4392. opts = opts || {};
  4393. opts.flags = opts.flags || 'r';
  4394. opts.encoding = opts.encoding || 'binary';
  4395. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  4396. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  4397. }
  4398. var ret;
  4399. var stream = FS.open(path, opts.flags);
  4400. var stat = FS.stat(path);
  4401. var length = stat.size;
  4402. var buf = new Uint8Array(length);
  4403. FS.read(stream, buf, 0, length, 0);
  4404. if (opts.encoding === 'utf8') {
  4405. ret = UTF8ArrayToString(buf, 0);
  4406. } else if (opts.encoding === 'binary') {
  4407. ret = buf;
  4408. }
  4409. FS.close(stream);
  4410. return ret;
  4411. }, writeFile: function (path, data, opts) {
  4412. opts = opts || {};
  4413. opts.flags = opts.flags || 'w';
  4414. opts.encoding = opts.encoding || 'utf8';
  4415. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  4416. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  4417. }
  4418. var stream = FS.open(path, opts.flags, opts.mode);
  4419. if (opts.encoding === 'utf8') {
  4420. var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
  4421. var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
  4422. FS.write(stream, buf, 0, actualNumBytes, 0, opts.canOwn);
  4423. } else if (opts.encoding === 'binary') {
  4424. FS.write(stream, data, 0, data.length, 0, opts.canOwn);
  4425. }
  4426. FS.close(stream);
  4427. }, cwd: function () {
  4428. return FS.currentPath;
  4429. }, chdir: function (path) {
  4430. var lookup = FS.lookupPath(path, { follow: true });
  4431. if (lookup.node === null) {
  4432. throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
  4433. }
  4434. if (!FS.isDir(lookup.node.mode)) {
  4435. throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
  4436. }
  4437. var err = FS.nodePermissions(lookup.node, 'x');
  4438. if (err) {
  4439. throw new FS.ErrnoError(err);
  4440. }
  4441. FS.currentPath = lookup.path;
  4442. }, createDefaultDirectories: function () {
  4443. FS.mkdir('/tmp');
  4444. FS.mkdir('/home');
  4445. FS.mkdir('/home/web_user');
  4446. }, createDefaultDevices: function () {
  4447. // create /dev
  4448. FS.mkdir('/dev');
  4449. // setup /dev/null
  4450. FS.registerDevice(FS.makedev(1, 3), {
  4451. read: function () { return 0; },
  4452. write: function (stream, buffer, offset, length, pos) { return length; }
  4453. });
  4454. FS.mkdev('/dev/null', FS.makedev(1, 3));
  4455. // setup /dev/tty and /dev/tty1
  4456. // stderr needs to print output using Module['printErr']
  4457. // so we register a second tty just for it.
  4458. TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
  4459. TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
  4460. FS.mkdev('/dev/tty', FS.makedev(5, 0));
  4461. FS.mkdev('/dev/tty1', FS.makedev(6, 0));
  4462. // setup /dev/[u]random
  4463. var random_device;
  4464. if (typeof crypto !== 'undefined') {
  4465. // for modern web browsers
  4466. var randomBuffer = new Uint8Array(1);
  4467. random_device = function () { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
  4468. } else if (ENVIRONMENT_IS_NODE) {
  4469. // for nodejs
  4470. random_device = function () { return require('crypto').randomBytes(1)[0]; };
  4471. } else {
  4472. // default for ES5 platforms
  4473. random_device = function () { return (Math.random() * 256) | 0; };
  4474. }
  4475. FS.createDevice('/dev', 'random', random_device);
  4476. FS.createDevice('/dev', 'urandom', random_device);
  4477. // we're not going to emulate the actual shm device,
  4478. // just create the tmp dirs that reside in it commonly
  4479. FS.mkdir('/dev/shm');
  4480. FS.mkdir('/dev/shm/tmp');
  4481. }, createSpecialDirectories: function () {
  4482. // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the name of the stream for fd 6 (see test_unistd_ttyname)
  4483. FS.mkdir('/proc');
  4484. FS.mkdir('/proc/self');
  4485. FS.mkdir('/proc/self/fd');
  4486. FS.mount({
  4487. mount: function () {
  4488. var node = FS.createNode('/proc/self', 'fd', 16384 | 511 /* 0777 */, 73);
  4489. node.node_ops = {
  4490. lookup: function (parent, name) {
  4491. var fd = +name;
  4492. var stream = FS.getStream(fd);
  4493. if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  4494. var ret = {
  4495. parent: null,
  4496. mount: { mountpoint: 'fake' },
  4497. node_ops: { readlink: function () { return stream.path } }
  4498. };
  4499. ret.parent = ret; // make it look like a simple root node
  4500. return ret;
  4501. }
  4502. };
  4503. return node;
  4504. }
  4505. }, {}, '/proc/self/fd');
  4506. }, createStandardStreams: function () {
  4507. // TODO deprecate the old functionality of a single
  4508. // input / output callback and that utilizes FS.createDevice
  4509. // and instead require a unique set of stream ops
  4510. // by default, we symlink the standard streams to the
  4511. // default tty devices. however, if the standard streams
  4512. // have been overwritten we create a unique device for
  4513. // them instead.
  4514. if (Module['stdin']) {
  4515. FS.createDevice('/dev', 'stdin', Module['stdin']);
  4516. } else {
  4517. FS.symlink('/dev/tty', '/dev/stdin');
  4518. }
  4519. if (Module['stdout']) {
  4520. FS.createDevice('/dev', 'stdout', null, Module['stdout']);
  4521. } else {
  4522. FS.symlink('/dev/tty', '/dev/stdout');
  4523. }
  4524. if (Module['stderr']) {
  4525. FS.createDevice('/dev', 'stderr', null, Module['stderr']);
  4526. } else {
  4527. FS.symlink('/dev/tty1', '/dev/stderr');
  4528. }
  4529. // open default streams for the stdin, stdout and stderr devices
  4530. var stdin = FS.open('/dev/stdin', 'r');
  4531. assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
  4532. var stdout = FS.open('/dev/stdout', 'w');
  4533. assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
  4534. var stderr = FS.open('/dev/stderr', 'w');
  4535. assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
  4536. }, ensureErrnoError: function () {
  4537. if (FS.ErrnoError) return;
  4538. FS.ErrnoError = function ErrnoError(errno, node) {
  4539. //Module.printErr(stackTrace()); // useful for debugging
  4540. this.node = node;
  4541. this.setErrno = function (errno) {
  4542. this.errno = errno;
  4543. for (var key in ERRNO_CODES) {
  4544. if (ERRNO_CODES[key] === errno) {
  4545. this.code = key;
  4546. break;
  4547. }
  4548. }
  4549. };
  4550. this.setErrno(errno);
  4551. this.message = ERRNO_MESSAGES[errno];
  4552. };
  4553. FS.ErrnoError.prototype = new Error();
  4554. FS.ErrnoError.prototype.constructor = FS.ErrnoError;
  4555. // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
  4556. [ERRNO_CODES.ENOENT].forEach(function (code) {
  4557. FS.genericErrors[code] = new FS.ErrnoError(code);
  4558. FS.genericErrors[code].stack = '<generic error, no stack>';
  4559. });
  4560. }, staticInit: function () {
  4561. FS.ensureErrnoError();
  4562. FS.nameTable = new Array(4096);
  4563. FS.mount(MEMFS, {}, '/');
  4564. FS.createDefaultDirectories();
  4565. FS.createDefaultDevices();
  4566. FS.createSpecialDirectories();
  4567. FS.filesystems = {
  4568. 'MEMFS': MEMFS,
  4569. 'IDBFS': IDBFS,
  4570. 'NODEFS': NODEFS,
  4571. 'WORKERFS': WORKERFS,
  4572. };
  4573. }, init: function (input, output, error) {
  4574. 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)');
  4575. FS.init.initialized = true;
  4576. FS.ensureErrnoError();
  4577. // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
  4578. Module['stdin'] = input || Module['stdin'];
  4579. Module['stdout'] = output || Module['stdout'];
  4580. Module['stderr'] = error || Module['stderr'];
  4581. FS.createStandardStreams();
  4582. }, quit: function () {
  4583. FS.init.initialized = false;
  4584. // force-flush all streams, so we get musl std streams printed out
  4585. var fflush = Module['_fflush'];
  4586. if (fflush) fflush(0);
  4587. // close all of our streams
  4588. for (var i = 0; i < FS.streams.length; i++) {
  4589. var stream = FS.streams[i];
  4590. if (!stream) {
  4591. continue;
  4592. }
  4593. FS.close(stream);
  4594. }
  4595. }, getMode: function (canRead, canWrite) {
  4596. var mode = 0;
  4597. if (canRead) mode |= 292 | 73;
  4598. if (canWrite) mode |= 146;
  4599. return mode;
  4600. }, joinPath: function (parts, forceRelative) {
  4601. var path = PATH.join.apply(null, parts);
  4602. if (forceRelative && path[0] == '/') path = path.substr(1);
  4603. return path;
  4604. }, absolutePath: function (relative, base) {
  4605. return PATH.resolve(base, relative);
  4606. }, standardizePath: function (path) {
  4607. return PATH.normalize(path);
  4608. }, findObject: function (path, dontResolveLastLink) {
  4609. var ret = FS.analyzePath(path, dontResolveLastLink);
  4610. if (ret.exists) {
  4611. return ret.object;
  4612. } else {
  4613. ___setErrNo(ret.error);
  4614. return null;
  4615. }
  4616. }, analyzePath: function (path, dontResolveLastLink) {
  4617. // operate from within the context of the symlink's target
  4618. try {
  4619. var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  4620. path = lookup.path;
  4621. } catch (e) {
  4622. }
  4623. var ret = {
  4624. isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
  4625. parentExists: false, parentPath: null, parentObject: null
  4626. };
  4627. try {
  4628. var lookup = FS.lookupPath(path, { parent: true });
  4629. ret.parentExists = true;
  4630. ret.parentPath = lookup.path;
  4631. ret.parentObject = lookup.node;
  4632. ret.name = PATH.basename(path);
  4633. lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  4634. ret.exists = true;
  4635. ret.path = lookup.path;
  4636. ret.object = lookup.node;
  4637. ret.name = lookup.node.name;
  4638. ret.isRoot = lookup.path === '/';
  4639. } catch (e) {
  4640. ret.error = e.errno;
  4641. };
  4642. return ret;
  4643. }, createFolder: function (parent, name, canRead, canWrite) {
  4644. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  4645. var mode = FS.getMode(canRead, canWrite);
  4646. return FS.mkdir(path, mode);
  4647. }, createPath: function (parent, path, canRead, canWrite) {
  4648. parent = typeof parent === 'string' ? parent : FS.getPath(parent);
  4649. var parts = path.split('/').reverse();
  4650. while (parts.length) {
  4651. var part = parts.pop();
  4652. if (!part) continue;
  4653. var current = PATH.join2(parent, part);
  4654. try {
  4655. FS.mkdir(current);
  4656. } catch (e) {
  4657. // ignore EEXIST
  4658. }
  4659. parent = current;
  4660. }
  4661. return current;
  4662. }, createFile: function (parent, name, properties, canRead, canWrite) {
  4663. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  4664. var mode = FS.getMode(canRead, canWrite);
  4665. return FS.create(path, mode);
  4666. }, createDataFile: function (parent, name, data, canRead, canWrite, canOwn) {
  4667. var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
  4668. var mode = FS.getMode(canRead, canWrite);
  4669. var node = FS.create(path, mode);
  4670. if (data) {
  4671. if (typeof data === 'string') {
  4672. var arr = new Array(data.length);
  4673. for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
  4674. data = arr;
  4675. }
  4676. // make sure we can write to the file
  4677. FS.chmod(node, mode | 146);
  4678. var stream = FS.open(node, 'w');
  4679. FS.write(stream, data, 0, data.length, 0, canOwn);
  4680. FS.close(stream);
  4681. FS.chmod(node, mode);
  4682. }
  4683. return node;
  4684. }, createDevice: function (parent, name, input, output) {
  4685. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  4686. var mode = FS.getMode(!!input, !!output);
  4687. if (!FS.createDevice.major) FS.createDevice.major = 64;
  4688. var dev = FS.makedev(FS.createDevice.major++, 0);
  4689. // Create a fake device that a set of stream ops to emulate
  4690. // the old behavior.
  4691. FS.registerDevice(dev, {
  4692. open: function (stream) {
  4693. stream.seekable = false;
  4694. },
  4695. close: function (stream) {
  4696. // flush any pending line data
  4697. if (output && output.buffer && output.buffer.length) {
  4698. output(10);
  4699. }
  4700. },
  4701. read: function (stream, buffer, offset, length, pos /* ignored */) {
  4702. var bytesRead = 0;
  4703. for (var i = 0; i < length; i++) {
  4704. var result;
  4705. try {
  4706. result = input();
  4707. } catch (e) {
  4708. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  4709. }
  4710. if (result === undefined && bytesRead === 0) {
  4711. throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
  4712. }
  4713. if (result === null || result === undefined) break;
  4714. bytesRead++;
  4715. buffer[offset + i] = result;
  4716. }
  4717. if (bytesRead) {
  4718. stream.node.timestamp = Date.now();
  4719. }
  4720. return bytesRead;
  4721. },
  4722. write: function (stream, buffer, offset, length, pos) {
  4723. for (var i = 0; i < length; i++) {
  4724. try {
  4725. output(buffer[offset + i]);
  4726. } catch (e) {
  4727. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  4728. }
  4729. }
  4730. if (length) {
  4731. stream.node.timestamp = Date.now();
  4732. }
  4733. return i;
  4734. }
  4735. });
  4736. return FS.mkdev(path, mode, dev);
  4737. }, createLink: function (parent, name, target, canRead, canWrite) {
  4738. var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
  4739. return FS.symlink(target, path);
  4740. }, forceLoadFile: function (obj) {
  4741. if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
  4742. var success = true;
  4743. if (typeof XMLHttpRequest !== 'undefined') {
  4744. 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.");
  4745. } else if (Module['read']) {
  4746. // Command-line.
  4747. try {
  4748. // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
  4749. // read() will try to parse UTF8.
  4750. obj.contents = intArrayFromString(Module['read'](obj.url), true);
  4751. obj.usedBytes = obj.contents.length;
  4752. } catch (e) {
  4753. success = false;
  4754. }
  4755. } else {
  4756. throw new Error('Cannot load without read() or XMLHttpRequest.');
  4757. }
  4758. if (!success) ___setErrNo(ERRNO_CODES.EIO);
  4759. return success;
  4760. }, createLazyFile: function (parent, name, url, canRead, canWrite) {
  4761. // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
  4762. function LazyUint8Array() {
  4763. this.lengthKnown = false;
  4764. this.chunks = []; // Loaded chunks. Index is the chunk number
  4765. }
  4766. LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
  4767. if (idx > this.length - 1 || idx < 0) {
  4768. return undefined;
  4769. }
  4770. var chunkOffset = idx % this.chunkSize;
  4771. var chunkNum = (idx / this.chunkSize) | 0;
  4772. return this.getter(chunkNum)[chunkOffset];
  4773. }
  4774. LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
  4775. this.getter = getter;
  4776. }
  4777. LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
  4778. // Find length
  4779. var xhr = new XMLHttpRequest();
  4780. xhr.open('HEAD', url, false);
  4781. xhr.send(null);
  4782. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  4783. var datalength = Number(xhr.getResponseHeader("Content-length"));
  4784. var header;
  4785. var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
  4786. var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
  4787. var chunkSize = 1024 * 1024; // Chunk size in bytes
  4788. if (!hasByteServing) chunkSize = datalength;
  4789. // Function to get a range from the remote URL.
  4790. var doXHR = (function (from, to) {
  4791. if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
  4792. if (to > datalength - 1) throw new Error("only " + datalength + " bytes available! programmer error!");
  4793. // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
  4794. var xhr = new XMLHttpRequest();
  4795. xhr.open('GET', url, false);
  4796. if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
  4797. // Some hints to the browser that we want binary data.
  4798. if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
  4799. if (xhr.overrideMimeType) {
  4800. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  4801. }
  4802. xhr.send(null);
  4803. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  4804. if (xhr.response !== undefined) {
  4805. return new Uint8Array(xhr.response || []);
  4806. } else {
  4807. return intArrayFromString(xhr.responseText || '', true);
  4808. }
  4809. });
  4810. var lazyArray = this;
  4811. lazyArray.setDataGetter(function (chunkNum) {
  4812. var start = chunkNum * chunkSize;
  4813. var end = (chunkNum + 1) * chunkSize - 1; // including this byte
  4814. end = Math.min(end, datalength - 1); // if datalength-1 is selected, this is the last block
  4815. if (typeof (lazyArray.chunks[chunkNum]) === "undefined") {
  4816. lazyArray.chunks[chunkNum] = doXHR(start, end);
  4817. }
  4818. if (typeof (lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
  4819. return lazyArray.chunks[chunkNum];
  4820. });
  4821. if (usesGzip || !datalength) {
  4822. // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
  4823. chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
  4824. datalength = this.getter(0).length;
  4825. chunkSize = datalength;
  4826. console.log("LazyFiles on gzip forces download of the whole file when length is accessed");
  4827. }
  4828. this._length = datalength;
  4829. this._chunkSize = chunkSize;
  4830. this.lengthKnown = true;
  4831. }
  4832. if (typeof XMLHttpRequest !== 'undefined') {
  4833. if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
  4834. var lazyArray = new LazyUint8Array();
  4835. Object.defineProperties(lazyArray, {
  4836. length: {
  4837. get: function () {
  4838. if (!this.lengthKnown) {
  4839. this.cacheLength();
  4840. }
  4841. return this._length;
  4842. }
  4843. },
  4844. chunkSize: {
  4845. get: function () {
  4846. if (!this.lengthKnown) {
  4847. this.cacheLength();
  4848. }
  4849. return this._chunkSize;
  4850. }
  4851. }
  4852. });
  4853. var properties = { isDevice: false, contents: lazyArray };
  4854. } else {
  4855. var properties = { isDevice: false, url: url };
  4856. }
  4857. var node = FS.createFile(parent, name, properties, canRead, canWrite);
  4858. // This is a total hack, but I want to get this lazy file code out of the
  4859. // core of MEMFS. If we want to keep this lazy file concept I feel it should
  4860. // be its own thin LAZYFS proxying calls to MEMFS.
  4861. if (properties.contents) {
  4862. node.contents = properties.contents;
  4863. } else if (properties.url) {
  4864. node.contents = null;
  4865. node.url = properties.url;
  4866. }
  4867. // Add a function that defers querying the file size until it is asked the first time.
  4868. Object.defineProperties(node, {
  4869. usedBytes: {
  4870. get: function () { return this.contents.length; }
  4871. }
  4872. });
  4873. // override each stream op with one that tries to force load the lazy file first
  4874. var stream_ops = {};
  4875. var keys = Object.keys(node.stream_ops);
  4876. keys.forEach(function (key) {
  4877. var fn = node.stream_ops[key];
  4878. stream_ops[key] = function forceLoadLazyFile() {
  4879. if (!FS.forceLoadFile(node)) {
  4880. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  4881. }
  4882. return fn.apply(null, arguments);
  4883. };
  4884. });
  4885. // use a custom read function
  4886. stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
  4887. if (!FS.forceLoadFile(node)) {
  4888. throw new FS.ErrnoError(ERRNO_CODES.EIO);
  4889. }
  4890. var contents = stream.node.contents;
  4891. if (position >= contents.length)
  4892. return 0;
  4893. var size = Math.min(contents.length - position, length);
  4894. assert(size >= 0);
  4895. if (contents.slice) { // normal array
  4896. for (var i = 0; i < size; i++) {
  4897. buffer[offset + i] = contents[position + i];
  4898. }
  4899. } else {
  4900. for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
  4901. buffer[offset + i] = contents.get(position + i);
  4902. }
  4903. }
  4904. return size;
  4905. };
  4906. node.stream_ops = stream_ops;
  4907. return node;
  4908. }, createPreloadedFile: function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
  4909. Browser.init(); // XXX perhaps this method should move onto Browser?
  4910. // TODO we should allow people to just pass in a complete filename instead
  4911. // of parent and name being that we just join them anyways
  4912. var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
  4913. var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
  4914. function processData(byteArray) {
  4915. function finish(byteArray) {
  4916. if (preFinish) preFinish();
  4917. if (!dontCreateFile) {
  4918. FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
  4919. }
  4920. if (onload) onload();
  4921. removeRunDependency(dep);
  4922. }
  4923. var handled = false;
  4924. Module['preloadPlugins'].forEach(function (plugin) {
  4925. if (handled) return;
  4926. if (plugin['canHandle'](fullname)) {
  4927. plugin['handle'](byteArray, fullname, finish, function () {
  4928. if (onerror) onerror();
  4929. removeRunDependency(dep);
  4930. });
  4931. handled = true;
  4932. }
  4933. });
  4934. if (!handled) finish(byteArray);
  4935. }
  4936. addRunDependency(dep);
  4937. if (typeof url == 'string') {
  4938. Browser.asyncLoad(url, function (byteArray) {
  4939. processData(byteArray);
  4940. }, onerror);
  4941. } else {
  4942. processData(url);
  4943. }
  4944. }, indexedDB: function () {
  4945. return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  4946. }, DB_NAME: function () {
  4947. return 'EM_FS_' + window.location.pathname;
  4948. }, DB_VERSION: 20, DB_STORE_NAME: "FILE_DATA", saveFilesToDB: function (paths, onload, onerror) {
  4949. onload = onload || function () { };
  4950. onerror = onerror || function () { };
  4951. var indexedDB = FS.indexedDB();
  4952. try {
  4953. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  4954. } catch (e) {
  4955. return onerror(e);
  4956. }
  4957. openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
  4958. console.log('creating db');
  4959. var db = openRequest.result;
  4960. db.createObjectStore(FS.DB_STORE_NAME);
  4961. };
  4962. openRequest.onsuccess = function openRequest_onsuccess() {
  4963. var db = openRequest.result;
  4964. var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
  4965. var files = transaction.objectStore(FS.DB_STORE_NAME);
  4966. var ok = 0, fail = 0, total = paths.length;
  4967. function finish() {
  4968. if (fail == 0) onload(); else onerror();
  4969. }
  4970. paths.forEach(function (path) {
  4971. var putRequest = files.put(FS.analyzePath(path).object.contents, path);
  4972. putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
  4973. putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
  4974. });
  4975. transaction.onerror = onerror;
  4976. };
  4977. openRequest.onerror = onerror;
  4978. }, loadFilesFromDB: function (paths, onload, onerror) {
  4979. onload = onload || function () { };
  4980. onerror = onerror || function () { };
  4981. var indexedDB = FS.indexedDB();
  4982. try {
  4983. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  4984. } catch (e) {
  4985. return onerror(e);
  4986. }
  4987. openRequest.onupgradeneeded = onerror; // no database to load from
  4988. openRequest.onsuccess = function openRequest_onsuccess() {
  4989. var db = openRequest.result;
  4990. try {
  4991. var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
  4992. } catch (e) {
  4993. onerror(e);
  4994. return;
  4995. }
  4996. var files = transaction.objectStore(FS.DB_STORE_NAME);
  4997. var ok = 0, fail = 0, total = paths.length;
  4998. function finish() {
  4999. if (fail == 0) onload(); else onerror();
  5000. }
  5001. paths.forEach(function (path) {
  5002. var getRequest = files.get(path);
  5003. getRequest.onsuccess = function getRequest_onsuccess() {
  5004. if (FS.analyzePath(path).exists) {
  5005. FS.unlink(path);
  5006. }
  5007. FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
  5008. ok++;
  5009. if (ok + fail == total) finish();
  5010. };
  5011. getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
  5012. });
  5013. transaction.onerror = onerror;
  5014. };
  5015. openRequest.onerror = onerror;
  5016. }
  5017. }; var SYSCALLS = {
  5018. DEFAULT_POLLMASK: 5, mappings: {}, umask: 511, calculateAt: function (dirfd, path) {
  5019. if (path[0] !== '/') {
  5020. // relative path
  5021. var dir;
  5022. if (dirfd === -100) {
  5023. dir = FS.cwd();
  5024. } else {
  5025. var dirstream = FS.getStream(dirfd);
  5026. if (!dirstream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  5027. dir = dirstream.path;
  5028. }
  5029. path = PATH.join2(dir, path);
  5030. }
  5031. return path;
  5032. }, doStat: function (func, path, buf) {
  5033. try {
  5034. var stat = func(path);
  5035. } catch (e) {
  5036. if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
  5037. // an error occurred while trying to look up the path; we should just report ENOTDIR
  5038. return -ERRNO_CODES.ENOTDIR;
  5039. }
  5040. throw e;
  5041. }
  5042. HEAP32[((buf) >> 2)] = stat.dev;
  5043. HEAP32[(((buf) + (4)) >> 2)] = 0;
  5044. HEAP32[(((buf) + (8)) >> 2)] = stat.ino;
  5045. HEAP32[(((buf) + (12)) >> 2)] = stat.mode;
  5046. HEAP32[(((buf) + (16)) >> 2)] = stat.nlink;
  5047. HEAP32[(((buf) + (20)) >> 2)] = stat.uid;
  5048. HEAP32[(((buf) + (24)) >> 2)] = stat.gid;
  5049. HEAP32[(((buf) + (28)) >> 2)] = stat.rdev;
  5050. HEAP32[(((buf) + (32)) >> 2)] = 0;
  5051. HEAP32[(((buf) + (36)) >> 2)] = stat.size;
  5052. HEAP32[(((buf) + (40)) >> 2)] = 4096;
  5053. HEAP32[(((buf) + (44)) >> 2)] = stat.blocks;
  5054. HEAP32[(((buf) + (48)) >> 2)] = (stat.atime.getTime() / 1000) | 0;
  5055. HEAP32[(((buf) + (52)) >> 2)] = 0;
  5056. HEAP32[(((buf) + (56)) >> 2)] = (stat.mtime.getTime() / 1000) | 0;
  5057. HEAP32[(((buf) + (60)) >> 2)] = 0;
  5058. HEAP32[(((buf) + (64)) >> 2)] = (stat.ctime.getTime() / 1000) | 0;
  5059. HEAP32[(((buf) + (68)) >> 2)] = 0;
  5060. HEAP32[(((buf) + (72)) >> 2)] = stat.ino;
  5061. return 0;
  5062. }, doMsync: function (addr, stream, len, flags) {
  5063. var buffer = new Uint8Array(HEAPU8.subarray(addr, addr + len));
  5064. FS.msync(stream, buffer, 0, len, flags);
  5065. }, doMkdir: function (path, mode) {
  5066. // remove a trailing slash, if one - /a/b/ has basename of '', but
  5067. // we want to create b in the context of this function
  5068. path = PATH.normalize(path);
  5069. if (path[path.length - 1] === '/') path = path.substr(0, path.length - 1);
  5070. FS.mkdir(path, mode, 0);
  5071. return 0;
  5072. }, doMknod: function (path, mode, dev) {
  5073. // we don't want this in the JS API as it uses mknod to create all nodes.
  5074. switch (mode & 61440) {
  5075. case 32768:
  5076. case 8192:
  5077. case 24576:
  5078. case 4096:
  5079. case 49152:
  5080. break;
  5081. default: return -ERRNO_CODES.EINVAL;
  5082. }
  5083. FS.mknod(path, mode, dev);
  5084. return 0;
  5085. }, doReadlink: function (path, buf, bufsize) {
  5086. if (bufsize <= 0) return -ERRNO_CODES.EINVAL;
  5087. var ret = FS.readlink(path);
  5088. var len = Math.min(bufsize, lengthBytesUTF8(ret));
  5089. var endChar = HEAP8[buf + len];
  5090. stringToUTF8(ret, buf, bufsize + 1);
  5091. // readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
  5092. // stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
  5093. HEAP8[buf + len] = endChar;
  5094. return len;
  5095. }, doAccess: function (path, amode) {
  5096. if (amode & ~7) {
  5097. // need a valid mode
  5098. return -ERRNO_CODES.EINVAL;
  5099. }
  5100. var node;
  5101. var lookup = FS.lookupPath(path, { follow: true });
  5102. node = lookup.node;
  5103. var perms = '';
  5104. if (amode & 4) perms += 'r';
  5105. if (amode & 2) perms += 'w';
  5106. if (amode & 1) perms += 'x';
  5107. if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
  5108. return -ERRNO_CODES.EACCES;
  5109. }
  5110. return 0;
  5111. }, doDup: function (path, flags, suggestFD) {
  5112. var suggest = FS.getStream(suggestFD);
  5113. if (suggest) FS.close(suggest);
  5114. return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
  5115. }, doReadv: function (stream, iov, iovcnt, offset) {
  5116. var ret = 0;
  5117. for (var i = 0; i < iovcnt; i++) {
  5118. var ptr = HEAP32[(((iov) + (i * 8)) >> 2)];
  5119. var len = HEAP32[(((iov) + (i * 8 + 4)) >> 2)];
  5120. var curr = FS.read(stream, HEAP8, ptr, len, offset);
  5121. if (curr < 0) return -1;
  5122. ret += curr;
  5123. if (curr < len) break; // nothing more to read
  5124. }
  5125. return ret;
  5126. }, doWritev: function (stream, iov, iovcnt, offset) {
  5127. var ret = 0;
  5128. for (var i = 0; i < iovcnt; i++) {
  5129. var ptr = HEAP32[(((iov) + (i * 8)) >> 2)];
  5130. var len = HEAP32[(((iov) + (i * 8 + 4)) >> 2)];
  5131. var curr = FS.write(stream, HEAP8, ptr, len, offset);
  5132. if (curr < 0) return -1;
  5133. ret += curr;
  5134. }
  5135. return ret;
  5136. }, varargs: 0, get: function (varargs) {
  5137. SYSCALLS.varargs += 4;
  5138. var ret = HEAP32[(((SYSCALLS.varargs) - (4)) >> 2)];
  5139. return ret;
  5140. }, getStr: function () {
  5141. var ret = Pointer_stringify(SYSCALLS.get());
  5142. return ret;
  5143. }, getStreamFromFD: function () {
  5144. var stream = FS.getStream(SYSCALLS.get());
  5145. if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  5146. return stream;
  5147. }, getSocketFromFD: function () {
  5148. var socket = SOCKFS.getSocket(SYSCALLS.get());
  5149. if (!socket) throw new FS.ErrnoError(ERRNO_CODES.EBADF);
  5150. return socket;
  5151. }, getSocketAddress: function (allowNull) {
  5152. var addrp = SYSCALLS.get(), addrlen = SYSCALLS.get();
  5153. if (allowNull && addrp === 0) return null;
  5154. var info = __read_sockaddr(addrp, addrlen);
  5155. if (info.errno) throw new FS.ErrnoError(info.errno);
  5156. info.addr = DNS.lookup_addr(info.addr) || info.addr;
  5157. return info;
  5158. }, get64: function () {
  5159. var low = SYSCALLS.get(), high = SYSCALLS.get();
  5160. if (low >= 0) assert(high === 0);
  5161. else assert(high === -1);
  5162. return low;
  5163. }, getZero: function () {
  5164. assert(SYSCALLS.get() === 0);
  5165. }
  5166. }; function ___syscall91(which, varargs) {
  5167. SYSCALLS.varargs = varargs;
  5168. try {
  5169. // munmap
  5170. var addr = SYSCALLS.get(), len = SYSCALLS.get();
  5171. // TODO: support unmmap'ing parts of allocations
  5172. var info = SYSCALLS.mappings[addr];
  5173. if (!info) return 0;
  5174. if (len === info.len) {
  5175. var stream = FS.getStream(info.fd);
  5176. SYSCALLS.doMsync(addr, stream, len, info.flags)
  5177. FS.munmap(stream);
  5178. SYSCALLS.mappings[addr] = null;
  5179. if (info.allocated) {
  5180. _free(info.malloc);
  5181. }
  5182. }
  5183. return 0;
  5184. } catch (e) {
  5185. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  5186. return -e.errno;
  5187. }
  5188. }
  5189. function __embind_register_emval(rawType, name) {
  5190. name = readLatin1String(name);
  5191. registerType(rawType, {
  5192. name: name,
  5193. 'fromWireType': function (handle) {
  5194. var rv = emval_handle_array[handle].value;
  5195. __emval_decref(handle);
  5196. return rv;
  5197. },
  5198. 'toWireType': function (destructors, value) {
  5199. return __emval_register(value);
  5200. },
  5201. 'argPackAdvance': 8,
  5202. 'readValueFromPointer': simpleReadValueFromPointer,
  5203. destructorFunction: null, // This type does not need a destructor
  5204. // TODO: do we need a deleteObject here? write a test where
  5205. // emval is passed into JS via an interface
  5206. });
  5207. }
  5208. function ___syscall54(which, varargs) {
  5209. SYSCALLS.varargs = varargs;
  5210. try {
  5211. // ioctl
  5212. var stream = SYSCALLS.getStreamFromFD(), op = SYSCALLS.get();
  5213. switch (op) {
  5214. case 21505: {
  5215. if (!stream.tty) return -ERRNO_CODES.ENOTTY;
  5216. return 0;
  5217. }
  5218. case 21506: {
  5219. if (!stream.tty) return -ERRNO_CODES.ENOTTY;
  5220. return 0; // no-op, not actually adjusting terminal settings
  5221. }
  5222. case 21519: {
  5223. if (!stream.tty) return -ERRNO_CODES.ENOTTY;
  5224. var argp = SYSCALLS.get();
  5225. HEAP32[((argp) >> 2)] = 0;
  5226. return 0;
  5227. }
  5228. case 21520: {
  5229. if (!stream.tty) return -ERRNO_CODES.ENOTTY;
  5230. return -ERRNO_CODES.EINVAL; // not supported
  5231. }
  5232. case 21531: {
  5233. var argp = SYSCALLS.get();
  5234. return FS.ioctl(stream, op, argp);
  5235. }
  5236. case 21523: {
  5237. // TODO: in theory we should write to the winsize struct that gets
  5238. // passed in, but for now musl doesn't read anything on it
  5239. if (!stream.tty) return -ERRNO_CODES.ENOTTY;
  5240. return 0;
  5241. }
  5242. default: abort('bad ioctl syscall ' + op);
  5243. }
  5244. } catch (e) {
  5245. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  5246. return -e.errno;
  5247. }
  5248. }
  5249. var _environ = STATICTOP; STATICTOP += 16;; var ___environ = _environ; function ___buildEnvironment(env) {
  5250. // WARNING: Arbitrary limit!
  5251. var MAX_ENV_VALUES = 64;
  5252. var TOTAL_ENV_SIZE = 1024;
  5253. // Statically allocate memory for the environment.
  5254. var poolPtr;
  5255. var envPtr;
  5256. if (!___buildEnvironment.called) {
  5257. ___buildEnvironment.called = true;
  5258. // Set default values. Use string keys for Closure Compiler compatibility.
  5259. ENV['USER'] = ENV['LOGNAME'] = 'web_user';
  5260. ENV['PATH'] = '/';
  5261. ENV['PWD'] = '/';
  5262. ENV['HOME'] = '/home/web_user';
  5263. ENV['LANG'] = 'C';
  5264. ENV['_'] = Module['thisProgram'];
  5265. // Allocate memory.
  5266. poolPtr = allocate(TOTAL_ENV_SIZE, 'i8', ALLOC_STATIC);
  5267. envPtr = allocate(MAX_ENV_VALUES * 4,
  5268. 'i8*', ALLOC_STATIC);
  5269. HEAP32[((envPtr) >> 2)] = poolPtr;
  5270. HEAP32[((_environ) >> 2)] = envPtr;
  5271. } else {
  5272. envPtr = HEAP32[((_environ) >> 2)];
  5273. poolPtr = HEAP32[((envPtr) >> 2)];
  5274. }
  5275. // Collect key=value lines.
  5276. var strings = [];
  5277. var totalSize = 0;
  5278. for (var key in env) {
  5279. if (typeof env[key] === 'string') {
  5280. var line = key + '=' + env[key];
  5281. strings.push(line);
  5282. totalSize += line.length;
  5283. }
  5284. }
  5285. if (totalSize > TOTAL_ENV_SIZE) {
  5286. throw new Error('Environment size exceeded TOTAL_ENV_SIZE!');
  5287. }
  5288. // Make new.
  5289. var ptrSize = 4;
  5290. for (var i = 0; i < strings.length; i++) {
  5291. var line = strings[i];
  5292. writeAsciiToMemory(line, poolPtr);
  5293. HEAP32[(((envPtr) + (i * ptrSize)) >> 2)] = poolPtr;
  5294. poolPtr += line.length + 1;
  5295. }
  5296. HEAP32[(((envPtr) + (strings.length * ptrSize)) >> 2)] = 0;
  5297. } var ENV = {}; function _getenv(name) {
  5298. // char *getenv(const char *name);
  5299. // http://pubs.opengroup.org/onlinepubs/009695399/functions/getenv.html
  5300. if (name === 0) return 0;
  5301. name = Pointer_stringify(name);
  5302. if (!ENV.hasOwnProperty(name)) return 0;
  5303. if (_getenv.ret) _free(_getenv.ret);
  5304. _getenv.ret = allocate(intArrayFromString(ENV[name]), 'i8', ALLOC_NORMAL);
  5305. return _getenv.ret;
  5306. }
  5307. function __isLeapYear(year) {
  5308. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  5309. }
  5310. function __arraySum(array, index) {
  5311. var sum = 0;
  5312. for (var i = 0; i <= index; sum += array[i++]);
  5313. return sum;
  5314. }
  5315. var __MONTH_DAYS_LEAP = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  5316. var __MONTH_DAYS_REGULAR = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function __addDays(date, days) {
  5317. var newDate = new Date(date.getTime());
  5318. while (days > 0) {
  5319. var leap = __isLeapYear(newDate.getFullYear());
  5320. var currentMonth = newDate.getMonth();
  5321. var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth];
  5322. if (days > daysInCurrentMonth - newDate.getDate()) {
  5323. // we spill over to next month
  5324. days -= (daysInCurrentMonth - newDate.getDate() + 1);
  5325. newDate.setDate(1);
  5326. if (currentMonth < 11) {
  5327. newDate.setMonth(currentMonth + 1)
  5328. } else {
  5329. newDate.setMonth(0);
  5330. newDate.setFullYear(newDate.getFullYear() + 1);
  5331. }
  5332. } else {
  5333. // we stay in current month
  5334. newDate.setDate(newDate.getDate() + days);
  5335. return newDate;
  5336. }
  5337. }
  5338. return newDate;
  5339. } function _strftime(s, maxsize, format, tm) {
  5340. // size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr);
  5341. // http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
  5342. var tm_zone = HEAP32[(((tm) + (40)) >> 2)];
  5343. var date = {
  5344. tm_sec: HEAP32[((tm) >> 2)],
  5345. tm_min: HEAP32[(((tm) + (4)) >> 2)],
  5346. tm_hour: HEAP32[(((tm) + (8)) >> 2)],
  5347. tm_mday: HEAP32[(((tm) + (12)) >> 2)],
  5348. tm_mon: HEAP32[(((tm) + (16)) >> 2)],
  5349. tm_year: HEAP32[(((tm) + (20)) >> 2)],
  5350. tm_wday: HEAP32[(((tm) + (24)) >> 2)],
  5351. tm_yday: HEAP32[(((tm) + (28)) >> 2)],
  5352. tm_isdst: HEAP32[(((tm) + (32)) >> 2)],
  5353. tm_gmtoff: HEAP32[(((tm) + (36)) >> 2)],
  5354. tm_zone: tm_zone ? Pointer_stringify(tm_zone) : ''
  5355. };
  5356. var pattern = Pointer_stringify(format);
  5357. // expand format
  5358. var EXPANSION_RULES_1 = {
  5359. '%c': '%a %b %d %H:%M:%S %Y', // Replaced by the locale's appropriate date and time representation - e.g., Mon Aug 3 14:02:01 2013
  5360. '%D': '%m/%d/%y', // Equivalent to %m / %d / %y
  5361. '%F': '%Y-%m-%d', // Equivalent to %Y - %m - %d
  5362. '%h': '%b', // Equivalent to %b
  5363. '%r': '%I:%M:%S %p', // Replaced by the time in a.m. and p.m. notation
  5364. '%R': '%H:%M', // Replaced by the time in 24-hour notation
  5365. '%T': '%H:%M:%S', // Replaced by the time
  5366. '%x': '%m/%d/%y', // Replaced by the locale's appropriate date representation
  5367. '%X': '%H:%M:%S' // Replaced by the locale's appropriate date representation
  5368. };
  5369. for (var rule in EXPANSION_RULES_1) {
  5370. pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_1[rule]);
  5371. }
  5372. var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  5373. var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  5374. function leadingSomething(value, digits, character) {
  5375. var str = typeof value === 'number' ? value.toString() : (value || '');
  5376. while (str.length < digits) {
  5377. str = character[0] + str;
  5378. }
  5379. return str;
  5380. };
  5381. function leadingNulls(value, digits) {
  5382. return leadingSomething(value, digits, '0');
  5383. };
  5384. function compareByDay(date1, date2) {
  5385. function sgn(value) {
  5386. return value < 0 ? -1 : (value > 0 ? 1 : 0);
  5387. };
  5388. var compare;
  5389. if ((compare = sgn(date1.getFullYear() - date2.getFullYear())) === 0) {
  5390. if ((compare = sgn(date1.getMonth() - date2.getMonth())) === 0) {
  5391. compare = sgn(date1.getDate() - date2.getDate());
  5392. }
  5393. }
  5394. return compare;
  5395. };
  5396. function getFirstWeekStartDate(janFourth) {
  5397. switch (janFourth.getDay()) {
  5398. case 0: // Sunday
  5399. return new Date(janFourth.getFullYear() - 1, 11, 29);
  5400. case 1: // Monday
  5401. return janFourth;
  5402. case 2: // Tuesday
  5403. return new Date(janFourth.getFullYear(), 0, 3);
  5404. case 3: // Wednesday
  5405. return new Date(janFourth.getFullYear(), 0, 2);
  5406. case 4: // Thursday
  5407. return new Date(janFourth.getFullYear(), 0, 1);
  5408. case 5: // Friday
  5409. return new Date(janFourth.getFullYear() - 1, 11, 31);
  5410. case 6: // Saturday
  5411. return new Date(janFourth.getFullYear() - 1, 11, 30);
  5412. }
  5413. };
  5414. function getWeekBasedYear(date) {
  5415. var thisDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday);
  5416. var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4);
  5417. var janFourthNextYear = new Date(thisDate.getFullYear() + 1, 0, 4);
  5418. var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
  5419. var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
  5420. if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) {
  5421. // this date is after the start of the first week of this year
  5422. if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) {
  5423. return thisDate.getFullYear() + 1;
  5424. } else {
  5425. return thisDate.getFullYear();
  5426. }
  5427. } else {
  5428. return thisDate.getFullYear() - 1;
  5429. }
  5430. };
  5431. var EXPANSION_RULES_2 = {
  5432. '%a': function (date) {
  5433. return WEEKDAYS[date.tm_wday].substring(0, 3);
  5434. },
  5435. '%A': function (date) {
  5436. return WEEKDAYS[date.tm_wday];
  5437. },
  5438. '%b': function (date) {
  5439. return MONTHS[date.tm_mon].substring(0, 3);
  5440. },
  5441. '%B': function (date) {
  5442. return MONTHS[date.tm_mon];
  5443. },
  5444. '%C': function (date) {
  5445. var year = date.tm_year + 1900;
  5446. return leadingNulls((year / 100) | 0, 2);
  5447. },
  5448. '%d': function (date) {
  5449. return leadingNulls(date.tm_mday, 2);
  5450. },
  5451. '%e': function (date) {
  5452. return leadingSomething(date.tm_mday, 2, ' ');
  5453. },
  5454. '%g': function (date) {
  5455. // %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year.
  5456. // In this system, weeks begin on a Monday and week 1 of the year is the week that includes
  5457. // January 4th, which is also the week that includes the first Thursday of the year, and
  5458. // is also the first week that contains at least four days in the year.
  5459. // If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of
  5460. // the last week of the preceding year; thus, for Saturday 2nd January 1999,
  5461. // %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th,
  5462. // or 31st is a Monday, it and any following days are part of week 1 of the following year.
  5463. // Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.
  5464. return getWeekBasedYear(date).toString().substring(2);
  5465. },
  5466. '%G': function (date) {
  5467. return getWeekBasedYear(date);
  5468. },
  5469. '%H': function (date) {
  5470. return leadingNulls(date.tm_hour, 2);
  5471. },
  5472. '%I': function (date) {
  5473. var twelveHour = date.tm_hour;
  5474. if (twelveHour == 0) twelveHour = 12;
  5475. else if (twelveHour > 12) twelveHour -= 12;
  5476. return leadingNulls(twelveHour, 2);
  5477. },
  5478. '%j': function (date) {
  5479. // Day of the year (001-366)
  5480. return leadingNulls(date.tm_mday + __arraySum(__isLeapYear(date.tm_year + 1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon - 1), 3);
  5481. },
  5482. '%m': function (date) {
  5483. return leadingNulls(date.tm_mon + 1, 2);
  5484. },
  5485. '%M': function (date) {
  5486. return leadingNulls(date.tm_min, 2);
  5487. },
  5488. '%n': function () {
  5489. return '\n';
  5490. },
  5491. '%p': function (date) {
  5492. if (date.tm_hour >= 0 && date.tm_hour < 12) {
  5493. return 'AM';
  5494. } else {
  5495. return 'PM';
  5496. }
  5497. },
  5498. '%S': function (date) {
  5499. return leadingNulls(date.tm_sec, 2);
  5500. },
  5501. '%t': function () {
  5502. return '\t';
  5503. },
  5504. '%u': function (date) {
  5505. var day = new Date(date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, 0, 0, 0, 0);
  5506. return day.getDay() || 7;
  5507. },
  5508. '%U': function (date) {
  5509. // Replaced by the week number of the year as a decimal number [00,53].
  5510. // The first Sunday of January is the first day of week 1;
  5511. // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
  5512. var janFirst = new Date(date.tm_year + 1900, 0, 1);
  5513. var firstSunday = janFirst.getDay() === 0 ? janFirst : __addDays(janFirst, 7 - janFirst.getDay());
  5514. var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday);
  5515. // is target date after the first Sunday?
  5516. if (compareByDay(firstSunday, endDate) < 0) {
  5517. // calculate difference in days between first Sunday and endDate
  5518. var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31;
  5519. var firstSundayUntilEndJanuary = 31 - firstSunday.getDate();
  5520. var days = firstSundayUntilEndJanuary + februaryFirstUntilEndMonth + endDate.getDate();
  5521. return leadingNulls(Math.ceil(days / 7), 2);
  5522. }
  5523. return compareByDay(firstSunday, janFirst) === 0 ? '01' : '00';
  5524. },
  5525. '%V': function (date) {
  5526. // Replaced by the week number of the year (Monday as the first day of the week)
  5527. // as a decimal number [01,53]. If the week containing 1 January has four
  5528. // or more days in the new year, then it is considered week 1.
  5529. // Otherwise, it is the last week of the previous year, and the next week is week 1.
  5530. // Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]
  5531. var janFourthThisYear = new Date(date.tm_year + 1900, 0, 4);
  5532. var janFourthNextYear = new Date(date.tm_year + 1901, 0, 4);
  5533. var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
  5534. var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
  5535. var endDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday);
  5536. if (compareByDay(endDate, firstWeekStartThisYear) < 0) {
  5537. // if given date is before this years first week, then it belongs to the 53rd week of last year
  5538. return '53';
  5539. }
  5540. if (compareByDay(firstWeekStartNextYear, endDate) <= 0) {
  5541. // if given date is after next years first week, then it belongs to the 01th week of next year
  5542. return '01';
  5543. }
  5544. // given date is in between CW 01..53 of this calendar year
  5545. var daysDifference;
  5546. if (firstWeekStartThisYear.getFullYear() < date.tm_year + 1900) {
  5547. // first CW of this year starts last year
  5548. daysDifference = date.tm_yday + 32 - firstWeekStartThisYear.getDate()
  5549. } else {
  5550. // first CW of this year starts this year
  5551. daysDifference = date.tm_yday + 1 - firstWeekStartThisYear.getDate();
  5552. }
  5553. return leadingNulls(Math.ceil(daysDifference / 7), 2);
  5554. },
  5555. '%w': function (date) {
  5556. var day = new Date(date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, 0, 0, 0, 0);
  5557. return day.getDay();
  5558. },
  5559. '%W': function (date) {
  5560. // Replaced by the week number of the year as a decimal number [00,53].
  5561. // The first Monday of January is the first day of week 1;
  5562. // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
  5563. var janFirst = new Date(date.tm_year, 0, 1);
  5564. var firstMonday = janFirst.getDay() === 1 ? janFirst : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7 - janFirst.getDay() + 1);
  5565. var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday);
  5566. // is target date after the first Monday?
  5567. if (compareByDay(firstMonday, endDate) < 0) {
  5568. var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31;
  5569. var firstMondayUntilEndJanuary = 31 - firstMonday.getDate();
  5570. var days = firstMondayUntilEndJanuary + februaryFirstUntilEndMonth + endDate.getDate();
  5571. return leadingNulls(Math.ceil(days / 7), 2);
  5572. }
  5573. return compareByDay(firstMonday, janFirst) === 0 ? '01' : '00';
  5574. },
  5575. '%y': function (date) {
  5576. // Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]
  5577. return (date.tm_year + 1900).toString().substring(2);
  5578. },
  5579. '%Y': function (date) {
  5580. // Replaced by the year as a decimal number (for example, 1997). [ tm_year]
  5581. return date.tm_year + 1900;
  5582. },
  5583. '%z': function (date) {
  5584. // Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ).
  5585. // For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich).
  5586. var off = date.tm_gmtoff;
  5587. var ahead = off >= 0;
  5588. off = Math.abs(off) / 60;
  5589. // convert from minutes into hhmm format (which means 60 minutes = 100 units)
  5590. off = (off / 60) * 100 + (off % 60);
  5591. return (ahead ? '+' : '-') + String("0000" + off).slice(-4);
  5592. },
  5593. '%Z': function (date) {
  5594. return date.tm_zone;
  5595. },
  5596. '%%': function () {
  5597. return '%';
  5598. }
  5599. };
  5600. for (var rule in EXPANSION_RULES_2) {
  5601. if (pattern.indexOf(rule) >= 0) {
  5602. pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_2[rule](date));
  5603. }
  5604. }
  5605. var bytes = intArrayFromString(pattern, false);
  5606. if (bytes.length > maxsize) {
  5607. return 0;
  5608. }
  5609. writeArrayToMemory(bytes, s);
  5610. return bytes.length - 1;
  5611. } function _strftime_l(s, maxsize, format, tm) {
  5612. return _strftime(s, maxsize, format, tm); // no locale support yet
  5613. }
  5614. function ___map_file(pathname, size) {
  5615. ___setErrNo(ERRNO_CODES.EPERM);
  5616. return -1;
  5617. }
  5618. function _emscripten_memcpy_big(dest, src, num) {
  5619. HEAPU8.set(HEAPU8.subarray(src, src + num), dest);
  5620. return dest;
  5621. }
  5622. function __embind_register_enum_value(
  5623. rawEnumType,
  5624. name,
  5625. enumValue
  5626. ) {
  5627. var enumType = requireRegisteredType(rawEnumType, 'enum');
  5628. name = readLatin1String(name);
  5629. var Enum = enumType.constructor;
  5630. var Value = Object.create(enumType.constructor.prototype, {
  5631. value: { value: enumValue },
  5632. constructor: { value: createNamedFunction(enumType.name + '_' + name, function () { }) },
  5633. });
  5634. Enum.values[enumValue] = Value;
  5635. Enum[name] = Value;
  5636. }
  5637. var _llvm_pow_f64 = Math_pow;
  5638. function ___gxx_personality_v0() {
  5639. }
  5640. function _pthread_mutex_destroy() { }
  5641. function _pthread_cond_wait() { return 0; }
  5642. function __embind_register_memory_view(rawType, dataTypeIndex, name) {
  5643. var typeMapping = [
  5644. Int8Array,
  5645. Uint8Array,
  5646. Int16Array,
  5647. Uint16Array,
  5648. Int32Array,
  5649. Uint32Array,
  5650. Float32Array,
  5651. Float64Array,
  5652. ];
  5653. var TA = typeMapping[dataTypeIndex];
  5654. function decodeMemoryView(handle) {
  5655. handle = handle >> 2;
  5656. var heap = HEAPU32;
  5657. var size = heap[handle]; // in elements
  5658. var data = heap[handle + 1]; // byte offset into emscripten heap
  5659. return new TA(heap['buffer'], data, size);
  5660. }
  5661. name = readLatin1String(name);
  5662. registerType(rawType, {
  5663. name: name,
  5664. 'fromWireType': decodeMemoryView,
  5665. 'argPackAdvance': 8,
  5666. 'readValueFromPointer': decodeMemoryView,
  5667. }, {
  5668. ignoreDuplicateRegistrations: true,
  5669. });
  5670. }
  5671. function ensureOverloadTable(proto, methodName, humanName) {
  5672. if (undefined === proto[methodName].overloadTable) {
  5673. var prevFunc = proto[methodName];
  5674. // Inject an overload resolver function that routes to the appropriate overload based on the number of arguments.
  5675. proto[methodName] = function () {
  5676. // TODO This check can be removed in -O3 level "unsafe" optimizations.
  5677. if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) {
  5678. throwBindingError("Function '" + humanName + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + proto[methodName].overloadTable + ")!");
  5679. }
  5680. return proto[methodName].overloadTable[arguments.length].apply(this, arguments);
  5681. };
  5682. // Move the previous function into the overload table.
  5683. proto[methodName].overloadTable = [];
  5684. proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
  5685. }
  5686. } function exposePublicSymbol(name, value, numArguments) {
  5687. if (Module.hasOwnProperty(name)) {
  5688. if (undefined === numArguments || (undefined !== Module[name].overloadTable && undefined !== Module[name].overloadTable[numArguments])) {
  5689. throwBindingError("Cannot register public name '" + name + "' twice");
  5690. }
  5691. // We are exposing a function with the same name as an existing function. Create an overload table and a function selector
  5692. // that routes between the two.
  5693. ensureOverloadTable(Module, name, name);
  5694. if (Module.hasOwnProperty(numArguments)) {
  5695. throwBindingError("Cannot register multiple overloads of a function with the same number of arguments (" + numArguments + ")!");
  5696. }
  5697. // Add the new function into the overload table.
  5698. Module[name].overloadTable[numArguments] = value;
  5699. }
  5700. else {
  5701. Module[name] = value;
  5702. if (undefined !== numArguments) {
  5703. Module[name].numArguments = numArguments;
  5704. }
  5705. }
  5706. }
  5707. function enumReadValueFromPointer(name, shift, signed) {
  5708. switch (shift) {
  5709. case 0: return function (pointer) {
  5710. var heap = signed ? HEAP8 : HEAPU8;
  5711. return this['fromWireType'](heap[pointer]);
  5712. };
  5713. case 1: return function (pointer) {
  5714. var heap = signed ? HEAP16 : HEAPU16;
  5715. return this['fromWireType'](heap[pointer >> 1]);
  5716. };
  5717. case 2: return function (pointer) {
  5718. var heap = signed ? HEAP32 : HEAPU32;
  5719. return this['fromWireType'](heap[pointer >> 2]);
  5720. };
  5721. default:
  5722. throw new TypeError("Unknown integer type: " + name);
  5723. }
  5724. } function __embind_register_enum(
  5725. rawType,
  5726. name,
  5727. size,
  5728. isSigned
  5729. ) {
  5730. var shift = getShiftFromSize(size);
  5731. name = readLatin1String(name);
  5732. function ctor() {
  5733. }
  5734. ctor.values = {};
  5735. registerType(rawType, {
  5736. name: name,
  5737. constructor: ctor,
  5738. 'fromWireType': function (c) {
  5739. return this.constructor.values[c];
  5740. },
  5741. 'toWireType': function (destructors, c) {
  5742. return c.value;
  5743. },
  5744. 'argPackAdvance': 8,
  5745. 'readValueFromPointer': enumReadValueFromPointer(name, shift, isSigned),
  5746. destructorFunction: null,
  5747. });
  5748. exposePublicSymbol(name, ctor);
  5749. }
  5750. function __emval_incref(handle) {
  5751. if (handle > 4) {
  5752. emval_handle_array[handle].refcount += 1;
  5753. }
  5754. }
  5755. function ___assert_fail(condition, filename, line, func) {
  5756. ABORT = true;
  5757. throw 'Assertion failed: ' + Pointer_stringify(condition) + ', at: ' + [filename ? Pointer_stringify(filename) : 'unknown filename', line, func ? Pointer_stringify(func) : 'unknown function'] + ' at ' + stackTrace();
  5758. }
  5759. function __embind_register_void(rawType, name) {
  5760. name = readLatin1String(name);
  5761. registerType(rawType, {
  5762. isVoid: true, // void return values can be optimized out sometimes
  5763. name: name,
  5764. 'argPackAdvance': 0,
  5765. 'fromWireType': function () {
  5766. return undefined;
  5767. },
  5768. 'toWireType': function (destructors, o) {
  5769. // TODO: assert if anything else is given?
  5770. return undefined;
  5771. },
  5772. });
  5773. }
  5774. function _pthread_mutexattr_init() { }
  5775. function _pthread_mutexattr_settype() { }
  5776. function _abort() {
  5777. Module['abort']();
  5778. }
  5779. function _pthread_once(ptr, func) {
  5780. if (!_pthread_once.seen) _pthread_once.seen = {};
  5781. if (ptr in _pthread_once.seen) return;
  5782. Module['dynCall_v'](func);
  5783. _pthread_once.seen[ptr] = 1;
  5784. }
  5785. function ClassHandle_isAliasOf(other) {
  5786. if (!(this instanceof ClassHandle)) {
  5787. return false;
  5788. }
  5789. if (!(other instanceof ClassHandle)) {
  5790. return false;
  5791. }
  5792. var leftClass = this.$$.ptrType.registeredClass;
  5793. var left = this.$$.ptr;
  5794. var rightClass = other.$$.ptrType.registeredClass;
  5795. var right = other.$$.ptr;
  5796. while (leftClass.baseClass) {
  5797. left = leftClass.upcast(left);
  5798. leftClass = leftClass.baseClass;
  5799. }
  5800. while (rightClass.baseClass) {
  5801. right = rightClass.upcast(right);
  5802. rightClass = rightClass.baseClass;
  5803. }
  5804. return leftClass === rightClass && left === right;
  5805. }
  5806. function shallowCopyInternalPointer(o) {
  5807. return {
  5808. count: o.count,
  5809. deleteScheduled: o.deleteScheduled,
  5810. preservePointerOnDelete: o.preservePointerOnDelete,
  5811. ptr: o.ptr,
  5812. ptrType: o.ptrType,
  5813. smartPtr: o.smartPtr,
  5814. smartPtrType: o.smartPtrType,
  5815. };
  5816. }
  5817. function throwInstanceAlreadyDeleted(obj) {
  5818. function getInstanceTypeName(handle) {
  5819. return handle.$$.ptrType.registeredClass.name;
  5820. }
  5821. throwBindingError(getInstanceTypeName(obj) + ' instance already deleted');
  5822. } function ClassHandle_clone() {
  5823. if (!this.$$.ptr) {
  5824. throwInstanceAlreadyDeleted(this);
  5825. }
  5826. if (this.$$.preservePointerOnDelete) {
  5827. this.$$.count.value += 1;
  5828. return this;
  5829. } else {
  5830. var clone = Object.create(Object.getPrototypeOf(this), {
  5831. $$: {
  5832. value: shallowCopyInternalPointer(this.$$),
  5833. }
  5834. });
  5835. clone.$$.count.value += 1;
  5836. clone.$$.deleteScheduled = false;
  5837. return clone;
  5838. }
  5839. }
  5840. function runDestructor(handle) {
  5841. var $$ = handle.$$;
  5842. if ($$.smartPtr) {
  5843. $$.smartPtrType.rawDestructor($$.smartPtr);
  5844. } else {
  5845. $$.ptrType.registeredClass.rawDestructor($$.ptr);
  5846. }
  5847. } function ClassHandle_delete() {
  5848. if (!this.$$.ptr) {
  5849. throwInstanceAlreadyDeleted(this);
  5850. }
  5851. if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
  5852. throwBindingError('Object already scheduled for deletion');
  5853. }
  5854. this.$$.count.value -= 1;
  5855. var toDelete = 0 === this.$$.count.value;
  5856. if (toDelete) {
  5857. runDestructor(this);
  5858. }
  5859. if (!this.$$.preservePointerOnDelete) {
  5860. this.$$.smartPtr = undefined;
  5861. this.$$.ptr = undefined;
  5862. }
  5863. }
  5864. function ClassHandle_isDeleted() {
  5865. return !this.$$.ptr;
  5866. }
  5867. var delayFunction = undefined;
  5868. var deletionQueue = [];
  5869. function flushPendingDeletes() {
  5870. while (deletionQueue.length) {
  5871. var obj = deletionQueue.pop();
  5872. obj.$$.deleteScheduled = false;
  5873. obj['delete']();
  5874. }
  5875. } function ClassHandle_deleteLater() {
  5876. if (!this.$$.ptr) {
  5877. throwInstanceAlreadyDeleted(this);
  5878. }
  5879. if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
  5880. throwBindingError('Object already scheduled for deletion');
  5881. }
  5882. deletionQueue.push(this);
  5883. if (deletionQueue.length === 1 && delayFunction) {
  5884. delayFunction(flushPendingDeletes);
  5885. }
  5886. this.$$.deleteScheduled = true;
  5887. return this;
  5888. } function init_ClassHandle() {
  5889. ClassHandle.prototype['isAliasOf'] = ClassHandle_isAliasOf;
  5890. ClassHandle.prototype['clone'] = ClassHandle_clone;
  5891. ClassHandle.prototype['delete'] = ClassHandle_delete;
  5892. ClassHandle.prototype['isDeleted'] = ClassHandle_isDeleted;
  5893. ClassHandle.prototype['deleteLater'] = ClassHandle_deleteLater;
  5894. } function ClassHandle() {
  5895. }
  5896. var registeredPointers = {};
  5897. function RegisteredClass(
  5898. name,
  5899. constructor,
  5900. instancePrototype,
  5901. rawDestructor,
  5902. baseClass,
  5903. getActualType,
  5904. upcast,
  5905. downcast
  5906. ) {
  5907. this.name = name;
  5908. this.constructor = constructor;
  5909. this.instancePrototype = instancePrototype;
  5910. this.rawDestructor = rawDestructor;
  5911. this.baseClass = baseClass;
  5912. this.getActualType = getActualType;
  5913. this.upcast = upcast;
  5914. this.downcast = downcast;
  5915. this.pureVirtualFunctions = [];
  5916. }
  5917. function upcastPointer(ptr, ptrClass, desiredClass) {
  5918. while (ptrClass !== desiredClass) {
  5919. if (!ptrClass.upcast) {
  5920. throwBindingError("Expected null or instance of " + desiredClass.name + ", got an instance of " + ptrClass.name);
  5921. }
  5922. ptr = ptrClass.upcast(ptr);
  5923. ptrClass = ptrClass.baseClass;
  5924. }
  5925. return ptr;
  5926. } function constNoSmartPtrRawPointerToWireType(destructors, handle) {
  5927. if (handle === null) {
  5928. if (this.isReference) {
  5929. throwBindingError('null is not a valid ' + this.name);
  5930. }
  5931. return 0;
  5932. }
  5933. if (!handle.$$) {
  5934. throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name);
  5935. }
  5936. if (!handle.$$.ptr) {
  5937. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  5938. }
  5939. var handleClass = handle.$$.ptrType.registeredClass;
  5940. var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  5941. return ptr;
  5942. }
  5943. function genericPointerToWireType(destructors, handle) {
  5944. if (handle === null) {
  5945. if (this.isReference) {
  5946. throwBindingError('null is not a valid ' + this.name);
  5947. }
  5948. if (this.isSmartPointer) {
  5949. var ptr = this.rawConstructor();
  5950. if (destructors !== null) {
  5951. destructors.push(this.rawDestructor, ptr);
  5952. }
  5953. return ptr;
  5954. } else {
  5955. return 0;
  5956. }
  5957. }
  5958. if (!handle.$$) {
  5959. throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name);
  5960. }
  5961. if (!handle.$$.ptr) {
  5962. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  5963. }
  5964. if (!this.isConst && handle.$$.ptrType.isConst) {
  5965. throwBindingError('Cannot convert argument of type ' + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + ' to parameter type ' + this.name);
  5966. }
  5967. var handleClass = handle.$$.ptrType.registeredClass;
  5968. var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  5969. if (this.isSmartPointer) {
  5970. // TODO: this is not strictly true
  5971. // We could support BY_EMVAL conversions from raw pointers to smart pointers
  5972. // because the smart pointer can hold a reference to the handle
  5973. if (undefined === handle.$$.smartPtr) {
  5974. throwBindingError('Passing raw pointer to smart pointer is illegal');
  5975. }
  5976. switch (this.sharingPolicy) {
  5977. case 0: // NONE
  5978. // no upcasting
  5979. if (handle.$$.smartPtrType === this) {
  5980. ptr = handle.$$.smartPtr;
  5981. } else {
  5982. throwBindingError('Cannot convert argument of type ' + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + ' to parameter type ' + this.name);
  5983. }
  5984. break;
  5985. case 1: // INTRUSIVE
  5986. ptr = handle.$$.smartPtr;
  5987. break;
  5988. case 2: // BY_EMVAL
  5989. if (handle.$$.smartPtrType === this) {
  5990. ptr = handle.$$.smartPtr;
  5991. } else {
  5992. var clonedHandle = handle['clone']();
  5993. ptr = this.rawShare(
  5994. ptr,
  5995. __emval_register(function () {
  5996. clonedHandle['delete']();
  5997. })
  5998. );
  5999. if (destructors !== null) {
  6000. destructors.push(this.rawDestructor, ptr);
  6001. }
  6002. }
  6003. break;
  6004. default:
  6005. throwBindingError('Unsupporting sharing policy');
  6006. }
  6007. }
  6008. return ptr;
  6009. }
  6010. function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) {
  6011. if (handle === null) {
  6012. if (this.isReference) {
  6013. throwBindingError('null is not a valid ' + this.name);
  6014. }
  6015. return 0;
  6016. }
  6017. if (!handle.$$) {
  6018. throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name);
  6019. }
  6020. if (!handle.$$.ptr) {
  6021. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  6022. }
  6023. if (handle.$$.ptrType.isConst) {
  6024. throwBindingError('Cannot convert argument of type ' + handle.$$.ptrType.name + ' to parameter type ' + this.name);
  6025. }
  6026. var handleClass = handle.$$.ptrType.registeredClass;
  6027. var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  6028. return ptr;
  6029. }
  6030. function RegisteredPointer_getPointee(ptr) {
  6031. if (this.rawGetPointee) {
  6032. ptr = this.rawGetPointee(ptr);
  6033. }
  6034. return ptr;
  6035. }
  6036. function RegisteredPointer_destructor(ptr) {
  6037. if (this.rawDestructor) {
  6038. this.rawDestructor(ptr);
  6039. }
  6040. }
  6041. function RegisteredPointer_deleteObject(handle) {
  6042. if (handle !== null) {
  6043. handle['delete']();
  6044. }
  6045. }
  6046. function downcastPointer(ptr, ptrClass, desiredClass) {
  6047. if (ptrClass === desiredClass) {
  6048. return ptr;
  6049. }
  6050. if (undefined === desiredClass.baseClass) {
  6051. return null; // no conversion
  6052. }
  6053. var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass);
  6054. if (rv === null) {
  6055. return null;
  6056. }
  6057. return desiredClass.downcast(rv);
  6058. }
  6059. function getInheritedInstanceCount() {
  6060. return Object.keys(registeredInstances).length;
  6061. }
  6062. function getLiveInheritedInstances() {
  6063. var rv = [];
  6064. for (var k in registeredInstances) {
  6065. if (registeredInstances.hasOwnProperty(k)) {
  6066. rv.push(registeredInstances[k]);
  6067. }
  6068. }
  6069. return rv;
  6070. }
  6071. function setDelayFunction(fn) {
  6072. delayFunction = fn;
  6073. if (deletionQueue.length && delayFunction) {
  6074. delayFunction(flushPendingDeletes);
  6075. }
  6076. } function init_embind() {
  6077. Module['getInheritedInstanceCount'] = getInheritedInstanceCount;
  6078. Module['getLiveInheritedInstances'] = getLiveInheritedInstances;
  6079. Module['flushPendingDeletes'] = flushPendingDeletes;
  6080. Module['setDelayFunction'] = setDelayFunction;
  6081. } var registeredInstances = {};
  6082. function getBasestPointer(class_, ptr) {
  6083. if (ptr === undefined) {
  6084. throwBindingError('ptr should not be undefined');
  6085. }
  6086. while (class_.baseClass) {
  6087. ptr = class_.upcast(ptr);
  6088. class_ = class_.baseClass;
  6089. }
  6090. return ptr;
  6091. } function getInheritedInstance(class_, ptr) {
  6092. ptr = getBasestPointer(class_, ptr);
  6093. return registeredInstances[ptr];
  6094. }
  6095. function makeClassHandle(prototype, record) {
  6096. if (!record.ptrType || !record.ptr) {
  6097. throwInternalError('makeClassHandle requires ptr and ptrType');
  6098. }
  6099. var hasSmartPtrType = !!record.smartPtrType;
  6100. var hasSmartPtr = !!record.smartPtr;
  6101. if (hasSmartPtrType !== hasSmartPtr) {
  6102. throwInternalError('Both smartPtrType and smartPtr must be specified');
  6103. }
  6104. record.count = { value: 1 };
  6105. return Object.create(prototype, {
  6106. $$: {
  6107. value: record,
  6108. },
  6109. });
  6110. } function RegisteredPointer_fromWireType(ptr) {
  6111. // ptr is a raw pointer (or a raw smartpointer)
  6112. // rawPointer is a maybe-null raw pointer
  6113. var rawPointer = this.getPointee(ptr);
  6114. if (!rawPointer) {
  6115. this.destructor(ptr);
  6116. return null;
  6117. }
  6118. var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer);
  6119. if (undefined !== registeredInstance) {
  6120. // JS object has been neutered, time to repopulate it
  6121. if (0 === registeredInstance.$$.count.value) {
  6122. registeredInstance.$$.ptr = rawPointer;
  6123. registeredInstance.$$.smartPtr = ptr;
  6124. return registeredInstance['clone']();
  6125. } else {
  6126. // else, just increment reference count on existing object
  6127. // it already has a reference to the smart pointer
  6128. var rv = registeredInstance['clone']();
  6129. this.destructor(ptr);
  6130. return rv;
  6131. }
  6132. }
  6133. function makeDefaultHandle() {
  6134. if (this.isSmartPointer) {
  6135. return makeClassHandle(this.registeredClass.instancePrototype, {
  6136. ptrType: this.pointeeType,
  6137. ptr: rawPointer,
  6138. smartPtrType: this,
  6139. smartPtr: ptr,
  6140. });
  6141. } else {
  6142. return makeClassHandle(this.registeredClass.instancePrototype, {
  6143. ptrType: this,
  6144. ptr: ptr,
  6145. });
  6146. }
  6147. }
  6148. var actualType = this.registeredClass.getActualType(rawPointer);
  6149. var registeredPointerRecord = registeredPointers[actualType];
  6150. if (!registeredPointerRecord) {
  6151. return makeDefaultHandle.call(this);
  6152. }
  6153. var toType;
  6154. if (this.isConst) {
  6155. toType = registeredPointerRecord.constPointerType;
  6156. } else {
  6157. toType = registeredPointerRecord.pointerType;
  6158. }
  6159. var dp = downcastPointer(
  6160. rawPointer,
  6161. this.registeredClass,
  6162. toType.registeredClass);
  6163. if (dp === null) {
  6164. return makeDefaultHandle.call(this);
  6165. }
  6166. if (this.isSmartPointer) {
  6167. return makeClassHandle(toType.registeredClass.instancePrototype, {
  6168. ptrType: toType,
  6169. ptr: dp,
  6170. smartPtrType: this,
  6171. smartPtr: ptr,
  6172. });
  6173. } else {
  6174. return makeClassHandle(toType.registeredClass.instancePrototype, {
  6175. ptrType: toType,
  6176. ptr: dp,
  6177. });
  6178. }
  6179. } function init_RegisteredPointer() {
  6180. RegisteredPointer.prototype.getPointee = RegisteredPointer_getPointee;
  6181. RegisteredPointer.prototype.destructor = RegisteredPointer_destructor;
  6182. RegisteredPointer.prototype['argPackAdvance'] = 8;
  6183. RegisteredPointer.prototype['readValueFromPointer'] = simpleReadValueFromPointer;
  6184. RegisteredPointer.prototype['deleteObject'] = RegisteredPointer_deleteObject;
  6185. RegisteredPointer.prototype['fromWireType'] = RegisteredPointer_fromWireType;
  6186. } function RegisteredPointer(
  6187. name,
  6188. registeredClass,
  6189. isReference,
  6190. isConst,
  6191. // smart pointer properties
  6192. isSmartPointer,
  6193. pointeeType,
  6194. sharingPolicy,
  6195. rawGetPointee,
  6196. rawConstructor,
  6197. rawShare,
  6198. rawDestructor
  6199. ) {
  6200. this.name = name;
  6201. this.registeredClass = registeredClass;
  6202. this.isReference = isReference;
  6203. this.isConst = isConst;
  6204. // smart pointer properties
  6205. this.isSmartPointer = isSmartPointer;
  6206. this.pointeeType = pointeeType;
  6207. this.sharingPolicy = sharingPolicy;
  6208. this.rawGetPointee = rawGetPointee;
  6209. this.rawConstructor = rawConstructor;
  6210. this.rawShare = rawShare;
  6211. this.rawDestructor = rawDestructor;
  6212. if (!isSmartPointer && registeredClass.baseClass === undefined) {
  6213. if (isConst) {
  6214. this['toWireType'] = constNoSmartPtrRawPointerToWireType;
  6215. this.destructorFunction = null;
  6216. } else {
  6217. this['toWireType'] = nonConstNoSmartPtrRawPointerToWireType;
  6218. this.destructorFunction = null;
  6219. }
  6220. } else {
  6221. this['toWireType'] = genericPointerToWireType;
  6222. // Here we must leave this.destructorFunction undefined, since whether genericPointerToWireType returns
  6223. // a pointer that needs to be freed up is runtime-dependent, and cannot be evaluated at registration time.
  6224. // TODO: Create an alternative mechanism that allows removing the use of var destructors = []; array in
  6225. // craftInvokerFunction altogether.
  6226. }
  6227. }
  6228. function replacePublicSymbol(name, value, numArguments) {
  6229. if (!Module.hasOwnProperty(name)) {
  6230. throwInternalError('Replacing nonexistant public symbol');
  6231. }
  6232. // If there's an overload table for this symbol, replace the symbol in the overload table instead.
  6233. if (undefined !== Module[name].overloadTable && undefined !== numArguments) {
  6234. Module[name].overloadTable[numArguments] = value;
  6235. }
  6236. else {
  6237. Module[name] = value;
  6238. Module[name].argCount = numArguments;
  6239. }
  6240. }
  6241. function requireFunction(signature, rawFunction) {
  6242. signature = readLatin1String(signature);
  6243. function makeDynCaller(dynCall) {
  6244. var args = [];
  6245. for (var i = 1; i < signature.length; ++i) {
  6246. args.push('a' + i);
  6247. }
  6248. var name = 'dynCall_' + signature + '_' + rawFunction;
  6249. var body = 'return function ' + name + '(' + args.join(', ') + ') {\n';
  6250. body += ' return dynCall(rawFunction' + (args.length ? ', ' : '') + args.join(', ') + ');\n';
  6251. body += '};\n';
  6252. return (new Function('dynCall', 'rawFunction', body))(dynCall, rawFunction);
  6253. }
  6254. var fp;
  6255. if (Module['FUNCTION_TABLE_' + signature] !== undefined) {
  6256. fp = Module['FUNCTION_TABLE_' + signature][rawFunction];
  6257. } else if (typeof FUNCTION_TABLE !== "undefined") {
  6258. fp = FUNCTION_TABLE[rawFunction];
  6259. } else {
  6260. // asm.js does not give direct access to the function tables,
  6261. // and thus we must go through the dynCall interface which allows
  6262. // calling into a signature's function table by pointer value.
  6263. //
  6264. // https://github.com/dherman/asm.js/issues/83
  6265. //
  6266. // This has three main penalties:
  6267. // - dynCall is another function call in the path from JavaScript to C++.
  6268. // - JITs may not predict through the function table indirection at runtime.
  6269. var dc = Module["asm"]['dynCall_' + signature];
  6270. if (dc === undefined) {
  6271. // We will always enter this branch if the signature
  6272. // contains 'f' and PRECISE_F32 is not enabled.
  6273. //
  6274. // Try again, replacing 'f' with 'd'.
  6275. dc = Module["asm"]['dynCall_' + signature.replace(/f/g, 'd')];
  6276. if (dc === undefined) {
  6277. throwBindingError("No dynCall invoker for signature: " + signature);
  6278. }
  6279. }
  6280. fp = makeDynCaller(dc);
  6281. }
  6282. if (typeof fp !== "function") {
  6283. throwBindingError("unknown function pointer with signature " + signature + ": " + rawFunction);
  6284. }
  6285. return fp;
  6286. }
  6287. var UnboundTypeError = undefined; function throwUnboundTypeError(message, types) {
  6288. var unboundTypes = [];
  6289. var seen = {};
  6290. function visit(type) {
  6291. if (seen[type]) {
  6292. return;
  6293. }
  6294. if (registeredTypes[type]) {
  6295. return;
  6296. }
  6297. if (typeDependencies[type]) {
  6298. typeDependencies[type].forEach(visit);
  6299. return;
  6300. }
  6301. unboundTypes.push(type);
  6302. seen[type] = true;
  6303. }
  6304. types.forEach(visit);
  6305. throw new UnboundTypeError(message + ': ' + unboundTypes.map(getTypeName).join([', ']));
  6306. } function __embind_register_class(
  6307. rawType,
  6308. rawPointerType,
  6309. rawConstPointerType,
  6310. baseClassRawType,
  6311. getActualTypeSignature,
  6312. getActualType,
  6313. upcastSignature,
  6314. upcast,
  6315. downcastSignature,
  6316. downcast,
  6317. name,
  6318. destructorSignature,
  6319. rawDestructor
  6320. ) {
  6321. name = readLatin1String(name);
  6322. getActualType = requireFunction(getActualTypeSignature, getActualType);
  6323. if (upcast) {
  6324. upcast = requireFunction(upcastSignature, upcast);
  6325. }
  6326. if (downcast) {
  6327. downcast = requireFunction(downcastSignature, downcast);
  6328. }
  6329. rawDestructor = requireFunction(destructorSignature, rawDestructor);
  6330. var legalFunctionName = makeLegalFunctionName(name);
  6331. exposePublicSymbol(legalFunctionName, function () {
  6332. // this code cannot run if baseClassRawType is zero
  6333. throwUnboundTypeError('Cannot construct ' + name + ' due to unbound types', [baseClassRawType]);
  6334. });
  6335. whenDependentTypesAreResolved(
  6336. [rawType, rawPointerType, rawConstPointerType],
  6337. baseClassRawType ? [baseClassRawType] : [],
  6338. function (base) {
  6339. base = base[0];
  6340. var baseClass;
  6341. var basePrototype;
  6342. if (baseClassRawType) {
  6343. baseClass = base.registeredClass;
  6344. basePrototype = baseClass.instancePrototype;
  6345. } else {
  6346. basePrototype = ClassHandle.prototype;
  6347. }
  6348. var constructor = createNamedFunction(legalFunctionName, function () {
  6349. if (Object.getPrototypeOf(this) !== instancePrototype) {
  6350. throw new BindingError("Use 'new' to construct " + name);
  6351. }
  6352. if (undefined === registeredClass.constructor_body) {
  6353. throw new BindingError(name + " has no accessible constructor");
  6354. }
  6355. var body = registeredClass.constructor_body[arguments.length];
  6356. if (undefined === body) {
  6357. throw new BindingError("Tried to invoke ctor of " + name + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(registeredClass.constructor_body).toString() + ") parameters instead!");
  6358. }
  6359. return body.apply(this, arguments);
  6360. });
  6361. var instancePrototype = Object.create(basePrototype, {
  6362. constructor: { value: constructor },
  6363. });
  6364. constructor.prototype = instancePrototype;
  6365. var registeredClass = new RegisteredClass(
  6366. name,
  6367. constructor,
  6368. instancePrototype,
  6369. rawDestructor,
  6370. baseClass,
  6371. getActualType,
  6372. upcast,
  6373. downcast);
  6374. var referenceConverter = new RegisteredPointer(
  6375. name,
  6376. registeredClass,
  6377. true,
  6378. false,
  6379. false);
  6380. var pointerConverter = new RegisteredPointer(
  6381. name + '*',
  6382. registeredClass,
  6383. false,
  6384. false,
  6385. false);
  6386. var constPointerConverter = new RegisteredPointer(
  6387. name + ' const*',
  6388. registeredClass,
  6389. false,
  6390. true,
  6391. false);
  6392. registeredPointers[rawType] = {
  6393. pointerType: pointerConverter,
  6394. constPointerType: constPointerConverter
  6395. };
  6396. replacePublicSymbol(legalFunctionName, constructor);
  6397. return [referenceConverter, pointerConverter, constPointerConverter];
  6398. }
  6399. );
  6400. }
  6401. function ___lock() { }
  6402. function ___unlock() { }
  6403. function _pthread_getspecific(key) {
  6404. return PTHREAD_SPECIFIC[key] || 0;
  6405. }
  6406. function __exit(status) {
  6407. // void _exit(int status);
  6408. // http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html
  6409. Module['exit'](status);
  6410. } function _exit(status) {
  6411. __exit(status);
  6412. }
  6413. function _pthread_setspecific(key, value) {
  6414. if (!(key in PTHREAD_SPECIFIC)) {
  6415. return ERRNO_CODES.EINVAL;
  6416. }
  6417. PTHREAD_SPECIFIC[key] = value;
  6418. return 0;
  6419. }
  6420. function ___cxa_allocate_exception(size) {
  6421. return _malloc(size);
  6422. }
  6423. function ___cxa_pure_virtual() {
  6424. ABORT = true;
  6425. throw 'Pure virtual function called!';
  6426. }
  6427. var _llvm_ctlz_i32 = true;
  6428. function floatReadValueFromPointer(name, shift) {
  6429. switch (shift) {
  6430. case 2: return function (pointer) {
  6431. return this['fromWireType'](HEAPF32[pointer >> 2]);
  6432. };
  6433. case 3: return function (pointer) {
  6434. return this['fromWireType'](HEAPF64[pointer >> 3]);
  6435. };
  6436. default:
  6437. throw new TypeError("Unknown float type: " + name);
  6438. }
  6439. } function __embind_register_float(rawType, name, size) {
  6440. var shift = getShiftFromSize(size);
  6441. name = readLatin1String(name);
  6442. registerType(rawType, {
  6443. name: name,
  6444. 'fromWireType': function (value) {
  6445. return value;
  6446. },
  6447. 'toWireType': function (destructors, value) {
  6448. // todo: Here we have an opportunity for -O3 level "unsafe" optimizations: we could
  6449. // avoid the following if() and assume value is of proper type.
  6450. if (typeof value !== "number" && typeof value !== "boolean") {
  6451. throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name);
  6452. }
  6453. return value;
  6454. },
  6455. 'argPackAdvance': 8,
  6456. 'readValueFromPointer': floatReadValueFromPointer(name, shift),
  6457. destructorFunction: null, // This type does not need a destructor
  6458. });
  6459. }
  6460. function ___cxa_begin_catch(ptr) {
  6461. var info = EXCEPTIONS.infos[ptr];
  6462. if (info && !info.caught) {
  6463. info.caught = true;
  6464. __ZSt18uncaught_exceptionv.uncaught_exception--;
  6465. }
  6466. if (info) info.rethrown = false;
  6467. EXCEPTIONS.caught.push(ptr);
  6468. EXCEPTIONS.addRef(EXCEPTIONS.deAdjust(ptr));
  6469. return ptr;
  6470. }
  6471. function ___syscall140(which, varargs) {
  6472. SYSCALLS.varargs = varargs;
  6473. try {
  6474. // llseek
  6475. var stream = SYSCALLS.getStreamFromFD(), offset_high = SYSCALLS.get(), offset_low = SYSCALLS.get(), result = SYSCALLS.get(), whence = SYSCALLS.get();
  6476. // NOTE: offset_high is unused - Emscripten's off_t is 32-bit
  6477. var offset = offset_low;
  6478. FS.llseek(stream, offset, whence);
  6479. HEAP32[((result) >> 2)] = stream.position;
  6480. if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
  6481. return 0;
  6482. } catch (e) {
  6483. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  6484. return -e.errno;
  6485. }
  6486. }
  6487. function ___syscall6(which, varargs) {
  6488. SYSCALLS.varargs = varargs;
  6489. try {
  6490. // close
  6491. var stream = SYSCALLS.getStreamFromFD();
  6492. FS.close(stream);
  6493. return 0;
  6494. } catch (e) {
  6495. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  6496. return -e.errno;
  6497. }
  6498. }
  6499. function __embind_register_std_wstring(rawType, charSize, name) {
  6500. // nb. do not cache HEAPU16 and HEAPU32, they may be destroyed by enlargeMemory().
  6501. name = readLatin1String(name);
  6502. var getHeap, shift;
  6503. if (charSize === 2) {
  6504. getHeap = function () { return HEAPU16; };
  6505. shift = 1;
  6506. } else if (charSize === 4) {
  6507. getHeap = function () { return HEAPU32; };
  6508. shift = 2;
  6509. }
  6510. registerType(rawType, {
  6511. name: name,
  6512. 'fromWireType': function (value) {
  6513. var HEAP = getHeap();
  6514. var length = HEAPU32[value >> 2];
  6515. var a = new Array(length);
  6516. var start = (value + 4) >> shift;
  6517. for (var i = 0; i < length; ++i) {
  6518. a[i] = String.fromCharCode(HEAP[start + i]);
  6519. }
  6520. _free(value);
  6521. return a.join('');
  6522. },
  6523. 'toWireType': function (destructors, value) {
  6524. // assumes 4-byte alignment
  6525. var HEAP = getHeap();
  6526. var length = value.length;
  6527. var ptr = _malloc(4 + length * charSize);
  6528. HEAPU32[ptr >> 2] = length;
  6529. var start = (ptr + 4) >> shift;
  6530. for (var i = 0; i < length; ++i) {
  6531. HEAP[start + i] = value.charCodeAt(i);
  6532. }
  6533. if (destructors !== null) {
  6534. destructors.push(_free, ptr);
  6535. }
  6536. return ptr;
  6537. },
  6538. 'argPackAdvance': 8,
  6539. 'readValueFromPointer': simpleReadValueFromPointer,
  6540. destructorFunction: function (ptr) { _free(ptr); },
  6541. });
  6542. }
  6543. function heap32VectorToArray(count, firstElement) {
  6544. var array = [];
  6545. for (var i = 0; i < count; i++) {
  6546. array.push(HEAP32[(firstElement >> 2) + i]);
  6547. }
  6548. return array;
  6549. }
  6550. function runDestructors(destructors) {
  6551. while (destructors.length) {
  6552. var ptr = destructors.pop();
  6553. var del = destructors.pop();
  6554. del(ptr);
  6555. }
  6556. } function __embind_register_class_constructor(
  6557. rawClassType,
  6558. argCount,
  6559. rawArgTypesAddr,
  6560. invokerSignature,
  6561. invoker,
  6562. rawConstructor
  6563. ) {
  6564. var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  6565. invoker = requireFunction(invokerSignature, invoker);
  6566. whenDependentTypesAreResolved([], [rawClassType], function (classType) {
  6567. classType = classType[0];
  6568. var humanName = 'constructor ' + classType.name;
  6569. if (undefined === classType.registeredClass.constructor_body) {
  6570. classType.registeredClass.constructor_body = [];
  6571. }
  6572. if (undefined !== classType.registeredClass.constructor_body[argCount - 1]) {
  6573. throw new BindingError("Cannot register multiple constructors with identical number of parameters (" + (argCount - 1) + ") for class '" + classType.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
  6574. }
  6575. classType.registeredClass.constructor_body[argCount - 1] = function unboundTypeHandler() {
  6576. throwUnboundTypeError('Cannot construct ' + classType.name + ' due to unbound types', rawArgTypes);
  6577. };
  6578. whenDependentTypesAreResolved([], rawArgTypes, function (argTypes) {
  6579. classType.registeredClass.constructor_body[argCount - 1] = function constructor_body() {
  6580. if (arguments.length !== argCount - 1) {
  6581. throwBindingError(humanName + ' called with ' + arguments.length + ' arguments, expected ' + (argCount - 1));
  6582. }
  6583. var destructors = [];
  6584. var args = new Array(argCount);
  6585. args[0] = rawConstructor;
  6586. for (var i = 1; i < argCount; ++i) {
  6587. args[i] = argTypes[i]['toWireType'](destructors, arguments[i - 1]);
  6588. }
  6589. var ptr = invoker.apply(null, args);
  6590. runDestructors(destructors);
  6591. return argTypes[0]['fromWireType'](ptr);
  6592. };
  6593. return [];
  6594. });
  6595. return [];
  6596. });
  6597. }
  6598. function new_(constructor, argumentList) {
  6599. if (!(constructor instanceof Function)) {
  6600. throw new TypeError('new_ called with constructor type ' + typeof (constructor) + " which is not a function");
  6601. }
  6602. /*
  6603. * Previously, the following line was just:
  6604. function dummy() {};
  6605. * Unfortunately, Chrome was preserving 'dummy' as the object's name, even though at creation, the 'dummy' has the
  6606. * correct constructor name. Thus, objects created with IMVU.new would show up in the debugger as 'dummy', which
  6607. * isn't very helpful. Using IMVU.createNamedFunction addresses the issue. Doublely-unfortunately, there's no way
  6608. * to write a test for this behavior. -NRD 2013.02.22
  6609. */
  6610. var dummy = createNamedFunction(constructor.name || 'unknownFunctionName', function () { });
  6611. dummy.prototype = constructor.prototype;
  6612. var obj = new dummy;
  6613. var r = constructor.apply(obj, argumentList);
  6614. return (r instanceof Object) ? r : obj;
  6615. } function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) {
  6616. // humanName: a human-readable string name for the function to be generated.
  6617. // argTypes: An array that contains the embind type objects for all types in the function signature.
  6618. // argTypes[0] is the type object for the function return value.
  6619. // argTypes[1] is the type object for function this object/class type, or null if not crafting an invoker for a class method.
  6620. // argTypes[2...] are the actual function parameters.
  6621. // classType: The embind type object for the class to be bound, or null if this is not a method of a class.
  6622. // cppInvokerFunc: JS Function object to the C++-side function that interops into C++ code.
  6623. // cppTargetFunc: Function pointer (an integer to FUNCTION_TABLE) to the target C++ function the cppInvokerFunc will end up calling.
  6624. var argCount = argTypes.length;
  6625. if (argCount < 2) {
  6626. throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
  6627. }
  6628. var isClassMethodFunc = (argTypes[1] !== null && classType !== null);
  6629. // Free functions with signature "void function()" do not need an invoker that marshalls between wire types.
  6630. // TODO: This omits argument count check - enable only at -O3 or similar.
  6631. // if (ENABLE_UNSAFE_OPTS && argCount == 2 && argTypes[0].name == "void" && !isClassMethodFunc) {
  6632. // return FUNCTION_TABLE[fn];
  6633. // }
  6634. var argsList = "";
  6635. var argsListWired = "";
  6636. for (var i = 0; i < argCount - 2; ++i) {
  6637. argsList += (i !== 0 ? ", " : "") + "arg" + i;
  6638. argsListWired += (i !== 0 ? ", " : "") + "arg" + i + "Wired";
  6639. }
  6640. var invokerFnBody =
  6641. "return function " + makeLegalFunctionName(humanName) + "(" + argsList + ") {\n" +
  6642. "if (arguments.length !== " + (argCount - 2) + ") {\n" +
  6643. "throwBindingError('function " + humanName + " called with ' + arguments.length + ' arguments, expected " + (argCount - 2) + " args!');\n" +
  6644. "}\n";
  6645. // Determine if we need to use a dynamic stack to store the destructors for the function parameters.
  6646. // TODO: Remove this completely once all function invokers are being dynamically generated.
  6647. var needsDestructorStack = false;
  6648. for (var i = 1; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here.
  6649. if (argTypes[i] !== null && argTypes[i].destructorFunction === undefined) { // The type does not define a destructor function - must use dynamic stack
  6650. needsDestructorStack = true;
  6651. break;
  6652. }
  6653. }
  6654. if (needsDestructorStack) {
  6655. invokerFnBody +=
  6656. "var destructors = [];\n";
  6657. }
  6658. var dtorStack = needsDestructorStack ? "destructors" : "null";
  6659. var args1 = ["throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"];
  6660. var args2 = [throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]];
  6661. if (isClassMethodFunc) {
  6662. invokerFnBody += "var thisWired = classParam.toWireType(" + dtorStack + ", this);\n";
  6663. }
  6664. for (var i = 0; i < argCount - 2; ++i) {
  6665. invokerFnBody += "var arg" + i + "Wired = argType" + i + ".toWireType(" + dtorStack + ", arg" + i + "); // " + argTypes[i + 2].name + "\n";
  6666. args1.push("argType" + i);
  6667. args2.push(argTypes[i + 2]);
  6668. }
  6669. if (isClassMethodFunc) {
  6670. argsListWired = "thisWired" + (argsListWired.length > 0 ? ", " : "") + argsListWired;
  6671. }
  6672. var returns = (argTypes[0].name !== "void");
  6673. invokerFnBody +=
  6674. (returns ? "var rv = " : "") + "invoker(fn" + (argsListWired.length > 0 ? ", " : "") + argsListWired + ");\n";
  6675. if (needsDestructorStack) {
  6676. invokerFnBody += "runDestructors(destructors);\n";
  6677. } else {
  6678. for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here. Also skip class type if not a method.
  6679. var paramName = (i === 1 ? "thisWired" : ("arg" + (i - 2) + "Wired"));
  6680. if (argTypes[i].destructorFunction !== null) {
  6681. invokerFnBody += paramName + "_dtor(" + paramName + "); // " + argTypes[i].name + "\n";
  6682. args1.push(paramName + "_dtor");
  6683. args2.push(argTypes[i].destructorFunction);
  6684. }
  6685. }
  6686. }
  6687. if (returns) {
  6688. invokerFnBody += "var ret = retType.fromWireType(rv);\n" +
  6689. "return ret;\n";
  6690. } else {
  6691. }
  6692. invokerFnBody += "}\n";
  6693. args1.push(invokerFnBody);
  6694. var invokerFunction = new_(Function, args1).apply(null, args2);
  6695. return invokerFunction;
  6696. } function __embind_register_class_function(
  6697. rawClassType,
  6698. methodName,
  6699. argCount,
  6700. rawArgTypesAddr, // [ReturnType, ThisType, Args...]
  6701. invokerSignature,
  6702. rawInvoker,
  6703. context,
  6704. isPureVirtual
  6705. ) {
  6706. var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  6707. methodName = readLatin1String(methodName);
  6708. rawInvoker = requireFunction(invokerSignature, rawInvoker);
  6709. whenDependentTypesAreResolved([], [rawClassType], function (classType) {
  6710. classType = classType[0];
  6711. var humanName = classType.name + '.' + methodName;
  6712. if (isPureVirtual) {
  6713. classType.registeredClass.pureVirtualFunctions.push(methodName);
  6714. }
  6715. function unboundTypesHandler() {
  6716. throwUnboundTypeError('Cannot call ' + humanName + ' due to unbound types', rawArgTypes);
  6717. }
  6718. var proto = classType.registeredClass.instancePrototype;
  6719. var method = proto[methodName];
  6720. if (undefined === method || (undefined === method.overloadTable && method.className !== classType.name && method.argCount === argCount - 2)) {
  6721. // This is the first overload to be registered, OR we are replacing a function in the base class with a function in the derived class.
  6722. unboundTypesHandler.argCount = argCount - 2;
  6723. unboundTypesHandler.className = classType.name;
  6724. proto[methodName] = unboundTypesHandler;
  6725. } else {
  6726. // There was an existing function with the same name registered. Set up a function overload routing table.
  6727. ensureOverloadTable(proto, methodName, humanName);
  6728. proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler;
  6729. }
  6730. whenDependentTypesAreResolved([], rawArgTypes, function (argTypes) {
  6731. var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context);
  6732. // Replace the initial unbound-handler-stub function with the appropriate member function, now that all types
  6733. // are resolved. If multiple overloads are registered for this function, the function goes into an overload table.
  6734. if (undefined === proto[methodName].overloadTable) {
  6735. // Set argCount in case an overload is registered later
  6736. memberFunction.argCount = argCount - 2;
  6737. proto[methodName] = memberFunction;
  6738. } else {
  6739. proto[methodName].overloadTable[argCount - 2] = memberFunction;
  6740. }
  6741. return [];
  6742. });
  6743. return [];
  6744. });
  6745. }
  6746. function ___syscall146(which, varargs) {
  6747. SYSCALLS.varargs = varargs;
  6748. try {
  6749. // writev
  6750. var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get();
  6751. return SYSCALLS.doWritev(stream, iov, iovcnt);
  6752. } catch (e) {
  6753. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  6754. return -e.errno;
  6755. }
  6756. }
  6757. function ___syscall145(which, varargs) {
  6758. SYSCALLS.varargs = varargs;
  6759. try {
  6760. // readv
  6761. var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get();
  6762. return SYSCALLS.doReadv(stream, iov, iovcnt);
  6763. } catch (e) {
  6764. if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
  6765. return -e.errno;
  6766. }
  6767. }
  6768. var ___dso_handle = STATICTOP; STATICTOP += 16;;
  6769. embind_init_charCodes();
  6770. BindingError = Module['BindingError'] = extendError(Error, 'BindingError');;
  6771. InternalError = Module['InternalError'] = extendError(Error, 'InternalError');;
  6772. init_emval();;
  6773. FS.staticInit(); __ATINIT__.unshift(function () { if (!Module["noFSInit"] && !FS.init.initialized) FS.init() }); __ATMAIN__.push(function () { FS.ignorePermissions = false }); __ATEXIT__.push(function () { FS.quit() }); Module["FS_createFolder"] = FS.createFolder; Module["FS_createPath"] = FS.createPath; Module["FS_createDataFile"] = FS.createDataFile; Module["FS_createPreloadedFile"] = FS.createPreloadedFile; Module["FS_createLazyFile"] = FS.createLazyFile; Module["FS_createLink"] = FS.createLink; Module["FS_createDevice"] = FS.createDevice; Module["FS_unlink"] = FS.unlink;;
  6774. __ATINIT__.unshift(function () { TTY.init() }); __ATEXIT__.push(function () { TTY.shutdown() });;
  6775. if (ENVIRONMENT_IS_NODE) { var fs = require("fs"); var NODEJS_PATH = require("path"); NODEFS.staticInit(); };
  6776. ___buildEnvironment(ENV);;
  6777. init_ClassHandle();
  6778. init_RegisteredPointer();
  6779. init_embind();;
  6780. UnboundTypeError = Module['UnboundTypeError'] = extendError(Error, 'UnboundTypeError');;
  6781. DYNAMICTOP_PTR = allocate(1, "i32", ALLOC_STATIC);
  6782. STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
  6783. STACK_MAX = STACK_BASE + TOTAL_STACK;
  6784. DYNAMIC_BASE = Runtime.alignMemory(STACK_MAX);
  6785. HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE;
  6786. staticSealed = true; // seal the static portion of memory
  6787. Module['wasmTableSize'] = 3304;
  6788. Module['wasmMaxTableSize'] = 3304;
  6789. function invoke_iiiiiiii(index, a1, a2, a3, a4, a5, a6, a7) {
  6790. try {
  6791. return Module["dynCall_iiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7);
  6792. } catch (e) {
  6793. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6794. Module["setThrew"](1, 0);
  6795. }
  6796. }
  6797. function invoke_iiii(index, a1, a2, a3) {
  6798. try {
  6799. return Module["dynCall_iiii"](index, a1, a2, a3);
  6800. } catch (e) {
  6801. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6802. Module["setThrew"](1, 0);
  6803. }
  6804. }
  6805. function invoke_viiiiii(index, a1, a2, a3, a4, a5, a6) {
  6806. try {
  6807. Module["dynCall_viiiiii"](index, a1, a2, a3, a4, a5, a6);
  6808. } catch (e) {
  6809. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6810. Module["setThrew"](1, 0);
  6811. }
  6812. }
  6813. function invoke_viiiii(index, a1, a2, a3, a4, a5) {
  6814. try {
  6815. Module["dynCall_viiiii"](index, a1, a2, a3, a4, a5);
  6816. } catch (e) {
  6817. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6818. Module["setThrew"](1, 0);
  6819. }
  6820. }
  6821. function invoke_viiiiiii(index, a1, a2, a3, a4, a5, a6, a7) {
  6822. try {
  6823. Module["dynCall_viiiiiii"](index, a1, a2, a3, a4, a5, a6, a7);
  6824. } catch (e) {
  6825. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6826. Module["setThrew"](1, 0);
  6827. }
  6828. }
  6829. function invoke_iiiiiid(index, a1, a2, a3, a4, a5, a6) {
  6830. try {
  6831. return Module["dynCall_iiiiiid"](index, a1, a2, a3, a4, a5, a6);
  6832. } catch (e) {
  6833. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6834. Module["setThrew"](1, 0);
  6835. }
  6836. }
  6837. function invoke_i(index) {
  6838. try {
  6839. return Module["dynCall_i"](index);
  6840. } catch (e) {
  6841. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6842. Module["setThrew"](1, 0);
  6843. }
  6844. }
  6845. function invoke_vi(index, a1) {
  6846. try {
  6847. Module["dynCall_vi"](index, a1);
  6848. } catch (e) {
  6849. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6850. Module["setThrew"](1, 0);
  6851. }
  6852. }
  6853. function invoke_vii(index, a1, a2) {
  6854. try {
  6855. Module["dynCall_vii"](index, a1, a2);
  6856. } catch (e) {
  6857. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6858. Module["setThrew"](1, 0);
  6859. }
  6860. }
  6861. function invoke_iiiiiii(index, a1, a2, a3, a4, a5, a6) {
  6862. try {
  6863. return Module["dynCall_iiiiiii"](index, a1, a2, a3, a4, a5, a6);
  6864. } catch (e) {
  6865. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6866. Module["setThrew"](1, 0);
  6867. }
  6868. }
  6869. function invoke_ii(index, a1) {
  6870. try {
  6871. return Module["dynCall_ii"](index, a1);
  6872. } catch (e) {
  6873. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6874. Module["setThrew"](1, 0);
  6875. }
  6876. }
  6877. function invoke_viijii(index, a1, a2, a3, a4, a5, a6) {
  6878. try {
  6879. Module["dynCall_viijii"](index, a1, a2, a3, a4, a5, a6);
  6880. } catch (e) {
  6881. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6882. Module["setThrew"](1, 0);
  6883. }
  6884. }
  6885. function invoke_iiiiij(index, a1, a2, a3, a4, a5, a6) {
  6886. try {
  6887. return Module["dynCall_iiiiij"](index, a1, a2, a3, a4, a5, a6);
  6888. } catch (e) {
  6889. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6890. Module["setThrew"](1, 0);
  6891. }
  6892. }
  6893. function invoke_viii(index, a1, a2, a3) {
  6894. try {
  6895. Module["dynCall_viii"](index, a1, a2, a3);
  6896. } catch (e) {
  6897. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6898. Module["setThrew"](1, 0);
  6899. }
  6900. }
  6901. function invoke_v(index) {
  6902. try {
  6903. Module["dynCall_v"](index);
  6904. } catch (e) {
  6905. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6906. Module["setThrew"](1, 0);
  6907. }
  6908. }
  6909. function invoke_iiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8) {
  6910. try {
  6911. return Module["dynCall_iiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8);
  6912. } catch (e) {
  6913. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6914. Module["setThrew"](1, 0);
  6915. }
  6916. }
  6917. function invoke_iiiii(index, a1, a2, a3, a4) {
  6918. try {
  6919. return Module["dynCall_iiiii"](index, a1, a2, a3, a4);
  6920. } catch (e) {
  6921. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6922. Module["setThrew"](1, 0);
  6923. }
  6924. }
  6925. function invoke_viiii(index, a1, a2, a3, a4) {
  6926. try {
  6927. Module["dynCall_viiii"](index, a1, a2, a3, a4);
  6928. } catch (e) {
  6929. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6930. Module["setThrew"](1, 0);
  6931. }
  6932. }
  6933. function invoke_iii(index, a1, a2) {
  6934. try {
  6935. return Module["dynCall_iii"](index, a1, a2);
  6936. } catch (e) {
  6937. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6938. Module["setThrew"](1, 0);
  6939. }
  6940. }
  6941. function invoke_iiiiid(index, a1, a2, a3, a4, a5) {
  6942. try {
  6943. return Module["dynCall_iiiiid"](index, a1, a2, a3, a4, a5);
  6944. } catch (e) {
  6945. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6946. Module["setThrew"](1, 0);
  6947. }
  6948. }
  6949. function invoke_iiiiii(index, a1, a2, a3, a4, a5) {
  6950. try {
  6951. return Module["dynCall_iiiiii"](index, a1, a2, a3, a4, a5);
  6952. } catch (e) {
  6953. if (typeof e !== 'number' && e !== 'longjmp') throw e;
  6954. Module["setThrew"](1, 0);
  6955. }
  6956. }
  6957. Module.asmGlobalArg = { "Math": Math, "Int8Array": Int8Array, "Int16Array": Int16Array, "Int32Array": Int32Array, "Uint8Array": Uint8Array, "Uint16Array": Uint16Array, "Uint32Array": Uint32Array, "Float32Array": Float32Array, "Float64Array": Float64Array, "NaN": NaN, "Infinity": Infinity, "byteLength": byteLength };
  6958. Module.asmLibraryArg = { "abort": abort, "assert": assert, "enlargeMemory": enlargeMemory, "getTotalMemory": getTotalMemory, "abortOnCannotGrowMemory": abortOnCannotGrowMemory, "invoke_iiiiiiii": invoke_iiiiiiii, "invoke_iiii": invoke_iiii, "invoke_viiiiii": invoke_viiiiii, "invoke_viiiii": invoke_viiiii, "invoke_viiiiiii": invoke_viiiiiii, "invoke_iiiiiid": invoke_iiiiiid, "invoke_i": invoke_i, "invoke_vi": invoke_vi, "invoke_vii": invoke_vii, "invoke_iiiiiii": invoke_iiiiiii, "invoke_ii": invoke_ii, "invoke_viijii": invoke_viijii, "invoke_iiiiij": invoke_iiiiij, "invoke_viii": invoke_viii, "invoke_v": invoke_v, "invoke_iiiiiiiii": invoke_iiiiiiiii, "invoke_iiiii": invoke_iiiii, "invoke_viiii": invoke_viiii, "invoke_iii": invoke_iii, "invoke_iiiiid": invoke_iiiiid, "invoke_iiiiii": invoke_iiiiii, "floatReadValueFromPointer": floatReadValueFromPointer, "simpleReadValueFromPointer": simpleReadValueFromPointer, "throwInternalError": throwInternalError, "get_first_emval": get_first_emval, "getLiveInheritedInstances": getLiveInheritedInstances, "___assert_fail": ___assert_fail, "__ZSt18uncaught_exceptionv": __ZSt18uncaught_exceptionv, "ClassHandle": ClassHandle, "getShiftFromSize": getShiftFromSize, "__addDays": __addDays, "___cxa_begin_catch": ___cxa_begin_catch, "_emscripten_memcpy_big": _emscripten_memcpy_big, "runDestructor": runDestructor, "throwInstanceAlreadyDeleted": throwInstanceAlreadyDeleted, "__embind_register_std_string": __embind_register_std_string, "init_RegisteredPointer": init_RegisteredPointer, "ClassHandle_isAliasOf": ClassHandle_isAliasOf, "flushPendingDeletes": flushPendingDeletes, "_pthread_mutexattr_settype": _pthread_mutexattr_settype, "makeClassHandle": makeClassHandle, "whenDependentTypesAreResolved": whenDependentTypesAreResolved, "__embind_register_class_constructor": __embind_register_class_constructor, "___cxa_atexit": ___cxa_atexit, "init_ClassHandle": init_ClassHandle, "___syscall140": ___syscall140, "ClassHandle_clone": ClassHandle_clone, "___syscall145": ___syscall145, "___syscall146": ___syscall146, "RegisteredClass": RegisteredClass, "___cxa_find_matching_catch": ___cxa_find_matching_catch, "embind_init_charCodes": embind_init_charCodes, "___setErrNo": ___setErrNo, "__embind_register_bool": __embind_register_bool, "___resumeException": ___resumeException, "createNamedFunction": createNamedFunction, "___syscall91": ___syscall91, "___buildEnvironment": ___buildEnvironment, "__emval_decref": __emval_decref, "_pthread_once": _pthread_once, "init_embind": init_embind, "constNoSmartPtrRawPointerToWireType": constNoSmartPtrRawPointerToWireType, "heap32VectorToArray": heap32VectorToArray, "ClassHandle_delete": ClassHandle_delete, "___lock": ___lock, "___syscall6": ___syscall6, "ensureOverloadTable": ensureOverloadTable, "__embind_register_emval": __embind_register_emval, "new_": new_, "downcastPointer": downcastPointer, "_exit": _exit, "replacePublicSymbol": replacePublicSymbol, "__embind_register_class": __embind_register_class, "_llvm_pow_f64": _llvm_pow_f64, "ClassHandle_deleteLater": ClassHandle_deleteLater, "___syscall54": ___syscall54, "RegisteredPointer_deleteObject": RegisteredPointer_deleteObject, "ClassHandle_isDeleted": ClassHandle_isDeleted, "__embind_register_integer": __embind_register_integer, "___cxa_allocate_exception": ___cxa_allocate_exception, "__emval_take_value": __emval_take_value, "__isLeapYear": __isLeapYear, "enumReadValueFromPointer": enumReadValueFromPointer, "_embind_repr": _embind_repr, "_pthread_getspecific": _pthread_getspecific, "RegisteredPointer": RegisteredPointer, "_pthread_mutex_destroy": _pthread_mutex_destroy, "_getenv": _getenv, "runDestructors": runDestructors, "requireRegisteredType": requireRegisteredType, "makeLegalFunctionName": makeLegalFunctionName, "_pthread_key_create": _pthread_key_create, "upcastPointer": upcastPointer, "init_emval": init_emval, "shallowCopyInternalPointer": shallowCopyInternalPointer, "nonConstNoSmartPtrRawPointerToWireType": nonConstNoSmartPtrRawPointerToWireType, "_abort": _abort, "throwBindingError": throwBindingError, "getTypeName": getTypeName, "exposePublicSymbol": exposePublicSymbol, "RegisteredPointer_fromWireType": RegisteredPointer_fromWireType, "___cxa_pure_virtual": ___cxa_pure_virtual, "_strftime": _strftime, "_pthread_cond_wait": _pthread_cond_wait, "RegisteredPointer_destructor": RegisteredPointer_destructor, "__embind_register_memory_view": __embind_register_memory_view, "getInheritedInstance": getInheritedInstance, "setDelayFunction": setDelayFunction, "___gxx_personality_v0": ___gxx_personality_v0, "extendError": extendError, "__embind_register_void": __embind_register_void, "_strftime_l": _strftime_l, "RegisteredPointer_getPointee": RegisteredPointer_getPointee, "__emval_register": __emval_register, "__embind_register_std_wstring": __embind_register_std_wstring, "__embind_register_class_function": __embind_register_class_function, "__exit": __exit, "throwUnboundTypeError": throwUnboundTypeError, "__arraySum": __arraySum, "__emval_incref": __emval_incref, "readLatin1String": readLatin1String, "craftInvokerFunction": craftInvokerFunction, "getBasestPointer": getBasestPointer, "getInheritedInstanceCount": getInheritedInstanceCount, "__embind_register_float": __embind_register_float, "integerReadValueFromPointer": integerReadValueFromPointer, "___unlock": ___unlock, "__embind_register_enum_value": __embind_register_enum_value, "_pthread_mutexattr_init": _pthread_mutexattr_init, "_pthread_setspecific": _pthread_setspecific, "genericPointerToWireType": genericPointerToWireType, "registerType": registerType, "___cxa_throw": ___cxa_throw, "__embind_register_enum": __embind_register_enum, "count_emval_handles": count_emval_handles, "requireFunction": requireFunction, "_atexit": _atexit, "_pthread_mutex_init": _pthread_mutex_init, "___map_file": ___map_file, "DYNAMICTOP_PTR": DYNAMICTOP_PTR, "tempDoublePtr": tempDoublePtr, "ABORT": ABORT, "STACKTOP": STACKTOP, "STACK_MAX": STACK_MAX, "___dso_handle": ___dso_handle };
  6959. // EMSCRIPTEN_START_ASM
  6960. var asm = Module["asm"]// EMSCRIPTEN_END_ASM
  6961. (Module.asmGlobalArg, Module.asmLibraryArg, buffer);
  6962. Module["asm"] = asm;
  6963. var stackSave = Module["stackSave"] = function () { return Module["asm"]["stackSave"].apply(null, arguments) };
  6964. var setThrew = Module["setThrew"] = function () { return Module["asm"]["setThrew"].apply(null, arguments) };
  6965. var __GLOBAL__sub_I_shaderc_js_cpp = Module["__GLOBAL__sub_I_shaderc_js_cpp"] = function () { return Module["asm"]["__GLOBAL__sub_I_shaderc_js_cpp"].apply(null, arguments) };
  6966. var _fflush = Module["_fflush"] = function () { return Module["asm"]["_fflush"].apply(null, arguments) };
  6967. var ___cxa_is_pointer_type = Module["___cxa_is_pointer_type"] = function () { return Module["asm"]["___cxa_is_pointer_type"].apply(null, arguments) };
  6968. var _memset = Module["_memset"] = function () { return Module["asm"]["_memset"].apply(null, arguments) };
  6969. var __GLOBAL__sub_I_doc_cpp = Module["__GLOBAL__sub_I_doc_cpp"] = function () { return Module["asm"]["__GLOBAL__sub_I_doc_cpp"].apply(null, arguments) };
  6970. var _sbrk = Module["_sbrk"] = function () { return Module["asm"]["_sbrk"].apply(null, arguments) };
  6971. var _memcpy = Module["_memcpy"] = function () { return Module["asm"]["_memcpy"].apply(null, arguments) };
  6972. var _llvm_bswap_i32 = Module["_llvm_bswap_i32"] = function () { return Module["asm"]["_llvm_bswap_i32"].apply(null, arguments) };
  6973. var stackAlloc = Module["stackAlloc"] = function () { return Module["asm"]["stackAlloc"].apply(null, arguments) };
  6974. var getTempRet0 = Module["getTempRet0"] = function () { return Module["asm"]["getTempRet0"].apply(null, arguments) };
  6975. var __GLOBAL__sub_I_bind_cpp = Module["__GLOBAL__sub_I_bind_cpp"] = function () { return Module["asm"]["__GLOBAL__sub_I_bind_cpp"].apply(null, arguments) };
  6976. var setTempRet0 = Module["setTempRet0"] = function () { return Module["asm"]["setTempRet0"].apply(null, arguments) };
  6977. var _pthread_mutex_unlock = Module["_pthread_mutex_unlock"] = function () { return Module["asm"]["_pthread_mutex_unlock"].apply(null, arguments) };
  6978. var __GLOBAL__I_000101 = Module["__GLOBAL__I_000101"] = function () { return Module["asm"]["__GLOBAL__I_000101"].apply(null, arguments) };
  6979. var _emscripten_get_global_libc = Module["_emscripten_get_global_libc"] = function () { return Module["asm"]["_emscripten_get_global_libc"].apply(null, arguments) };
  6980. var ___getTypeName = Module["___getTypeName"] = function () { return Module["asm"]["___getTypeName"].apply(null, arguments) };
  6981. var __GLOBAL__sub_I_iostream_cpp = Module["__GLOBAL__sub_I_iostream_cpp"] = function () { return Module["asm"]["__GLOBAL__sub_I_iostream_cpp"].apply(null, arguments) };
  6982. var _pthread_cond_broadcast = Module["_pthread_cond_broadcast"] = function () { return Module["asm"]["_pthread_cond_broadcast"].apply(null, arguments) };
  6983. var ___errno_location = Module["___errno_location"] = function () { return Module["asm"]["___errno_location"].apply(null, arguments) };
  6984. var ___cxa_can_catch = Module["___cxa_can_catch"] = function () { return Module["asm"]["___cxa_can_catch"].apply(null, arguments) };
  6985. var _free = Module["_free"] = function () { return Module["asm"]["_free"].apply(null, arguments) };
  6986. var runPostSets = Module["runPostSets"] = function () { return Module["asm"]["runPostSets"].apply(null, arguments) };
  6987. var establishStackSpace = Module["establishStackSpace"] = function () { return Module["asm"]["establishStackSpace"].apply(null, arguments) };
  6988. var _memmove = Module["_memmove"] = function () { return Module["asm"]["_memmove"].apply(null, arguments) };
  6989. var stackRestore = Module["stackRestore"] = function () { return Module["asm"]["stackRestore"].apply(null, arguments) };
  6990. var _malloc = Module["_malloc"] = function () { return Module["asm"]["_malloc"].apply(null, arguments) };
  6991. var _pthread_mutex_lock = Module["_pthread_mutex_lock"] = function () { return Module["asm"]["_pthread_mutex_lock"].apply(null, arguments) };
  6992. var _emscripten_replace_memory = Module["_emscripten_replace_memory"] = function () { return Module["asm"]["_emscripten_replace_memory"].apply(null, arguments) };
  6993. var __GLOBAL__sub_I_SPVRemapper_cpp = Module["__GLOBAL__sub_I_SPVRemapper_cpp"] = function () { return Module["asm"]["__GLOBAL__sub_I_SPVRemapper_cpp"].apply(null, arguments) };
  6994. var dynCall_iiiiiiii = Module["dynCall_iiiiiiii"] = function () { return Module["asm"]["dynCall_iiiiiiii"].apply(null, arguments) };
  6995. var dynCall_iiii = Module["dynCall_iiii"] = function () { return Module["asm"]["dynCall_iiii"].apply(null, arguments) };
  6996. var dynCall_viiiiii = Module["dynCall_viiiiii"] = function () { return Module["asm"]["dynCall_viiiiii"].apply(null, arguments) };
  6997. var dynCall_viiiii = Module["dynCall_viiiii"] = function () { return Module["asm"]["dynCall_viiiii"].apply(null, arguments) };
  6998. var dynCall_viiiiiii = Module["dynCall_viiiiiii"] = function () { return Module["asm"]["dynCall_viiiiiii"].apply(null, arguments) };
  6999. var dynCall_iiiiiid = Module["dynCall_iiiiiid"] = function () { return Module["asm"]["dynCall_iiiiiid"].apply(null, arguments) };
  7000. var dynCall_i = Module["dynCall_i"] = function () { return Module["asm"]["dynCall_i"].apply(null, arguments) };
  7001. var dynCall_vi = Module["dynCall_vi"] = function () { return Module["asm"]["dynCall_vi"].apply(null, arguments) };
  7002. var dynCall_vii = Module["dynCall_vii"] = function () { return Module["asm"]["dynCall_vii"].apply(null, arguments) };
  7003. var dynCall_iiiiiii = Module["dynCall_iiiiiii"] = function () { return Module["asm"]["dynCall_iiiiiii"].apply(null, arguments) };
  7004. var dynCall_ii = Module["dynCall_ii"] = function () { return Module["asm"]["dynCall_ii"].apply(null, arguments) };
  7005. var dynCall_viijii = Module["dynCall_viijii"] = function () { return Module["asm"]["dynCall_viijii"].apply(null, arguments) };
  7006. var dynCall_iiiiij = Module["dynCall_iiiiij"] = function () { return Module["asm"]["dynCall_iiiiij"].apply(null, arguments) };
  7007. var dynCall_viii = Module["dynCall_viii"] = function () { return Module["asm"]["dynCall_viii"].apply(null, arguments) };
  7008. var dynCall_v = Module["dynCall_v"] = function () { return Module["asm"]["dynCall_v"].apply(null, arguments) };
  7009. var dynCall_iiiiiiiii = Module["dynCall_iiiiiiiii"] = function () { return Module["asm"]["dynCall_iiiiiiiii"].apply(null, arguments) };
  7010. var dynCall_iiiii = Module["dynCall_iiiii"] = function () { return Module["asm"]["dynCall_iiiii"].apply(null, arguments) };
  7011. var dynCall_viiii = Module["dynCall_viiii"] = function () { return Module["asm"]["dynCall_viiii"].apply(null, arguments) };
  7012. var dynCall_iii = Module["dynCall_iii"] = function () { return Module["asm"]["dynCall_iii"].apply(null, arguments) };
  7013. var dynCall_iiiiid = Module["dynCall_iiiiid"] = function () { return Module["asm"]["dynCall_iiiiid"].apply(null, arguments) };
  7014. var dynCall_iiiiii = Module["dynCall_iiiiii"] = function () { return Module["asm"]["dynCall_iiiiii"].apply(null, arguments) };
  7015. ;
  7016. Runtime.stackAlloc = Module['stackAlloc'];
  7017. Runtime.stackSave = Module['stackSave'];
  7018. Runtime.stackRestore = Module['stackRestore'];
  7019. Runtime.establishStackSpace = Module['establishStackSpace'];
  7020. Runtime.setTempRet0 = Module['setTempRet0'];
  7021. Runtime.getTempRet0 = Module['getTempRet0'];
  7022. // === Auto-generated postamble setup entry stuff ===
  7023. Module['asm'] = asm;
  7024. if (memoryInitializer) {
  7025. if (typeof Module['locateFile'] === 'function') {
  7026. memoryInitializer = Module['locateFile'](memoryInitializer);
  7027. } else if (Module['memoryInitializerPrefixURL']) {
  7028. memoryInitializer = Module['memoryInitializerPrefixURL'] + memoryInitializer;
  7029. }
  7030. if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
  7031. var data = Module['readBinary'](memoryInitializer);
  7032. HEAPU8.set(data, Runtime.GLOBAL_BASE);
  7033. } else {
  7034. addRunDependency('memory initializer');
  7035. var applyMemoryInitializer = function (data) {
  7036. if (data.byteLength) data = new Uint8Array(data);
  7037. HEAPU8.set(data, Runtime.GLOBAL_BASE);
  7038. // Delete the typed array that contains the large blob of the memory initializer request response so that
  7039. // we won't keep unnecessary memory lying around. However, keep the XHR object itself alive so that e.g.
  7040. // its .status field can still be accessed later.
  7041. if (Module['memoryInitializerRequest']) delete Module['memoryInitializerRequest'].response;
  7042. removeRunDependency('memory initializer');
  7043. }
  7044. function doBrowserLoad() {
  7045. Module['readAsync'](memoryInitializer, applyMemoryInitializer, function () {
  7046. throw 'could not load memory initializer ' + memoryInitializer;
  7047. });
  7048. }
  7049. if (Module['memoryInitializerRequest']) {
  7050. // a network request has already been created, just use that
  7051. function useRequest() {
  7052. var request = Module['memoryInitializerRequest'];
  7053. if (request.status !== 200 && request.status !== 0) {
  7054. // If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That
  7055. // means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place.
  7056. // Look in your browser's devtools network console to see what's going on.
  7057. console.warn('a problem seems to have happened with Module.memoryInitializerRequest, status: ' + request.status + ', retrying ' + memoryInitializer);
  7058. doBrowserLoad();
  7059. return;
  7060. }
  7061. applyMemoryInitializer(request.response);
  7062. }
  7063. if (Module['memoryInitializerRequest'].response) {
  7064. setTimeout(useRequest, 0); // it's already here; but, apply it asynchronously
  7065. } else {
  7066. Module['memoryInitializerRequest'].addEventListener('load', useRequest); // wait for it
  7067. }
  7068. } else {
  7069. // fetch it from the network ourselves
  7070. doBrowserLoad();
  7071. }
  7072. }
  7073. }
  7074. /**
  7075. * @constructor
  7076. * @extends {Error}
  7077. */
  7078. function ExitStatus(status) {
  7079. this.name = "ExitStatus";
  7080. this.message = "Program terminated with exit(" + status + ")";
  7081. this.status = status;
  7082. };
  7083. ExitStatus.prototype = new Error();
  7084. ExitStatus.prototype.constructor = ExitStatus;
  7085. var initialStackTop;
  7086. var preloadStartTime = null;
  7087. var calledMain = false;
  7088. dependenciesFulfilled = function runCaller() {
  7089. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  7090. if (!Module['calledRun']) run();
  7091. if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  7092. }
  7093. Module['callMain'] = Module.callMain = function callMain(args) {
  7094. args = args || [];
  7095. ensureInitRuntime();
  7096. var argc = args.length + 1;
  7097. function pad() {
  7098. for (var i = 0; i < 4 - 1; i++) {
  7099. argv.push(0);
  7100. }
  7101. }
  7102. var argv = [allocate(intArrayFromString(Module['thisProgram']), 'i8', ALLOC_NORMAL)];
  7103. pad();
  7104. for (var i = 0; i < argc - 1; i = i + 1) {
  7105. argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
  7106. pad();
  7107. }
  7108. argv.push(0);
  7109. argv = allocate(argv, 'i32', ALLOC_NORMAL);
  7110. try {
  7111. var ret = Module['_main'](argc, argv, 0);
  7112. // if we're not running an evented main loop, it's time to exit
  7113. exit(ret, /* implicit = */ true);
  7114. }
  7115. catch (e) {
  7116. if (e instanceof ExitStatus) {
  7117. // exit() throws this once it's done to make sure execution
  7118. // has been stopped completely
  7119. return;
  7120. } else if (e == 'SimulateInfiniteLoop') {
  7121. // running an evented main loop, don't immediately exit
  7122. Module['noExitRuntime'] = true;
  7123. return;
  7124. } else {
  7125. var toLog = e;
  7126. if (e && typeof e === 'object' && e.stack) {
  7127. toLog = [e, e.stack];
  7128. }
  7129. Module.printErr('exception thrown: ' + toLog);
  7130. Module['quit'](1, e);
  7131. }
  7132. } finally {
  7133. calledMain = true;
  7134. }
  7135. }
  7136. /** @type {function(Array=)} */
  7137. function run(args) {
  7138. args = args || Module['arguments'];
  7139. if (preloadStartTime === null) preloadStartTime = Date.now();
  7140. if (runDependencies > 0) {
  7141. return;
  7142. }
  7143. preRun();
  7144. if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
  7145. if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
  7146. function doRun() {
  7147. if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
  7148. Module['calledRun'] = true;
  7149. if (ABORT) return;
  7150. ensureInitRuntime();
  7151. preMain();
  7152. if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
  7153. if (Module['_main'] && shouldRunNow) Module['callMain'](args);
  7154. postRun();
  7155. }
  7156. if (Module['setStatus']) {
  7157. Module['setStatus']('Running...');
  7158. setTimeout(function () {
  7159. setTimeout(function () {
  7160. Module['setStatus']('');
  7161. }, 1);
  7162. doRun();
  7163. }, 1);
  7164. } else {
  7165. doRun();
  7166. }
  7167. }
  7168. Module['run'] = Module.run = run;
  7169. function exit(status, implicit) {
  7170. if (implicit && Module['noExitRuntime']) {
  7171. return;
  7172. }
  7173. if (Module['noExitRuntime']) {
  7174. } else {
  7175. ABORT = true;
  7176. EXITSTATUS = status;
  7177. STACKTOP = initialStackTop;
  7178. exitRuntime();
  7179. if (Module['onExit']) Module['onExit'](status);
  7180. }
  7181. if (ENVIRONMENT_IS_NODE) {
  7182. process['exit'](status);
  7183. }
  7184. Module['quit'](status, new ExitStatus(status));
  7185. }
  7186. Module['exit'] = Module.exit = exit;
  7187. var abortDecorators = [];
  7188. function abort(what) {
  7189. if (Module['onAbort']) {
  7190. Module['onAbort'](what);
  7191. }
  7192. if (what !== undefined) {
  7193. Module.print(what);
  7194. Module.printErr(what);
  7195. what = JSON.stringify(what)
  7196. } else {
  7197. what = '';
  7198. }
  7199. ABORT = true;
  7200. EXITSTATUS = 1;
  7201. var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
  7202. var output = 'abort(' + what + ') at ' + stackTrace() + extra;
  7203. if (abortDecorators) {
  7204. abortDecorators.forEach(function (decorator) {
  7205. output = decorator(output, what);
  7206. });
  7207. }
  7208. throw output;
  7209. }
  7210. Module['abort'] = Module.abort = abort;
  7211. // {{PRE_RUN_ADDITIONS}}
  7212. if (Module['preInit']) {
  7213. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  7214. while (Module['preInit'].length > 0) {
  7215. Module['preInit'].pop()();
  7216. }
  7217. }
  7218. // shouldRunNow refers to calling main(), not run().
  7219. var shouldRunNow = true;
  7220. if (Module['noInitialRun']) {
  7221. shouldRunNow = false;
  7222. }
  7223. run();
  7224. // {{POST_RUN_ADDITIONS}}
  7225. // {{MODULE_ADDITIONS}}
  7226. return returnPromise;
  7227. };
  7228. return Shaderc;
  7229. });
  7230. // export default Shaderc;
  7231. // window.Shaderc = Shaderc;