n-body.c.js 249 KB

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