| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246 |
- /*
- ==============================================================================
- LLVM Release License
- ==============================================================================
- University of Illinois/NCSA
- Open Source License
- Copyright (c) 2003, 2004, 2005 University of Illinois at Urbana-Champaign.
- All rights reserved.
- Developed by:
- LLVM Team
- University of Illinois at Urbana-Champaign
- http://llvm.org/
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
- Copyright (C) 2014 Apple Inc. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- //OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- var referenceScore = 2444;
- if (typeof (WScript) === "undefined") {
- var WScript = {
- Echo: print
- }
- }
- var print = function () {};
- var performance = performance || {};
- performance.now = (function () {
- return performance.now ||
- performance.mozNow ||
- performance.msNow ||
- performance.oNow ||
- performance.webkitNow ||
- Date.now;
- })();
- function reportResult(score) {
- WScript.Echo("### SCORE: " + (100 * referenceScore / score));
- }
- var top = {};
- top.JetStream = {
- goodTime: performance.now,
- reportResult: reportResult
- };
- var __time_before = top.JetStream.goodTime();
- ////////////////////////////////////////////////////////////////////////////////
- // Test
- ////////////////////////////////////////////////////////////////////////////////
- // The Module object: Our interface to the outside world. We import
- // and export values on it, and do the work to get that through
- // closure compiler if necessary. There are various ways Module can be used:
- // 1. Not defined. We create it here
- // 2. A function parameter, function(Module) { ..generated code.. }
- // 3. pre-run appended it, var Module = {}; ..generated code..
- // 4. External script tag defines var Module.
- // We need to do an eval in order to handle the closure compiler
- // case, where this code here is minified but Module was defined
- // elsewhere (e.g. case 4 above). We also need to check if Module
- // already exists (e.g. case 3 above).
- // Note that if you want to run closure, and also to use Module
- // after the generated code, you will need to define var Module = {};
- // before the code. Then that object will be used in the code, and you
- // can continue to use Module afterwards as well.
- var Module;
- if (!Module) Module = eval('(function() { try { return Module || {} } catch(e) { return {} } })()');
- // Sometimes an existing Module object exists with properties
- // meant to overwrite the default module functionality. Here
- // we collect those properties and reapply _after_ we configure
- // the current environment's defaults to avoid having to be so
- // defensive during initialization.
- var moduleOverrides = {};
- for (var key in Module) {
- if (Module.hasOwnProperty(key)) {
- moduleOverrides[key] = Module[key];
- }
- }
- // The environment setup code below is customized to use Module.
- // *** Environment setup code ***
- var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
- var ENVIRONMENT_IS_WEB = typeof window === 'object';
- var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
- var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
- if (ENVIRONMENT_IS_NODE) {
- // Expose functionality in the same simple way that the shells work
- // Note that we pollute the global namespace here, otherwise we break in node
- if (!Module['print']) Module['print'] = function print(x) {
- process['stdout'].write(x + '\n');
- };
- if (!Module['printErr']) Module['printErr'] = function printErr(x) {
- process['stderr'].write(x + '\n');
- };
- var nodeFS = require('fs');
- var nodePath = require('path');
- Module['read'] = function read(filename, binary) {
- filename = nodePath['normalize'](filename);
- var ret = nodeFS['readFileSync'](filename);
- // The path is absolute if the normalized version is the same as the resolved.
- if (!ret && filename != nodePath['resolve'](filename)) {
- filename = path.join(__dirname, '..', 'src', filename);
- ret = nodeFS['readFileSync'](filename);
- }
- if (ret && !binary) ret = ret.toString();
- return ret;
- };
- Module['readBinary'] = function readBinary(filename) {
- return Module['read'](filename, true)
- };
- Module['load'] = function load(f) {
- globalEval(read(f));
- };
- Module['arguments'] = process['argv'].slice(2);
- module['exports'] = Module;
- } else if (ENVIRONMENT_IS_SHELL) {
- if (!Module['print']) Module['print'] = print;
- if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not present in v8 or older sm
- if (typeof read != 'undefined') {
- Module['read'] = read;
- } else {
- Module['read'] = function read() {
- throw 'no read() available (jsc?)'
- };
- }
- Module['readBinary'] = function readBinary(f) {
- return read(f, 'binary');
- };
- if (typeof scriptArgs != 'undefined') {
- Module['arguments'] = scriptArgs;
- } else if (typeof arguments != 'undefined') {
- Module['arguments'] = arguments;
- }
- this['Module'] = Module;
- 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)
- } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
- Module['read'] = function read(url) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, false);
- xhr.send(null);
- return xhr.responseText;
- };
- if (typeof arguments != 'undefined') {
- Module['arguments'] = arguments;
- }
- if (typeof console !== 'undefined') {
- if (!Module['print']) Module['print'] = function print(x) {
- console.log(x);
- };
- if (!Module['printErr']) Module['printErr'] = function printErr(x) {
- console.log(x);
- };
- } else {
- // Probably a worker, and without console.log. We can do very little here...
- var TRY_USE_DUMP = false;
- if (!Module['print']) Module['print'] = (TRY_USE_DUMP && (typeof (dump) !== "undefined") ? (function (x) {
- dump(x);
- }) : (function (x) {
- // self.postMessage(x); // enable this if you want stdout to be sent as messages
- }));
- }
- if (ENVIRONMENT_IS_WEB) {
- this['Module'] = Module;
- } else {
- Module['load'] = importScripts;
- }
- } else {
- // Unreachable because SHELL is dependant on the others
- throw 'Unknown runtime environment. Where are we?';
- }
- function globalEval(x) {
- eval.call(null, x);
- }
- if (!Module['load'] == 'undefined' && Module['read']) {
- Module['load'] = function load(f) {
- globalEval(Module['read'](f));
- };
- }
- if (!Module['print']) {
- Module['print'] = function () {};
- }
- if (!Module['printErr']) {
- Module['printErr'] = Module['print'];
- }
- if (!Module['arguments']) {
- Module['arguments'] = [];
- }
- // *** Environment setup code ***
- // Closure helpers
- Module.print = Module['print'];
- Module.printErr = Module['printErr'];
- // Callbacks
- Module['preRun'] = [];
- Module['postRun'] = [];
- // Merge back in the overrides
- for (var key in moduleOverrides) {
- if (moduleOverrides.hasOwnProperty(key)) {
- Module[key] = moduleOverrides[key];
- }
- }
- // === Auto-generated preamble library stuff ===
- //========================================
- // Runtime code shared with compiler
- //========================================
- var Runtime = {
- stackSave: function () {
- return STACKTOP;
- },
- stackRestore: function (stackTop) {
- STACKTOP = stackTop;
- },
- forceAlign: function (target, quantum) {
- quantum = quantum || 4;
- if (quantum == 1) return target;
- if (isNumber(target) && isNumber(quantum)) {
- return Math.ceil(target / quantum) * quantum;
- } else if (isNumber(quantum) && isPowerOfTwo(quantum)) {
- return '(((' + target + ')+' + (quantum - 1) + ')&' + -quantum + ')';
- }
- return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
- },
- isNumberType: function (type) {
- return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
- },
- isPointerType: function isPointerType(type) {
- return type[type.length - 1] == '*';
- },
- isStructType: function isStructType(type) {
- if (isPointerType(type)) return false;
- if (isArrayType(type)) return true;
- if (/<?\{ ?[^}]* ?\}>?/.test(type)) return true; // { i32, i8 } etc. - anonymous struct types
- // See comment in isStructPointerType()
- return type[0] == '%';
- },
- INT_TYPES: {
- "i1": 0,
- "i8": 0,
- "i16": 0,
- "i32": 0,
- "i64": 0
- },
- FLOAT_TYPES: {
- "float": 0,
- "double": 0
- },
- or64: function (x, y) {
- var l = (x | 0) | (y | 0);
- var h = (Math.round(x / 4294967296) | Math.round(y / 4294967296)) * 4294967296;
- return l + h;
- },
- and64: function (x, y) {
- var l = (x | 0) & (y | 0);
- var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 4294967296;
- return l + h;
- },
- xor64: function (x, y) {
- var l = (x | 0) ^ (y | 0);
- var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 4294967296;
- return l + h;
- },
- getNativeTypeSize: function (type) {
- switch (type) {
- case 'i1':
- case 'i8':
- return 1;
- case 'i16':
- return 2;
- case 'i32':
- return 4;
- case 'i64':
- return 8;
- case 'float':
- return 4;
- case 'double':
- return 8;
- default:
- {
- if (type[type.length - 1] === '*') {
- return Runtime.QUANTUM_SIZE; // A pointer
- } else if (type[0] === 'i') {
- var bits = parseInt(type.substr(1));
- assert(bits % 8 === 0);
- return bits / 8;
- } else {
- return 0;
- }
- }
- }
- },
- getNativeFieldSize: function (type) {
- return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
- },
- dedup: function dedup(items, ident) {
- var seen = {};
- if (ident) {
- return items.filter(function (item) {
- if (seen[item[ident]]) return false;
- seen[item[ident]] = true;
- return true;
- });
- } else {
- return items.filter(function (item) {
- if (seen[item]) return false;
- seen[item] = true;
- return true;
- });
- }
- },
- set: function set() {
- var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
- var ret = {};
- for (var i = 0; i < args.length; i++) {
- ret[args[i]] = 0;
- }
- return ret;
- },
- STACK_ALIGN: 8,
- getAlignSize: function (type, size, vararg) {
- // we align i64s and doubles on 64-bit boundaries, unlike x86
- if (!vararg && (type == 'i64' || type == 'double')) return 8;
- if (!type) return Math.min(size, 8); // align structures internally to 64 bits
- return Math.min(size || (type ? Runtime.getNativeFieldSize(type) : 0), Runtime.QUANTUM_SIZE);
- },
- calculateStructAlignment: function calculateStructAlignment(type) {
- type.flatSize = 0;
- type.alignSize = 0;
- var diffs = [];
- var prev = -1;
- var index = 0;
- type.flatIndexes = type.fields.map(function (field) {
- index++;
- var size, alignSize;
- if (Runtime.isNumberType(field) || Runtime.isPointerType(field)) {
- size = Runtime.getNativeTypeSize(field); // pack char; char; in structs, also char[X]s.
- alignSize = Runtime.getAlignSize(field, size);
- } else if (Runtime.isStructType(field)) {
- if (field[1] === '0') {
- // this is [0 x something]. When inside another structure like here, it must be at the end,
- // and it adds no size
- // XXX this happens in java-nbody for example... assert(index === type.fields.length, 'zero-length in the middle!');
- size = 0;
- if (Types.types[field]) {
- alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
- } else {
- alignSize = type.alignSize || QUANTUM_SIZE;
- }
- } else {
- size = Types.types[field].flatSize;
- alignSize = Runtime.getAlignSize(null, Types.types[field].alignSize);
- }
- } else if (field[0] == 'b') {
- // bN, large number field, like a [N x i8]
- size = field.substr(1) | 0;
- alignSize = 1;
- } else if (field[0] === '<') {
- // vector type
- size = alignSize = Types.types[field].flatSize; // fully aligned
- } else if (field[0] === 'i') {
- // illegal integer field, that could not be legalized because it is an internal structure field
- // it is ok to have such fields, if we just use them as markers of field size and nothing more complex
- size = alignSize = parseInt(field.substr(1)) / 8;
- assert(size % 1 === 0, 'cannot handle non-byte-size field ' + field);
- } else {
- assert(false, 'invalid type for calculateStructAlignment');
- }
- if (type.packed) alignSize = 1;
- type.alignSize = Math.max(type.alignSize, alignSize);
- var curr = Runtime.alignMemory(type.flatSize, alignSize); // if necessary, place this on aligned memory
- type.flatSize = curr + size;
- if (prev >= 0) {
- diffs.push(curr - prev);
- }
- prev = curr;
- return curr;
- });
- if (type.name_ && type.name_[0] === '[') {
- // arrays have 2 elements, so we get the proper difference. then we scale here. that way we avoid
- // allocating a potentially huge array for [999999 x i8] etc.
- type.flatSize = parseInt(type.name_.substr(1)) * type.flatSize / 2;
- }
- type.flatSize = Runtime.alignMemory(type.flatSize, type.alignSize);
- if (diffs.length == 0) {
- type.flatFactor = type.flatSize;
- } else if (Runtime.dedup(diffs).length == 1) {
- type.flatFactor = diffs[0];
- }
- type.needsFlattening = (type.flatFactor != 1);
- return type.flatIndexes;
- },
- generateStructInfo: function (struct, typeName, offset) {
- var type, alignment;
- if (typeName) {
- offset = offset || 0;
- type = (typeof Types === 'undefined' ? Runtime.typeInfo : Types.types)[typeName];
- if (!type) return null;
- if (type.fields.length != struct.length) {
- printErr('Number of named fields must match the type for ' + typeName + ': possibly duplicate struct names. Cannot return structInfo');
- return null;
- }
- alignment = type.flatIndexes;
- } else {
- var type = {
- fields: struct.map(function (item) {
- return item[0]
- })
- };
- alignment = Runtime.calculateStructAlignment(type);
- }
- var ret = {
- __size__: type.flatSize
- };
- if (typeName) {
- struct.forEach(function (item, i) {
- if (typeof item === 'string') {
- ret[item] = alignment[i] + offset;
- } else {
- // embedded struct
- var key;
- for (var k in item) key = k;
- ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], alignment[i]);
- }
- });
- } else {
- struct.forEach(function (item, i) {
- ret[item[1]] = alignment[i];
- });
- }
- return ret;
- },
- dynCall: function (sig, ptr, args) {
- if (args && args.length) {
- if (!args.splice) args = Array.prototype.slice.call(args);
- args.splice(0, 0, ptr);
- return Module['dynCall_' + sig].apply(null, args);
- } else {
- return Module['dynCall_' + sig].call(null, ptr);
- }
- },
- functionPointers: [],
- addFunction: function (func) {
- for (var i = 0; i < Runtime.functionPointers.length; i++) {
- if (!Runtime.functionPointers[i]) {
- Runtime.functionPointers[i] = func;
- return 2 * (1 + i);
- }
- }
- throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
- },
- removeFunction: function (index) {
- Runtime.functionPointers[(index - 2) / 2] = null;
- },
- getAsmConst: function (code, numArgs) {
- // code is a constant string on the heap, so we can cache these
- if (!Runtime.asmConstCache) Runtime.asmConstCache = {};
- var func = Runtime.asmConstCache[code];
- if (func) return func;
- var args = [];
- for (var i = 0; i < numArgs; i++) {
- args.push(String.fromCharCode(36) + i); // $0, $1 etc
- }
- code = Pointer_stringify(code);
- if (code[0] === '"') {
- // tolerate EM_ASM("..code..") even though EM_ASM(..code..) is correct
- if (code.indexOf('"', 1) === code.length - 1) {
- code = code.substr(1, code.length - 2);
- } else {
- // something invalid happened, e.g. EM_ASM("..code($0)..", input)
- abort('invalid EM_ASM input |' + code + '|. Please use EM_ASM(..code..) (no quotes) or EM_ASM({ ..code($0).. }, input) (to input values)');
- }
- }
- return Runtime.asmConstCache[code] = eval('(function(' + args.join(',') + '){ ' + code + ' })'); // new Function does not allow upvars in node
- },
- warnOnce: function (text) {
- if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
- if (!Runtime.warnOnce.shown[text]) {
- Runtime.warnOnce.shown[text] = 1;
- Module.printErr(text);
- }
- },
- funcWrappers: {},
- getFuncWrapper: function (func, sig) {
- assert(sig);
- if (!Runtime.funcWrappers[func]) {
- Runtime.funcWrappers[func] = function dynCall_wrapper() {
- return Runtime.dynCall(sig, func, arguments);
- };
- }
- return Runtime.funcWrappers[func];
- },
- UTF8Processor: function () {
- var buffer = [];
- var needed = 0;
- this.processCChar = function (code) {
- code = code & 0xFF;
- if (buffer.length == 0) {
- if ((code & 0x80) == 0x00) { // 0xxxxxxx
- return String.fromCharCode(code);
- }
- buffer.push(code);
- if ((code & 0xE0) == 0xC0) { // 110xxxxx
- needed = 1;
- } else if ((code & 0xF0) == 0xE0) { // 1110xxxx
- needed = 2;
- } else { // 11110xxx
- needed = 3;
- }
- return '';
- }
- if (needed) {
- buffer.push(code);
- needed--;
- if (needed > 0) return '';
- }
- var c1 = buffer[0];
- var c2 = buffer[1];
- var c3 = buffer[2];
- var c4 = buffer[3];
- var ret;
- if (buffer.length == 2) {
- ret = String.fromCharCode(((c1 & 0x1F) << 6) | (c2 & 0x3F));
- } else if (buffer.length == 3) {
- ret = String.fromCharCode(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
- } else {
- // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
- var codePoint = ((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) |
- ((c3 & 0x3F) << 6) | (c4 & 0x3F);
- ret = String.fromCharCode(
- Math.floor((codePoint - 0x10000) / 0x400) + 0xD800, (codePoint - 0x10000) % 0x400 + 0xDC00);
- }
- buffer.length = 0;
- return ret;
- }
- this.processJSString = function processJSString(string) {
- string = unescape(encodeURIComponent(string));
- var ret = [];
- for (var i = 0; i < string.length; i++) {
- ret.push(string.charCodeAt(i));
- }
- return ret;
- }
- },
- getCompilerSetting: function (name) {
- throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work';
- },
- stackAlloc: function (size) {
- var ret = STACKTOP;
- STACKTOP = (STACKTOP + size) | 0;
- STACKTOP = (((STACKTOP) + 7) & -8);
- return ret;
- },
- staticAlloc: function (size) {
- var ret = STATICTOP;
- STATICTOP = (STATICTOP + size) | 0;
- STATICTOP = (((STATICTOP) + 7) & -8);
- return ret;
- },
- dynamicAlloc: function (size) {
- var ret = DYNAMICTOP;
- DYNAMICTOP = (DYNAMICTOP + size) | 0;
- DYNAMICTOP = (((DYNAMICTOP) + 7) & -8);
- if (DYNAMICTOP >= TOTAL_MEMORY) enlargeMemory();;
- return ret;
- },
- alignMemory: function (size, quantum) {
- var ret = size = Math.ceil((size) / (quantum ? quantum : 8)) * (quantum ? quantum : 8);
- return ret;
- },
- makeBigInt: function (low, high, unsigned) {
- var ret = (unsigned ? ((+((low >>> 0))) + ((+((high >>> 0))) * (+4294967296))) : ((+((low >>> 0))) + ((+((high | 0))) * (+4294967296))));
- return ret;
- },
- GLOBAL_BASE: 8,
- QUANTUM_SIZE: 4,
- __dummy__: 0
- }
- Module['Runtime'] = Runtime;
- //========================================
- // Runtime essentials
- //========================================
- var __THREW__ = 0; // Used in checking for thrown exceptions.
- var ABORT = false; // whether we are quitting the application. no code should run after this. set in exit() and abort()
- var EXITSTATUS = 0;
- var undef = 0;
- // tempInt is used for 32-bit signed values or smaller. tempBigInt is used
- // for 32-bit unsigned values or more than 32 bits. TODO: audit all uses of tempInt
- var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI, tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD, tempDouble, tempFloat;
- var tempI64, tempI64b;
- var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRet7, tempRet8, tempRet9;
- function assert(condition, text) {
- if (!condition) {
- abort('Assertion failed: ' + text);
- }
- }
- var globalScope = this;
- // C calling interface. A convenient way to call C functions (in C files, or
- // defined with extern "C").
- //
- // Note: LLVM optimizations can inline and remove functions, after which you will not be
- // able to call them. Closure can also do so. To avoid that, add your function to
- // the exports using something like
- //
- // -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
- //
- // @param ident The name of the C function (note that C++ functions will be name-mangled - use extern "C")
- // @param returnType The return type of the function, one of the JS types 'number', 'string' or 'array' (use 'number' for any C pointer, and
- // 'array' for JavaScript arrays and typed arrays; note that arrays are 8-bit).
- // @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,
- // except that 'array' is not possible (there is no way for us to know the length of the array)
- // @param args An array of the arguments to the function, as native JS values (as in returnType)
- // Note that string arguments will be stored on the stack (the JS string will become a C string on the stack).
- // @return The return value, as a native JS value (as in returnType)
- function ccall(ident, returnType, argTypes, args) {
- return ccallFunc(getCFunc(ident), returnType, argTypes, args);
- }
- Module["ccall"] = ccall;
- // Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
- function getCFunc(ident) {
- try {
- var func = Module['_' + ident]; // closure exported function
- if (!func) func = eval('_' + ident); // explicit lookup
- } catch (e) {}
- assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
- return func;
- }
- // Internal function that does a C call using a function, not an identifier
- function ccallFunc(func, returnType, argTypes, args) {
- var stack = 0;
- function toC(value, type) {
- if (type == 'string') {
- if (value === null || value === undefined || value === 0) return 0; // null string
- value = intArrayFromString(value);
- type = 'array';
- }
- if (type == 'array') {
- if (!stack) stack = Runtime.stackSave();
- var ret = Runtime.stackAlloc(value.length);
- writeArrayToMemory(value, ret);
- return ret;
- }
- return value;
- }
- function fromC(value, type) {
- if (type == 'string') {
- return Pointer_stringify(value);
- }
- assert(type != 'array');
- return value;
- }
- var i = 0;
- var cArgs = args ? args.map(function (arg) {
- return toC(arg, argTypes[i++]);
- }) : [];
- var ret = fromC(func.apply(null, cArgs), returnType);
- if (stack) Runtime.stackRestore(stack);
- return ret;
- }
- // Returns a native JS wrapper for a C function. This is similar to ccall, but
- // returns a function you can call repeatedly in a normal way. For example:
- //
- // var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
- // alert(my_function(5, 22));
- // alert(my_function(99, 12));
- //
- function cwrap(ident, returnType, argTypes) {
- var func = getCFunc(ident);
- return function () {
- return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(arguments));
- }
- }
- Module["cwrap"] = cwrap;
- // Sets a value in memory in a dynamic way at run-time. Uses the
- // type data. This is the same as makeSetValue, except that
- // makeSetValue is done at compile-time and generates the needed
- // code then, whereas this function picks the right code at
- // run-time.
- // Note that setValue and getValue only do *aligned* writes and reads!
- // Note that ccall uses JS types as for defining types, while setValue and
- // getValue need LLVM types ('i8', 'i32') - this is a lower-level operation
- function setValue(ptr, value, type, noSafe) {
- type = type || 'i8';
- if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
- switch (type) {
- case 'i1':
- HEAP8[(ptr)] = value;
- break;
- case 'i8':
- HEAP8[(ptr)] = value;
- break;
- case 'i16':
- HEAP16[((ptr) >> 1)] = value;
- break;
- case 'i32':
- HEAP32[((ptr) >> 2)] = value;
- break;
- case 'i64':
- (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]);
- break;
- case 'float':
- HEAPF32[((ptr) >> 2)] = value;
- break;
- case 'double':
- HEAPF64[((ptr) >> 3)] = value;
- break;
- default:
- abort('invalid type for setValue: ' + type);
- }
- }
- Module['setValue'] = setValue;
- // Parallel to setValue.
- function getValue(ptr, type, noSafe) {
- type = type || 'i8';
- if (type.charAt(type.length - 1) === '*') type = 'i32'; // pointers are 32-bit
- switch (type) {
- case 'i1':
- return HEAP8[(ptr)];
- case 'i8':
- return HEAP8[(ptr)];
- case 'i16':
- return HEAP16[((ptr) >> 1)];
- case 'i32':
- return HEAP32[((ptr) >> 2)];
- case 'i64':
- return HEAP32[((ptr) >> 2)];
- case 'float':
- return HEAPF32[((ptr) >> 2)];
- case 'double':
- return HEAPF64[((ptr) >> 3)];
- default:
- abort('invalid type for setValue: ' + type);
- }
- return null;
- }
- Module['getValue'] = getValue;
- var ALLOC_NORMAL = 0; // Tries to use _malloc()
- var ALLOC_STACK = 1; // Lives for the duration of the current function call
- var ALLOC_STATIC = 2; // Cannot be freed
- var ALLOC_DYNAMIC = 3; // Cannot be freed except through sbrk
- var ALLOC_NONE = 4; // Do not allocate
- Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
- Module['ALLOC_STACK'] = ALLOC_STACK;
- Module['ALLOC_STATIC'] = ALLOC_STATIC;
- Module['ALLOC_DYNAMIC'] = ALLOC_DYNAMIC;
- Module['ALLOC_NONE'] = ALLOC_NONE;
- // allocate(): This is for internal use. You can use it yourself as well, but the interface
- // is a little tricky (see docs right below). The reason is that it is optimized
- // for multiple syntaxes to save space in generated code. So you should
- // normally not use allocate(), and instead allocate memory using _malloc(),
- // initialize it with setValue(), and so forth.
- // @slab: An array of data, or a number. If a number, then the size of the block to allocate,
- // in *bytes* (note that this is sometimes confusing: the next parameter does not
- // affect this!)
- // @types: Either an array of types, one for each byte (or 0 if no type at that position),
- // or a single type which is used for the entire block. This only matters if there
- // is initial data - if @slab is a number, then this does not matter at all and is
- // ignored.
- // @allocator: How to allocate memory, see ALLOC_*
- function allocate(slab, types, allocator, ptr) {
- var zeroinit, size;
- if (typeof slab === 'number') {
- zeroinit = true;
- size = slab;
- } else {
- zeroinit = false;
- size = slab.length;
- }
- var singleType = typeof types === 'string' ? types : null;
- var ret;
- if (allocator == ALLOC_NONE) {
- ret = ptr;
- } else {
- ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc, Runtime.dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
- }
- if (zeroinit) {
- var ptr = ret,
- stop;
- assert((ret & 3) == 0);
- stop = ret + (size & ~3);
- for (; ptr < stop; ptr += 4) {
- HEAP32[((ptr) >> 2)] = 0;
- }
- stop = ret + size;
- while (ptr < stop) {
- HEAP8[((ptr++) | 0)] = 0;
- }
- return ret;
- }
- if (singleType === 'i8') {
- if (slab.subarray || slab.slice) {
- HEAPU8.set(slab, ret);
- } else {
- HEAPU8.set(new Uint8Array(slab), ret);
- }
- return ret;
- }
- var i = 0,
- type, typeSize, previousType;
- while (i < size) {
- var curr = slab[i];
- if (typeof curr === 'function') {
- curr = Runtime.getFunctionIndex(curr);
- }
- type = singleType || types[i];
- if (type === 0) {
- i++;
- continue;
- }
- if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
- setValue(ret + i, curr, type);
- // no need to look up size unless type changes, so cache it
- if (previousType !== type) {
- typeSize = Runtime.getNativeTypeSize(type);
- previousType = type;
- }
- i += typeSize;
- }
- return ret;
- }
- Module['allocate'] = allocate;
- function Pointer_stringify(ptr, /* optional */ length) {
- // TODO: use TextDecoder
- // Find the length, and check for UTF while doing so
- var hasUtf = false;
- var t;
- var i = 0;
- while (1) {
- t = HEAPU8[(((ptr) + (i)) | 0)];
- if (t >= 128) hasUtf = true;
- else if (t == 0 && !length) break;
- i++;
- if (length && i == length) break;
- }
- if (!length) length = i;
- var ret = '';
- if (!hasUtf) {
- var MAX_CHUNK = 1024; // split up into chunks, because .apply on a huge string can overflow the stack
- var curr;
- while (length > 0) {
- curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK)));
- ret = ret ? ret + curr : curr;
- ptr += MAX_CHUNK;
- length -= MAX_CHUNK;
- }
- return ret;
- }
- var utf8 = new Runtime.UTF8Processor();
- for (i = 0; i < length; i++) {
- t = HEAPU8[(((ptr) + (i)) | 0)];
- ret += utf8.processCChar(t);
- }
- return ret;
- }
- Module['Pointer_stringify'] = Pointer_stringify;
- // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
- // a copy of that string as a Javascript String object.
- function UTF16ToString(ptr) {
- var i = 0;
- var str = '';
- while (1) {
- var codeUnit = HEAP16[(((ptr) + (i * 2)) >> 1)];
- if (codeUnit == 0)
- return str;
- ++i;
- // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
- str += String.fromCharCode(codeUnit);
- }
- }
- Module['UTF16ToString'] = UTF16ToString;
- // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
- // null-terminated and encoded in UTF16LE form. The copy will require at most (str.length*2+1)*2 bytes of space in the HEAP.
- function stringToUTF16(str, outPtr) {
- for (var i = 0; i < str.length; ++i) {
- // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
- var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
- HEAP16[(((outPtr) + (i * 2)) >> 1)] = codeUnit;
- }
- // Null-terminate the pointer to the HEAP.
- HEAP16[(((outPtr) + (str.length * 2)) >> 1)] = 0;
- }
- Module['stringToUTF16'] = stringToUTF16;
- // Given a pointer 'ptr' to a null-terminated UTF32LE-encoded string in the emscripten HEAP, returns
- // a copy of that string as a Javascript String object.
- function UTF32ToString(ptr) {
- var i = 0;
- var str = '';
- while (1) {
- var utf32 = HEAP32[(((ptr) + (i * 4)) >> 2)];
- if (utf32 == 0)
- return str;
- ++i;
- // 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.
- if (utf32 >= 0x10000) {
- var ch = utf32 - 0x10000;
- str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
- } else {
- str += String.fromCharCode(utf32);
- }
- }
- }
- Module['UTF32ToString'] = UTF32ToString;
- // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
- // null-terminated and encoded in UTF32LE form. The copy will require at most (str.length+1)*4 bytes of space in the HEAP,
- // 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.
- function stringToUTF32(str, outPtr) {
- var iChar = 0;
- for (var iCodeUnit = 0; iCodeUnit < str.length; ++iCodeUnit) {
- // 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.
- var codeUnit = str.charCodeAt(iCodeUnit); // possibly a lead surrogate
- if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
- var trailSurrogate = str.charCodeAt(++iCodeUnit);
- codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
- }
- HEAP32[(((outPtr) + (iChar * 4)) >> 2)] = codeUnit;
- ++iChar;
- }
- // Null-terminate the pointer to the HEAP.
- HEAP32[(((outPtr) + (iChar * 4)) >> 2)] = 0;
- }
- Module['stringToUTF32'] = stringToUTF32;
- function demangle(func) {
- var i = 3;
- // params, etc.
- var basicTypes = {
- 'v': 'void',
- 'b': 'bool',
- 'c': 'char',
- 's': 'short',
- 'i': 'int',
- 'l': 'long',
- 'f': 'float',
- 'd': 'double',
- 'w': 'wchar_t',
- 'a': 'signed char',
- 'h': 'unsigned char',
- 't': 'unsigned short',
- 'j': 'unsigned int',
- 'm': 'unsigned long',
- 'x': 'long long',
- 'y': 'unsigned long long',
- 'z': '...'
- };
- var subs = [];
- var first = true;
- function dump(x) {
- //return;
- if (x) Module.print(x);
- Module.print(func);
- var pre = '';
- for (var a = 0; a < i; a++) pre += ' ';
- Module.print(pre + '^');
- }
- function parseNested() {
- i++;
- if (func[i] === 'K') i++; // ignore const
- var parts = [];
- while (func[i] !== 'E') {
- if (func[i] === 'S') { // substitution
- i++;
- var next = func.indexOf('_', i);
- var num = func.substring(i, next) || 0;
- parts.push(subs[num] || '?');
- i = next + 1;
- continue;
- }
- if (func[i] === 'C') { // constructor
- parts.push(parts[parts.length - 1]);
- i += 2;
- continue;
- }
- var size = parseInt(func.substr(i));
- var pre = size.toString().length;
- if (!size || !pre) {
- i--;
- break;
- } // counter i++ below us
- var curr = func.substr(i + pre, size);
- parts.push(curr);
- subs.push(curr);
- i += pre + size;
- }
- i++; // skip E
- return parts;
- }
- function parse(rawList, limit, allowVoid) { // main parser
- limit = limit || Infinity;
- var ret = '',
- list = [];
- function flushList() {
- return '(' + list.join(', ') + ')';
- }
- var name;
- if (func[i] === 'N') {
- // namespaced N-E
- name = parseNested().join('::');
- limit--;
- if (limit === 0) return rawList ? [name] : name;
- } else {
- // not namespaced
- if (func[i] === 'K' || (first && func[i] === 'L')) i++; // ignore const and first 'L'
- var size = parseInt(func.substr(i));
- if (size) {
- var pre = size.toString().length;
- name = func.substr(i + pre, size);
- i += pre + size;
- }
- }
- first = false;
- if (func[i] === 'I') {
- i++;
- var iList = parse(true);
- var iRet = parse(true, 1, true);
- ret += iRet[0] + ' ' + name + '<' + iList.join(', ') + '>';
- } else {
- ret = name;
- }
- paramLoop: while (i < func.length && limit-- > 0) {
- //dump('paramLoop');
- var c = func[i++];
- if (c in basicTypes) {
- list.push(basicTypes[c]);
- } else {
- switch (c) {
- case 'P':
- list.push(parse(true, 1, true)[0] + '*');
- break; // pointer
- case 'R':
- list.push(parse(true, 1, true)[0] + '&');
- break; // reference
- case 'L':
- { // literal
- i++; // skip basic type
- var end = func.indexOf('E', i);
- var size = end - i;
- list.push(func.substr(i, size));
- i += size + 2; // size + 'EE'
- break;
- }
- case 'A':
- { // array
- var size = parseInt(func.substr(i));
- i += size.toString().length;
- if (func[i] !== '_') throw '?';
- i++; // skip _
- list.push(parse(true, 1, true)[0] + ' [' + size + ']');
- break;
- }
- case 'E':
- break paramLoop;
- default:
- ret += '?' + c;
- break paramLoop;
- }
- }
- }
- if (!allowVoid && list.length === 1 && list[0] === 'void') list = []; // avoid (void)
- return rawList ? list : ret + flushList();
- }
- try {
- // Special-case the entry point, since its name differs from other name mangling.
- if (func == 'Object._main' || func == '_main') {
- return 'main()';
- }
- if (typeof func === 'number') func = Pointer_stringify(func);
- if (func[0] !== '_') return func;
- if (func[1] !== '_') return func; // C function
- if (func[2] !== 'Z') return func;
- switch (func[3]) {
- case 'n':
- return 'operator new()';
- case 'd':
- return 'operator delete()';
- }
- return parse();
- } catch (e) {
- return func;
- }
- }
- function demangleAll(text) {
- return text.replace(/__Z[\w\d_]+/g, function (x) {
- var y = demangle(x);
- return x === y ? x : (x + ' [' + y + ']')
- });
- }
- function stackTrace() {
- var stack = new Error().stack;
- return stack ? demangleAll(stack) : '(no stack trace available)'; // Stack trace is not available at least on IE10 and Safari 6.
- }
- // Memory management
- var PAGE_SIZE = 4096;
- function alignMemoryPage(x) {
- return (x + 4095) & -4096;
- }
- var HEAP;
- var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
- var STATIC_BASE = 0,
- STATICTOP = 0,
- staticSealed = false; // static area
- var STACK_BASE = 0,
- STACKTOP = 0,
- STACK_MAX = 0; // stack area
- var DYNAMIC_BASE = 0,
- DYNAMICTOP = 0; // dynamic area handled by sbrk
- function enlargeMemory() {
- 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.');
- }
- var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
- var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216;
- var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
- var totalMemory = 4096;
- while (totalMemory < TOTAL_MEMORY || totalMemory < 2 * TOTAL_STACK) {
- if (totalMemory < 16 * 1024 * 1024) {
- totalMemory *= 2;
- } else {
- totalMemory += 16 * 1024 * 1024
- }
- }
- if (totalMemory !== TOTAL_MEMORY) {
- Module.printErr('increasing TOTAL_MEMORY to ' + totalMemory + ' to be more reasonable');
- TOTAL_MEMORY = totalMemory;
- }
- // Initialize the runtime's memory
- // check for full engine support (use string 'subarray' to avoid closure compiler confusion)
- assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
- 'JS engine does not provide full typed array support');
- var buffer = new ArrayBuffer(TOTAL_MEMORY);
- HEAP8 = new Int8Array(buffer);
- HEAP16 = new Int16Array(buffer);
- HEAP32 = new Int32Array(buffer);
- HEAPU8 = new Uint8Array(buffer);
- HEAPU16 = new Uint16Array(buffer);
- HEAPU32 = new Uint32Array(buffer);
- HEAPF32 = new Float32Array(buffer);
- HEAPF64 = new Float64Array(buffer);
- // Endianness check (note: assumes compiler arch was little-endian)
- HEAP32[0] = 255;
- assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a little-endian system');
- Module['HEAP'] = HEAP;
- Module['HEAP8'] = HEAP8;
- Module['HEAP16'] = HEAP16;
- Module['HEAP32'] = HEAP32;
- Module['HEAPU8'] = HEAPU8;
- Module['HEAPU16'] = HEAPU16;
- Module['HEAPU32'] = HEAPU32;
- Module['HEAPF32'] = HEAPF32;
- Module['HEAPF64'] = HEAPF64;
- function callRuntimeCallbacks(callbacks) {
- while (callbacks.length > 0) {
- var callback = callbacks.shift();
- if (typeof callback == 'function') {
- callback();
- continue;
- }
- var func = callback.func;
- if (typeof func === 'number') {
- if (callback.arg === undefined) {
- Runtime.dynCall('v', func);
- } else {
- Runtime.dynCall('vi', func, [callback.arg]);
- }
- } else {
- func(callback.arg === undefined ? null : callback.arg);
- }
- }
- }
- var __ATPRERUN__ = []; // functions called before the runtime is initialized
- var __ATINIT__ = []; // functions called during startup
- var __ATMAIN__ = []; // functions called when main() is to be run
- var __ATEXIT__ = []; // functions called during shutdown
- var __ATPOSTRUN__ = []; // functions called after the runtime has exited
- var runtimeInitialized = false;
- function preRun() {
- // compatibility - merge in anything from Module['preRun'] at this time
- if (Module['preRun']) {
- if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
- while (Module['preRun'].length) {
- addOnPreRun(Module['preRun'].shift());
- }
- }
- callRuntimeCallbacks(__ATPRERUN__);
- }
- function ensureInitRuntime() {
- if (runtimeInitialized) return;
- runtimeInitialized = true;
- callRuntimeCallbacks(__ATINIT__);
- }
- function preMain() {
- callRuntimeCallbacks(__ATMAIN__);
- }
- function exitRuntime() {
- callRuntimeCallbacks(__ATEXIT__);
- }
- function postRun() {
- // compatibility - merge in anything from Module['postRun'] at this time
- if (Module['postRun']) {
- if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
- while (Module['postRun'].length) {
- addOnPostRun(Module['postRun'].shift());
- }
- }
- callRuntimeCallbacks(__ATPOSTRUN__);
- }
- function addOnPreRun(cb) {
- __ATPRERUN__.unshift(cb);
- }
- Module['addOnPreRun'] = Module.addOnPreRun = addOnPreRun;
- function addOnInit(cb) {
- __ATINIT__.unshift(cb);
- }
- Module['addOnInit'] = Module.addOnInit = addOnInit;
- function addOnPreMain(cb) {
- __ATMAIN__.unshift(cb);
- }
- Module['addOnPreMain'] = Module.addOnPreMain = addOnPreMain;
- function addOnExit(cb) {
- __ATEXIT__.unshift(cb);
- }
- Module['addOnExit'] = Module.addOnExit = addOnExit;
- function addOnPostRun(cb) {
- __ATPOSTRUN__.unshift(cb);
- }
- Module['addOnPostRun'] = Module.addOnPostRun = addOnPostRun;
- // Tools
- // This processes a JS string into a C-line array of numbers, 0-terminated.
- // For LLVM-originating strings, see parser.js:parseLLVMString function
- function intArrayFromString(stringy, dontAddNull, length /* optional */ ) {
- var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
- if (length) {
- ret.length = length;
- }
- if (!dontAddNull) {
- ret.push(0);
- }
- return ret;
- }
- Module['intArrayFromString'] = intArrayFromString;
- function intArrayToString(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- var chr = array[i];
- if (chr > 0xFF) {
- chr &= 0xFF;
- }
- ret.push(String.fromCharCode(chr));
- }
- return ret.join('');
- }
- Module['intArrayToString'] = intArrayToString;
- // Write a Javascript array to somewhere in the heap
- function writeStringToMemory(string, buffer, dontAddNull) {
- var array = intArrayFromString(string, dontAddNull);
- var i = 0;
- while (i < array.length) {
- var chr = array[i];
- HEAP8[(((buffer) + (i)) | 0)] = chr;
- i = i + 1;
- }
- }
- Module['writeStringToMemory'] = writeStringToMemory;
- function writeArrayToMemory(array, buffer) {
- for (var i = 0; i < array.length; i++) {
- HEAP8[(((buffer) + (i)) | 0)] = array[i];
- }
- }
- Module['writeArrayToMemory'] = writeArrayToMemory;
- function writeAsciiToMemory(str, buffer, dontAddNull) {
- for (var i = 0; i < str.length; i++) {
- HEAP8[(((buffer) + (i)) | 0)] = str.charCodeAt(i);
- }
- if (!dontAddNull) HEAP8[(((buffer) + (str.length)) | 0)] = 0;
- }
- Module['writeAsciiToMemory'] = writeAsciiToMemory;
- function unSign(value, bits, ignore) {
- if (value >= 0) {
- return value;
- }
- 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
- : Math.pow(2, bits) + value;
- }
- function reSign(value, bits, ignore) {
- if (value <= 0) {
- return value;
- }
- var half = bits <= 32 ? Math.abs(1 << (bits - 1)) // abs is needed if bits == 32
- : Math.pow(2, bits - 1);
- 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
- // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
- // TODO: In i64 mode 1, resign the two parts separately and safely
- value = -2 * half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
- }
- return value;
- }
- // check for imul support, and also for correctness ( https://bugs.webkit.org/show_bug.cgi?id=126345 )
- if (!Math['imul'] || Math['imul'](0xffffffff, 5) !== -5) Math['imul'] = function imul(a, b) {
- var ah = a >>> 16;
- var al = a & 0xffff;
- var bh = b >>> 16;
- var bl = b & 0xffff;
- return (al * bl + ((ah * bl + al * bh) << 16)) | 0;
- };
- Math.imul = Math['imul'];
- var Math_abs = Math.abs;
- var Math_cos = Math.cos;
- var Math_sin = Math.sin;
- var Math_tan = Math.tan;
- var Math_acos = Math.acos;
- var Math_asin = Math.asin;
- var Math_atan = Math.atan;
- var Math_atan2 = Math.atan2;
- var Math_exp = Math.exp;
- var Math_log = Math.log;
- var Math_sqrt = Math.sqrt;
- var Math_ceil = Math.ceil;
- var Math_floor = Math.floor;
- var Math_pow = Math.pow;
- var Math_imul = Math.imul;
- var Math_fround = Math.fround;
- var Math_min = Math.min;
- // A counter of dependencies for calling run(). If we need to
- // do asynchronous work before running, increment this and
- // decrement it. Incrementing must happen in a place like
- // PRE_RUN_ADDITIONS (used by emcc to add file preloading).
- // Note that you can add dependencies in preRun, even though
- // it happens right before run - run will be postponed until
- // the dependencies are met.
- var runDependencies = 0;
- var runDependencyWatcher = null;
- var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
- function addRunDependency(id) {
- runDependencies++;
- if (Module['monitorRunDependencies']) {
- Module['monitorRunDependencies'](runDependencies);
- }
- }
- Module['addRunDependency'] = addRunDependency;
- function removeRunDependency(id) {
- runDependencies--;
- if (Module['monitorRunDependencies']) {
- Module['monitorRunDependencies'](runDependencies);
- }
- if (runDependencies == 0) {
- if (runDependencyWatcher !== null) {
- clearInterval(runDependencyWatcher);
- runDependencyWatcher = null;
- }
- if (dependenciesFulfilled) {
- var callback = dependenciesFulfilled;
- dependenciesFulfilled = null;
- callback(); // can add another dependenciesFulfilled
- }
- }
- }
- Module['removeRunDependency'] = removeRunDependency;
- Module["preloadedImages"] = {}; // maps url to image data
- Module["preloadedAudios"] = {}; // maps url to audio data
- var memoryInitializer = null;
- // === Body ===
- STATIC_BASE = 8;
- STATICTOP = STATIC_BASE + Runtime.alignMemory(291);
- /* global initializers */
- __ATINIT__.push();
- /* memory initializer */
- 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);
- var tempDoublePtr = Runtime.alignMemory(allocate(12, "i8", ALLOC_STATIC), 8);
- assert(tempDoublePtr % 8 == 0);
- function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
- HEAP8[tempDoublePtr] = HEAP8[ptr];
- HEAP8[tempDoublePtr + 1] = HEAP8[ptr + 1];
- HEAP8[tempDoublePtr + 2] = HEAP8[ptr + 2];
- HEAP8[tempDoublePtr + 3] = HEAP8[ptr + 3];
- }
- function copyTempDouble(ptr) {
- HEAP8[tempDoublePtr] = HEAP8[ptr];
- HEAP8[tempDoublePtr + 1] = HEAP8[ptr + 1];
- HEAP8[tempDoublePtr + 2] = HEAP8[ptr + 2];
- HEAP8[tempDoublePtr + 3] = HEAP8[ptr + 3];
- HEAP8[tempDoublePtr + 4] = HEAP8[ptr + 4];
- HEAP8[tempDoublePtr + 5] = HEAP8[ptr + 5];
- HEAP8[tempDoublePtr + 6] = HEAP8[ptr + 6];
- HEAP8[tempDoublePtr + 7] = HEAP8[ptr + 7];
- }
- function _llvm_lifetime_end() {}
- function _malloc(bytes) {
- /* Over-allocate to make sure it is byte-aligned by 8.
- * This will leak memory, but this is only the dummy
- * implementation (replaced by dlmalloc normally) so
- * not an issue.
- */
- var ptr = Runtime.dynamicAlloc(bytes + 8);
- return (ptr + 8) & 0xFFFFFFF8;
- }
- Module["_malloc"] = _malloc;
- Module["_memset"] = _memset;
- function _free() {}
- Module["_free"] = _free;
- function _llvm_lifetime_start() {}
- var ERRNO_CODES = {
- EPERM: 1,
- ENOENT: 2,
- ESRCH: 3,
- EINTR: 4,
- EIO: 5,
- ENXIO: 6,
- E2BIG: 7,
- ENOEXEC: 8,
- EBADF: 9,
- ECHILD: 10,
- EAGAIN: 11,
- EWOULDBLOCK: 11,
- ENOMEM: 12,
- EACCES: 13,
- EFAULT: 14,
- ENOTBLK: 15,
- EBUSY: 16,
- EEXIST: 17,
- EXDEV: 18,
- ENODEV: 19,
- ENOTDIR: 20,
- EISDIR: 21,
- EINVAL: 22,
- ENFILE: 23,
- EMFILE: 24,
- ENOTTY: 25,
- ETXTBSY: 26,
- EFBIG: 27,
- ENOSPC: 28,
- ESPIPE: 29,
- EROFS: 30,
- EMLINK: 31,
- EPIPE: 32,
- EDOM: 33,
- ERANGE: 34,
- ENOMSG: 42,
- EIDRM: 43,
- ECHRNG: 44,
- EL2NSYNC: 45,
- EL3HLT: 46,
- EL3RST: 47,
- ELNRNG: 48,
- EUNATCH: 49,
- ENOCSI: 50,
- EL2HLT: 51,
- EDEADLK: 35,
- ENOLCK: 37,
- EBADE: 52,
- EBADR: 53,
- EXFULL: 54,
- ENOANO: 55,
- EBADRQC: 56,
- EBADSLT: 57,
- EDEADLOCK: 35,
- EBFONT: 59,
- ENOSTR: 60,
- ENODATA: 61,
- ETIME: 62,
- ENOSR: 63,
- ENONET: 64,
- ENOPKG: 65,
- EREMOTE: 66,
- ENOLINK: 67,
- EADV: 68,
- ESRMNT: 69,
- ECOMM: 70,
- EPROTO: 71,
- EMULTIHOP: 72,
- EDOTDOT: 73,
- EBADMSG: 74,
- ENOTUNIQ: 76,
- EBADFD: 77,
- EREMCHG: 78,
- ELIBACC: 79,
- ELIBBAD: 80,
- ELIBSCN: 81,
- ELIBMAX: 82,
- ELIBEXEC: 83,
- ENOSYS: 38,
- ENOTEMPTY: 39,
- ENAMETOOLONG: 36,
- ELOOP: 40,
- EOPNOTSUPP: 95,
- EPFNOSUPPORT: 96,
- ECONNRESET: 104,
- ENOBUFS: 105,
- EAFNOSUPPORT: 97,
- EPROTOTYPE: 91,
- ENOTSOCK: 88,
- ENOPROTOOPT: 92,
- ESHUTDOWN: 108,
- ECONNREFUSED: 111,
- EADDRINUSE: 98,
- ECONNABORTED: 103,
- ENETUNREACH: 101,
- ENETDOWN: 100,
- ETIMEDOUT: 110,
- EHOSTDOWN: 112,
- EHOSTUNREACH: 113,
- EINPROGRESS: 115,
- EALREADY: 114,
- EDESTADDRREQ: 89,
- EMSGSIZE: 90,
- EPROTONOSUPPORT: 93,
- ESOCKTNOSUPPORT: 94,
- EADDRNOTAVAIL: 99,
- ENETRESET: 102,
- EISCONN: 106,
- ENOTCONN: 107,
- ETOOMANYREFS: 109,
- EUSERS: 87,
- EDQUOT: 122,
- ESTALE: 116,
- ENOTSUP: 95,
- ENOMEDIUM: 123,
- EILSEQ: 84,
- EOVERFLOW: 75,
- ECANCELED: 125,
- ENOTRECOVERABLE: 131,
- EOWNERDEAD: 130,
- ESTRPIPE: 86
- };
- var ERRNO_MESSAGES = {
- 0: "Success",
- 1: "Not super-user",
- 2: "No such file or directory",
- 3: "No such process",
- 4: "Interrupted system call",
- 5: "I/O error",
- 6: "No such device or address",
- 7: "Arg list too long",
- 8: "Exec format error",
- 9: "Bad file number",
- 10: "No children",
- 11: "No more processes",
- 12: "Not enough core",
- 13: "Permission denied",
- 14: "Bad address",
- 15: "Block device required",
- 16: "Mount device busy",
- 17: "File exists",
- 18: "Cross-device link",
- 19: "No such device",
- 20: "Not a directory",
- 21: "Is a directory",
- 22: "Invalid argument",
- 23: "Too many open files in system",
- 24: "Too many open files",
- 25: "Not a typewriter",
- 26: "Text file busy",
- 27: "File too large",
- 28: "No space left on device",
- 29: "Illegal seek",
- 30: "Read only file system",
- 31: "Too many links",
- 32: "Broken pipe",
- 33: "Math arg out of domain of func",
- 34: "Math result not representable",
- 35: "File locking deadlock error",
- 36: "File or path name too long",
- 37: "No record locks available",
- 38: "Function not implemented",
- 39: "Directory not empty",
- 40: "Too many symbolic links",
- 42: "No message of desired type",
- 43: "Identifier removed",
- 44: "Channel number out of range",
- 45: "Level 2 not synchronized",
- 46: "Level 3 halted",
- 47: "Level 3 reset",
- 48: "Link number out of range",
- 49: "Protocol driver not attached",
- 50: "No CSI structure available",
- 51: "Level 2 halted",
- 52: "Invalid exchange",
- 53: "Invalid request descriptor",
- 54: "Exchange full",
- 55: "No anode",
- 56: "Invalid request code",
- 57: "Invalid slot",
- 59: "Bad font file fmt",
- 60: "Device not a stream",
- 61: "No data (for no delay io)",
- 62: "Timer expired",
- 63: "Out of streams resources",
- 64: "Machine is not on the network",
- 65: "Package not installed",
- 66: "The object is remote",
- 67: "The link has been severed",
- 68: "Advertise error",
- 69: "Srmount error",
- 70: "Communication error on send",
- 71: "Protocol error",
- 72: "Multihop attempted",
- 73: "Cross mount point (not really error)",
- 74: "Trying to read unreadable message",
- 75: "Value too large for defined data type",
- 76: "Given log. name not unique",
- 77: "f.d. invalid for this operation",
- 78: "Remote address changed",
- 79: "Can access a needed shared lib",
- 80: "Accessing a corrupted shared lib",
- 81: ".lib section in a.out corrupted",
- 82: "Attempting to link in too many libs",
- 83: "Attempting to exec a shared library",
- 84: "Illegal byte sequence",
- 86: "Streams pipe error",
- 87: "Too many users",
- 88: "Socket operation on non-socket",
- 89: "Destination address required",
- 90: "Message too long",
- 91: "Protocol wrong type for socket",
- 92: "Protocol not available",
- 93: "Unknown protocol",
- 94: "Socket type not supported",
- 95: "Not supported",
- 96: "Protocol family not supported",
- 97: "Address family not supported by protocol family",
- 98: "Address already in use",
- 99: "Address not available",
- 100: "Network interface is not configured",
- 101: "Network is unreachable",
- 102: "Connection reset by network",
- 103: "Connection aborted",
- 104: "Connection reset by peer",
- 105: "No buffer space available",
- 106: "Socket is already connected",
- 107: "Socket is not connected",
- 108: "Can't send after socket shutdown",
- 109: "Too many references",
- 110: "Connection timed out",
- 111: "Connection refused",
- 112: "Host is down",
- 113: "Host is unreachable",
- 114: "Socket already connected",
- 115: "Connection already in progress",
- 116: "Stale file handle",
- 122: "Quota exceeded",
- 123: "No medium (in tape drive)",
- 125: "Operation canceled",
- 130: "Previous owner died",
- 131: "State not recoverable"
- };
- var ___errno_state = 0;
- function ___setErrNo(value) {
- // For convenient setting and returning of errno.
- HEAP32[((___errno_state) >> 2)] = value;
- return value;
- }
- var TTY = {
- ttys: [],
- init: function () {
- // https://github.com/kripken/emscripten/pull/1555
- // if (ENVIRONMENT_IS_NODE) {
- // // currently, FS.init does not distinguish if process.stdin is a file or TTY
- // // device, it always assumes it's a TTY device. because of this, we're forcing
- // // process.stdin to UTF8 encoding to at least make stdin reading compatible
- // // with text files until FS.init can be refactored.
- // process['stdin']['setEncoding']('utf8');
- // }
- },
- shutdown: function () {
- // https://github.com/kripken/emscripten/pull/1555
- // if (ENVIRONMENT_IS_NODE) {
- // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
- // // 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
- // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
- // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
- // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
- // process['stdin']['pause']();
- // }
- },
- register: function (dev, ops) {
- TTY.ttys[dev] = {
- input: [],
- output: [],
- ops: ops
- };
- FS.registerDevice(dev, TTY.stream_ops);
- },
- stream_ops: {
- open: function (stream) {
- var tty = TTY.ttys[stream.node.rdev];
- if (!tty) {
- throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
- }
- stream.tty = tty;
- stream.seekable = false;
- },
- close: function (stream) {
- // flush any pending line data
- if (stream.tty.output.length) {
- stream.tty.ops.put_char(stream.tty, 10);
- }
- },
- read: function (stream, buffer, offset, length, pos /* ignored */ ) {
- if (!stream.tty || !stream.tty.ops.get_char) {
- throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
- }
- var bytesRead = 0;
- for (var i = 0; i < length; i++) {
- var result;
- try {
- result = stream.tty.ops.get_char(stream.tty);
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- if (result === undefined && bytesRead === 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
- }
- if (result === null || result === undefined) break;
- bytesRead++;
- buffer[offset + i] = result;
- }
- if (bytesRead) {
- stream.node.timestamp = Date.now();
- }
- return bytesRead;
- },
- write: function (stream, buffer, offset, length, pos) {
- if (!stream.tty || !stream.tty.ops.put_char) {
- throw new FS.ErrnoError(ERRNO_CODES.ENXIO);
- }
- for (var i = 0; i < length; i++) {
- try {
- stream.tty.ops.put_char(stream.tty, buffer[offset + i]);
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- }
- if (length) {
- stream.node.timestamp = Date.now();
- }
- return i;
- }
- },
- default_tty_ops: {
- get_char: function (tty) {
- if (!tty.input.length) {
- var result = null;
- if (ENVIRONMENT_IS_NODE) {
- result = process['stdin']['read']();
- if (!result) {
- if (process['stdin']['_readableState'] && process['stdin']['_readableState']['ended']) {
- return null; // EOF
- }
- return undefined; // no data available
- }
- } else if (typeof window != 'undefined' &&
- typeof window.prompt == 'function') {
- // Browser.
- result = window.prompt('Input: '); // returns null on cancel
- if (result !== null) {
- result += '\n';
- }
- } else if (typeof readline == 'function') {
- // Command line.
- result = readline();
- if (result !== null) {
- result += '\n';
- }
- }
- if (!result) {
- return null;
- }
- tty.input = intArrayFromString(result, true);
- }
- return tty.input.shift();
- },
- put_char: function (tty, val) {
- if (val === null || val === 10) {
- Module['print'](tty.output.join(''));
- tty.output = [];
- } else {
- tty.output.push(TTY.utf8.processCChar(val));
- }
- }
- },
- default_tty1_ops: {
- put_char: function (tty, val) {
- if (val === null || val === 10) {
- Module['printErr'](tty.output.join(''));
- tty.output = [];
- } else {
- tty.output.push(TTY.utf8.processCChar(val));
- }
- }
- }
- };
- var MEMFS = {
- ops_table: null,
- CONTENT_OWNING: 1,
- CONTENT_FLEXIBLE: 2,
- CONTENT_FIXED: 3,
- mount: function (mount) {
- return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */ , 0);
- },
- createNode: function (parent, name, mode, dev) {
- if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
- // no supported
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- if (!MEMFS.ops_table) {
- MEMFS.ops_table = {
- dir: {
- node: {
- getattr: MEMFS.node_ops.getattr,
- setattr: MEMFS.node_ops.setattr,
- lookup: MEMFS.node_ops.lookup,
- mknod: MEMFS.node_ops.mknod,
- rename: MEMFS.node_ops.rename,
- unlink: MEMFS.node_ops.unlink,
- rmdir: MEMFS.node_ops.rmdir,
- readdir: MEMFS.node_ops.readdir,
- symlink: MEMFS.node_ops.symlink
- },
- stream: {
- llseek: MEMFS.stream_ops.llseek
- }
- },
- file: {
- node: {
- getattr: MEMFS.node_ops.getattr,
- setattr: MEMFS.node_ops.setattr
- },
- stream: {
- llseek: MEMFS.stream_ops.llseek,
- read: MEMFS.stream_ops.read,
- write: MEMFS.stream_ops.write,
- allocate: MEMFS.stream_ops.allocate,
- mmap: MEMFS.stream_ops.mmap
- }
- },
- link: {
- node: {
- getattr: MEMFS.node_ops.getattr,
- setattr: MEMFS.node_ops.setattr,
- readlink: MEMFS.node_ops.readlink
- },
- stream: {}
- },
- chrdev: {
- node: {
- getattr: MEMFS.node_ops.getattr,
- setattr: MEMFS.node_ops.setattr
- },
- stream: FS.chrdev_stream_ops
- },
- };
- }
- var node = FS.createNode(parent, name, mode, dev);
- if (FS.isDir(node.mode)) {
- node.node_ops = MEMFS.ops_table.dir.node;
- node.stream_ops = MEMFS.ops_table.dir.stream;
- node.contents = {};
- } else if (FS.isFile(node.mode)) {
- node.node_ops = MEMFS.ops_table.file.node;
- node.stream_ops = MEMFS.ops_table.file.stream;
- node.contents = [];
- node.contentMode = MEMFS.CONTENT_FLEXIBLE;
- } else if (FS.isLink(node.mode)) {
- node.node_ops = MEMFS.ops_table.link.node;
- node.stream_ops = MEMFS.ops_table.link.stream;
- } else if (FS.isChrdev(node.mode)) {
- node.node_ops = MEMFS.ops_table.chrdev.node;
- node.stream_ops = MEMFS.ops_table.chrdev.stream;
- }
- node.timestamp = Date.now();
- // add the new node to the parent
- if (parent) {
- parent.contents[name] = node;
- }
- return node;
- },
- ensureFlexible: function (node) {
- if (node.contentMode !== MEMFS.CONTENT_FLEXIBLE) {
- var contents = node.contents;
- node.contents = Array.prototype.slice.call(contents);
- node.contentMode = MEMFS.CONTENT_FLEXIBLE;
- }
- },
- node_ops: {
- getattr: function (node) {
- var attr = {};
- // device numbers reuse inode numbers.
- attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
- attr.ino = node.id;
- attr.mode = node.mode;
- attr.nlink = 1;
- attr.uid = 0;
- attr.gid = 0;
- attr.rdev = node.rdev;
- if (FS.isDir(node.mode)) {
- attr.size = 4096;
- } else if (FS.isFile(node.mode)) {
- attr.size = node.contents.length;
- } else if (FS.isLink(node.mode)) {
- attr.size = node.link.length;
- } else {
- attr.size = 0;
- }
- attr.atime = new Date(node.timestamp);
- attr.mtime = new Date(node.timestamp);
- attr.ctime = new Date(node.timestamp);
- // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
- // but this is not required by the standard.
- attr.blksize = 4096;
- attr.blocks = Math.ceil(attr.size / attr.blksize);
- return attr;
- },
- setattr: function (node, attr) {
- if (attr.mode !== undefined) {
- node.mode = attr.mode;
- }
- if (attr.timestamp !== undefined) {
- node.timestamp = attr.timestamp;
- }
- if (attr.size !== undefined) {
- MEMFS.ensureFlexible(node);
- var contents = node.contents;
- if (attr.size < contents.length) contents.length = attr.size;
- else
- while (attr.size > contents.length) contents.push(0);
- }
- },
- lookup: function (parent, name) {
- throw FS.genericErrors[ERRNO_CODES.ENOENT];
- },
- mknod: function (parent, name, mode, dev) {
- return MEMFS.createNode(parent, name, mode, dev);
- },
- rename: function (old_node, new_dir, new_name) {
- // if we're overwriting a directory at new_name, make sure it's empty.
- if (FS.isDir(old_node.mode)) {
- var new_node;
- try {
- new_node = FS.lookupNode(new_dir, new_name);
- } catch (e) {}
- if (new_node) {
- for (var i in new_node.contents) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
- }
- }
- }
- // do the internal rewiring
- delete old_node.parent.contents[old_node.name];
- old_node.name = new_name;
- new_dir.contents[new_name] = old_node;
- old_node.parent = new_dir;
- },
- unlink: function (parent, name) {
- delete parent.contents[name];
- },
- rmdir: function (parent, name) {
- var node = FS.lookupNode(parent, name);
- for (var i in node.contents) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
- }
- delete parent.contents[name];
- },
- readdir: function (node) {
- var entries = ['.', '..']
- for (var key in node.contents) {
- if (!node.contents.hasOwnProperty(key)) {
- continue;
- }
- entries.push(key);
- }
- return entries;
- },
- symlink: function (parent, newname, oldpath) {
- var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
- node.link = oldpath;
- return node;
- },
- readlink: function (node) {
- if (!FS.isLink(node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- return node.link;
- }
- },
- stream_ops: {
- read: function (stream, buffer, offset, length, position) {
- var contents = stream.node.contents;
- if (position >= contents.length)
- return 0;
- var size = Math.min(contents.length - position, length);
- assert(size >= 0);
- if (size > 8 && contents.subarray) { // non-trivial, and typed array
- buffer.set(contents.subarray(position, position + size), offset);
- } else {
- for (var i = 0; i < size; i++) {
- buffer[offset + i] = contents[position + i];
- }
- }
- return size;
- },
- write: function (stream, buffer, offset, length, position, canOwn) {
- var node = stream.node;
- node.timestamp = Date.now();
- var contents = node.contents;
- if (length && contents.length === 0 && position === 0 && buffer.subarray) {
- // just replace it with the new data
- if (canOwn && offset === 0) {
- node.contents = buffer; // this could be a subarray of Emscripten HEAP, or allocated from some other source.
- node.contentMode = (buffer.buffer === HEAP8.buffer) ? MEMFS.CONTENT_OWNING : MEMFS.CONTENT_FIXED;
- } else {
- node.contents = new Uint8Array(buffer.subarray(offset, offset + length));
- node.contentMode = MEMFS.CONTENT_FIXED;
- }
- return length;
- }
- MEMFS.ensureFlexible(node);
- var contents = node.contents;
- while (contents.length < position) contents.push(0);
- for (var i = 0; i < length; i++) {
- contents[position + i] = buffer[offset + i];
- }
- return length;
- },
- llseek: function (stream, offset, whence) {
- var position = offset;
- if (whence === 1) { // SEEK_CUR.
- position += stream.position;
- } else if (whence === 2) { // SEEK_END.
- if (FS.isFile(stream.node.mode)) {
- position += stream.node.contents.length;
- }
- }
- if (position < 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- stream.ungotten = [];
- stream.position = position;
- return position;
- },
- allocate: function (stream, offset, length) {
- MEMFS.ensureFlexible(stream.node);
- var contents = stream.node.contents;
- var limit = offset + length;
- while (limit > contents.length) contents.push(0);
- },
- mmap: function (stream, buffer, offset, length, position, prot, flags) {
- if (!FS.isFile(stream.node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
- }
- var ptr;
- var allocated;
- var contents = stream.node.contents;
- // Only make a new copy when MAP_PRIVATE is specified.
- if (!(flags & 2) &&
- (contents.buffer === buffer || contents.buffer === buffer.buffer)) {
- // We can't emulate MAP_SHARED when the file is not backed by the buffer
- // we're mapping to (e.g. the HEAP buffer).
- allocated = false;
- ptr = contents.byteOffset;
- } else {
- // Try to avoid unnecessary slices.
- if (position > 0 || position + length < contents.length) {
- if (contents.subarray) {
- contents = contents.subarray(position, position + length);
- } else {
- contents = Array.prototype.slice.call(contents, position, position + length);
- }
- }
- allocated = true;
- ptr = _malloc(length);
- if (!ptr) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOMEM);
- }
- buffer.set(contents, ptr);
- }
- return {
- ptr: ptr,
- allocated: allocated
- };
- }
- }
- };
- var IDBFS = {
- dbs: {},
- indexedDB: function () {
- return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
- },
- DB_VERSION: 21,
- DB_STORE_NAME: "FILE_DATA",
- mount: function (mount) {
- // reuse all of the core MEMFS functionality
- return MEMFS.mount.apply(null, arguments);
- },
- syncfs: function (mount, populate, callback) {
- IDBFS.getLocalSet(mount, function (err, local) {
- if (err) return callback(err);
- IDBFS.getRemoteSet(mount, function (err, remote) {
- if (err) return callback(err);
- var src = populate ? remote : local;
- var dst = populate ? local : remote;
- IDBFS.reconcile(src, dst, callback);
- });
- });
- },
- getDB: function (name, callback) {
- // check the cache first
- var db = IDBFS.dbs[name];
- if (db) {
- return callback(null, db);
- }
- var req;
- try {
- req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
- } catch (e) {
- return callback(e);
- }
- req.onupgradeneeded = function (e) {
- var db = e.target.result;
- var transaction = e.target.transaction;
- var fileStore;
- if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
- fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
- } else {
- fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
- }
- fileStore.createIndex('timestamp', 'timestamp', {
- unique: false
- });
- };
- req.onsuccess = function () {
- db = req.result;
- // add to the cache
- IDBFS.dbs[name] = db;
- callback(null, db);
- };
- req.onerror = function () {
- callback(this.error);
- };
- },
- getLocalSet: function (mount, callback) {
- var entries = {};
- function isRealDir(p) {
- return p !== '.' && p !== '..';
- };
- function toAbsolute(root) {
- return function (p) {
- return PATH.join2(root, p);
- }
- };
- var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
- while (check.length) {
- var path = check.pop();
- var stat;
- try {
- stat = FS.stat(path);
- } catch (e) {
- return callback(e);
- }
- if (FS.isDir(stat.mode)) {
- check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
- }
- entries[path] = {
- timestamp: stat.mtime
- };
- }
- return callback(null, {
- type: 'local',
- entries: entries
- });
- },
- getRemoteSet: function (mount, callback) {
- var entries = {};
- IDBFS.getDB(mount.mountpoint, function (err, db) {
- if (err) return callback(err);
- var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
- transaction.onerror = function () {
- callback(this.error);
- };
- var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
- var index = store.index('timestamp');
- index.openKeyCursor().onsuccess = function (event) {
- var cursor = event.target.result;
- if (!cursor) {
- return callback(null, {
- type: 'remote',
- db: db,
- entries: entries
- });
- }
- entries[cursor.primaryKey] = {
- timestamp: cursor.key
- };
- cursor.continue();
- };
- });
- },
- loadLocalEntry: function (path, callback) {
- var stat, node;
- try {
- var lookup = FS.lookupPath(path);
- node = lookup.node;
- stat = FS.stat(path);
- } catch (e) {
- return callback(e);
- }
- if (FS.isDir(stat.mode)) {
- return callback(null, {
- timestamp: stat.mtime,
- mode: stat.mode
- });
- } else if (FS.isFile(stat.mode)) {
- return callback(null, {
- timestamp: stat.mtime,
- mode: stat.mode,
- contents: node.contents
- });
- } else {
- return callback(new Error('node type not supported'));
- }
- },
- storeLocalEntry: function (path, entry, callback) {
- try {
- if (FS.isDir(entry.mode)) {
- FS.mkdir(path, entry.mode);
- } else if (FS.isFile(entry.mode)) {
- FS.writeFile(path, entry.contents, {
- encoding: 'binary',
- canOwn: true
- });
- } else {
- return callback(new Error('node type not supported'));
- }
- FS.utime(path, entry.timestamp, entry.timestamp);
- } catch (e) {
- return callback(e);
- }
- callback(null);
- },
- removeLocalEntry: function (path, callback) {
- try {
- var lookup = FS.lookupPath(path);
- var stat = FS.stat(path);
- if (FS.isDir(stat.mode)) {
- FS.rmdir(path);
- } else if (FS.isFile(stat.mode)) {
- FS.unlink(path);
- }
- } catch (e) {
- return callback(e);
- }
- callback(null);
- },
- loadRemoteEntry: function (store, path, callback) {
- var req = store.get(path);
- req.onsuccess = function (event) {
- callback(null, event.target.result);
- };
- req.onerror = function () {
- callback(this.error);
- };
- },
- storeRemoteEntry: function (store, path, entry, callback) {
- var req = store.put(entry, path);
- req.onsuccess = function () {
- callback(null);
- };
- req.onerror = function () {
- callback(this.error);
- };
- },
- removeRemoteEntry: function (store, path, callback) {
- var req = store.delete(path);
- req.onsuccess = function () {
- callback(null);
- };
- req.onerror = function () {
- callback(this.error);
- };
- },
- reconcile: function (src, dst, callback) {
- var total = 0;
- var create = [];
- Object.keys(src.entries).forEach(function (key) {
- var e = src.entries[key];
- var e2 = dst.entries[key];
- if (!e2 || e.timestamp > e2.timestamp) {
- create.push(key);
- total++;
- }
- });
- var remove = [];
- Object.keys(dst.entries).forEach(function (key) {
- var e = dst.entries[key];
- var e2 = src.entries[key];
- if (!e2) {
- remove.push(key);
- total++;
- }
- });
- if (!total) {
- return callback(null);
- }
- var errored = false;
- var completed = 0;
- var db = src.type === 'remote' ? src.db : dst.db;
- var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
- var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
- function done(err) {
- if (err) {
- if (!done.errored) {
- done.errored = true;
- return callback(err);
- }
- return;
- }
- if (++completed >= total) {
- return callback(null);
- }
- };
- transaction.onerror = function () {
- done(this.error);
- };
- // sort paths in ascending order so directory entries are created
- // before the files inside them
- create.sort().forEach(function (path) {
- if (dst.type === 'local') {
- IDBFS.loadRemoteEntry(store, path, function (err, entry) {
- if (err) return done(err);
- IDBFS.storeLocalEntry(path, entry, done);
- });
- } else {
- IDBFS.loadLocalEntry(path, function (err, entry) {
- if (err) return done(err);
- IDBFS.storeRemoteEntry(store, path, entry, done);
- });
- }
- });
- // sort paths in descending order so files are deleted before their
- // parent directories
- remove.sort().reverse().forEach(function (path) {
- if (dst.type === 'local') {
- IDBFS.removeLocalEntry(path, done);
- } else {
- IDBFS.removeRemoteEntry(store, path, done);
- }
- });
- }
- };
- var NODEFS = {
- isWindows: false,
- staticInit: function () {
- NODEFS.isWindows = !!process.platform.match(/^win/);
- },
- mount: function (mount) {
- assert(ENVIRONMENT_IS_NODE);
- return NODEFS.createNode(null, '/', NODEFS.getMode(mount.opts.root), 0);
- },
- createNode: function (parent, name, mode, dev) {
- if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var node = FS.createNode(parent, name, mode);
- node.node_ops = NODEFS.node_ops;
- node.stream_ops = NODEFS.stream_ops;
- return node;
- },
- getMode: function (path) {
- var stat;
- try {
- stat = fs.lstatSync(path);
- if (NODEFS.isWindows) {
- // On Windows, directories return permission bits 'rw-rw-rw-', even though they have 'rwxrwxrwx', so
- // propagate write bits to execute bits.
- stat.mode = stat.mode | ((stat.mode & 146) >> 1);
- }
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- return stat.mode;
- },
- realPath: function (node) {
- var parts = [];
- while (node.parent !== node) {
- parts.push(node.name);
- node = node.parent;
- }
- parts.push(node.mount.opts.root);
- parts.reverse();
- return PATH.join.apply(null, parts);
- },
- flagsToPermissionStringMap: {
- 0: "r",
- 1: "r+",
- 2: "r+",
- 64: "r",
- 65: "r+",
- 66: "r+",
- 129: "rx+",
- 193: "rx+",
- 514: "w+",
- 577: "w",
- 578: "w+",
- 705: "wx",
- 706: "wx+",
- 1024: "a",
- 1025: "a",
- 1026: "a+",
- 1089: "a",
- 1090: "a+",
- 1153: "ax",
- 1154: "ax+",
- 1217: "ax",
- 1218: "ax+",
- 4096: "rs",
- 4098: "rs+"
- },
- flagsToPermissionString: function (flags) {
- if (flags in NODEFS.flagsToPermissionStringMap) {
- return NODEFS.flagsToPermissionStringMap[flags];
- } else {
- return flags;
- }
- },
- node_ops: {
- getattr: function (node) {
- var path = NODEFS.realPath(node);
- var stat;
- try {
- stat = fs.lstatSync(path);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- // node.js v0.10.20 doesn't report blksize and blocks on Windows. Fake them with default blksize of 4096.
- // See http://support.microsoft.com/kb/140365
- if (NODEFS.isWindows && !stat.blksize) {
- stat.blksize = 4096;
- }
- if (NODEFS.isWindows && !stat.blocks) {
- stat.blocks = (stat.size + stat.blksize - 1) / stat.blksize | 0;
- }
- return {
- dev: stat.dev,
- ino: stat.ino,
- mode: stat.mode,
- nlink: stat.nlink,
- uid: stat.uid,
- gid: stat.gid,
- rdev: stat.rdev,
- size: stat.size,
- atime: stat.atime,
- mtime: stat.mtime,
- ctime: stat.ctime,
- blksize: stat.blksize,
- blocks: stat.blocks
- };
- },
- setattr: function (node, attr) {
- var path = NODEFS.realPath(node);
- try {
- if (attr.mode !== undefined) {
- fs.chmodSync(path, attr.mode);
- // update the common node structure mode as well
- node.mode = attr.mode;
- }
- if (attr.timestamp !== undefined) {
- var date = new Date(attr.timestamp);
- fs.utimesSync(path, date, date);
- }
- if (attr.size !== undefined) {
- fs.truncateSync(path, attr.size);
- }
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- lookup: function (parent, name) {
- var path = PATH.join2(NODEFS.realPath(parent), name);
- var mode = NODEFS.getMode(path);
- return NODEFS.createNode(parent, name, mode);
- },
- mknod: function (parent, name, mode, dev) {
- var node = NODEFS.createNode(parent, name, mode, dev);
- // create the backing node for this in the fs root as well
- var path = NODEFS.realPath(node);
- try {
- if (FS.isDir(node.mode)) {
- fs.mkdirSync(path, node.mode);
- } else {
- fs.writeFileSync(path, '', {
- mode: node.mode
- });
- }
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- return node;
- },
- rename: function (oldNode, newDir, newName) {
- var oldPath = NODEFS.realPath(oldNode);
- var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
- try {
- fs.renameSync(oldPath, newPath);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- unlink: function (parent, name) {
- var path = PATH.join2(NODEFS.realPath(parent), name);
- try {
- fs.unlinkSync(path);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- rmdir: function (parent, name) {
- var path = PATH.join2(NODEFS.realPath(parent), name);
- try {
- fs.rmdirSync(path);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- readdir: function (node) {
- var path = NODEFS.realPath(node);
- try {
- return fs.readdirSync(path);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- symlink: function (parent, newName, oldPath) {
- var newPath = PATH.join2(NODEFS.realPath(parent), newName);
- try {
- fs.symlinkSync(oldPath, newPath);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- readlink: function (node) {
- var path = NODEFS.realPath(node);
- try {
- return fs.readlinkSync(path);
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- }
- },
- stream_ops: {
- open: function (stream) {
- var path = NODEFS.realPath(stream.node);
- try {
- if (FS.isFile(stream.node.mode)) {
- stream.nfd = fs.openSync(path, NODEFS.flagsToPermissionString(stream.flags));
- }
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- close: function (stream) {
- try {
- if (FS.isFile(stream.node.mode) && stream.nfd) {
- fs.closeSync(stream.nfd);
- }
- } catch (e) {
- if (!e.code) throw e;
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- },
- read: function (stream, buffer, offset, length, position) {
- // FIXME this is terrible.
- var nbuffer = new Buffer(length);
- var res;
- try {
- res = fs.readSync(stream.nfd, nbuffer, 0, length, position);
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- if (res > 0) {
- for (var i = 0; i < res; i++) {
- buffer[offset + i] = nbuffer[i];
- }
- }
- return res;
- },
- write: function (stream, buffer, offset, length, position) {
- // FIXME this is terrible.
- var nbuffer = new Buffer(buffer.subarray(offset, offset + length));
- var res;
- try {
- res = fs.writeSync(stream.nfd, nbuffer, 0, length, position);
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- return res;
- },
- llseek: function (stream, offset, whence) {
- var position = offset;
- if (whence === 1) { // SEEK_CUR.
- position += stream.position;
- } else if (whence === 2) { // SEEK_END.
- if (FS.isFile(stream.node.mode)) {
- try {
- var stat = fs.fstatSync(stream.nfd);
- position += stat.size;
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES[e.code]);
- }
- }
- }
- if (position < 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- stream.position = position;
- return position;
- }
- }
- };
- var _stdin = allocate(1, "i32*", ALLOC_STATIC);
- var _stdout = allocate(1, "i32*", ALLOC_STATIC);
- var _stderr = allocate(1, "i32*", ALLOC_STATIC);
- function _fflush(stream) {
- // int fflush(FILE *stream);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/fflush.html
- // we don't currently perform any user-space buffering of data
- }
- var FS = {
- root: null,
- mounts: [],
- devices: [null],
- streams: [],
- nextInode: 1,
- nameTable: null,
- currentPath: "/",
- initialized: false,
- ignorePermissions: true,
- ErrnoError: null,
- genericErrors: {},
- handleFSError: function (e) {
- if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
- return ___setErrNo(e.errno);
- },
- lookupPath: function (path, opts) {
- path = PATH.resolve(FS.cwd(), path);
- opts = opts || {};
- var defaults = {
- follow_mount: true,
- recurse_count: 0
- };
- for (var key in defaults) {
- if (opts[key] === undefined) {
- opts[key] = defaults[key];
- }
- }
- if (opts.recurse_count > 8) { // max recursive lookup of 8
- throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
- }
- // split the path
- var parts = PATH.normalizeArray(path.split('/').filter(function (p) {
- return !!p;
- }), false);
- // start at the root
- var current = FS.root;
- var current_path = '/';
- for (var i = 0; i < parts.length; i++) {
- var islast = (i === parts.length - 1);
- if (islast && opts.parent) {
- // stop resolving
- break;
- }
- current = FS.lookupNode(current, parts[i]);
- current_path = PATH.join2(current_path, parts[i]);
- // jump to the mount's root node if this is a mountpoint
- if (FS.isMountpoint(current)) {
- if (!islast || (islast && opts.follow_mount)) {
- current = current.mounted.root;
- }
- }
- // by default, lookupPath will not follow a symlink if it is the final path component.
- // setting opts.follow = true will override this behavior.
- if (!islast || opts.follow) {
- var count = 0;
- while (FS.isLink(current.mode)) {
- var link = FS.readlink(current_path);
- current_path = PATH.resolve(PATH.dirname(current_path), link);
- var lookup = FS.lookupPath(current_path, {
- recurse_count: opts.recurse_count
- });
- current = lookup.node;
- if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
- throw new FS.ErrnoError(ERRNO_CODES.ELOOP);
- }
- }
- }
- }
- return {
- path: current_path,
- node: current
- };
- },
- getPath: function (node) {
- var path;
- while (true) {
- if (FS.isRoot(node)) {
- var mount = node.mount.mountpoint;
- if (!path) return mount;
- return mount[mount.length - 1] !== '/' ? mount + '/' + path : mount + path;
- }
- path = path ? node.name + '/' + path : node.name;
- node = node.parent;
- }
- },
- hashName: function (parentid, name) {
- var hash = 0;
- for (var i = 0; i < name.length; i++) {
- hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
- }
- return ((parentid + hash) >>> 0) % FS.nameTable.length;
- },
- hashAddNode: function (node) {
- var hash = FS.hashName(node.parent.id, node.name);
- node.name_next = FS.nameTable[hash];
- FS.nameTable[hash] = node;
- },
- hashRemoveNode: function (node) {
- var hash = FS.hashName(node.parent.id, node.name);
- if (FS.nameTable[hash] === node) {
- FS.nameTable[hash] = node.name_next;
- } else {
- var current = FS.nameTable[hash];
- while (current) {
- if (current.name_next === node) {
- current.name_next = node.name_next;
- break;
- }
- current = current.name_next;
- }
- }
- },
- lookupNode: function (parent, name) {
- var err = FS.mayLookup(parent);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- var hash = FS.hashName(parent.id, name);
- for (var node = FS.nameTable[hash]; node; node = node.name_next) {
- var nodeName = node.name;
- if (node.parent.id === parent.id && nodeName === name) {
- return node;
- }
- }
- // if we failed to find it in the cache, call into the VFS
- return FS.lookup(parent, name);
- },
- createNode: function (parent, name, mode, rdev) {
- if (!FS.FSNode) {
- FS.FSNode = function (parent, name, mode, rdev) {
- if (!parent) {
- parent = this; // root node sets parent to itself
- }
- this.parent = parent;
- this.mount = parent.mount;
- this.mounted = null;
- this.id = FS.nextInode++;
- this.name = name;
- this.mode = mode;
- this.node_ops = {};
- this.stream_ops = {};
- this.rdev = rdev;
- };
- FS.FSNode.prototype = {};
- // compatibility
- var readMode = 292 | 73;
- var writeMode = 146;
- // NOTE we must use Object.defineProperties instead of individual calls to
- // Object.defineProperty in order to make closure compiler happy
- Object.defineProperties(FS.FSNode.prototype, {
- read: {
- get: function () {
- return (this.mode & readMode) === readMode;
- },
- set: function (val) {
- val ? this.mode |= readMode : this.mode &= ~readMode;
- }
- },
- write: {
- get: function () {
- return (this.mode & writeMode) === writeMode;
- },
- set: function (val) {
- val ? this.mode |= writeMode : this.mode &= ~writeMode;
- }
- },
- isFolder: {
- get: function () {
- return FS.isDir(this.mode);
- },
- },
- isDevice: {
- get: function () {
- return FS.isChrdev(this.mode);
- },
- },
- });
- }
- var node = new FS.FSNode(parent, name, mode, rdev);
- FS.hashAddNode(node);
- return node;
- },
- destroyNode: function (node) {
- FS.hashRemoveNode(node);
- },
- isRoot: function (node) {
- return node === node.parent;
- },
- isMountpoint: function (node) {
- return !!node.mounted;
- },
- isFile: function (mode) {
- return (mode & 61440) === 32768;
- },
- isDir: function (mode) {
- return (mode & 61440) === 16384;
- },
- isLink: function (mode) {
- return (mode & 61440) === 40960;
- },
- isChrdev: function (mode) {
- return (mode & 61440) === 8192;
- },
- isBlkdev: function (mode) {
- return (mode & 61440) === 24576;
- },
- isFIFO: function (mode) {
- return (mode & 61440) === 4096;
- },
- isSocket: function (mode) {
- return (mode & 49152) === 49152;
- },
- flagModes: {
- "r": 0,
- "rs": 1052672,
- "r+": 2,
- "w": 577,
- "wx": 705,
- "xw": 705,
- "w+": 578,
- "wx+": 706,
- "xw+": 706,
- "a": 1089,
- "ax": 1217,
- "xa": 1217,
- "a+": 1090,
- "ax+": 1218,
- "xa+": 1218
- },
- modeStringToFlags: function (str) {
- var flags = FS.flagModes[str];
- if (typeof flags === 'undefined') {
- throw new Error('Unknown file open mode: ' + str);
- }
- return flags;
- },
- flagsToPermissionString: function (flag) {
- var accmode = flag & 2097155;
- var perms = ['r', 'w', 'rw'][accmode];
- if ((flag & 512)) {
- perms += 'w';
- }
- return perms;
- },
- nodePermissions: function (node, perms) {
- if (FS.ignorePermissions) {
- return 0;
- }
- // return 0 if any user, group or owner bits are set.
- if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
- return ERRNO_CODES.EACCES;
- } else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
- return ERRNO_CODES.EACCES;
- } else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
- return ERRNO_CODES.EACCES;
- }
- return 0;
- },
- mayLookup: function (dir) {
- return FS.nodePermissions(dir, 'x');
- },
- mayCreate: function (dir, name) {
- try {
- var node = FS.lookupNode(dir, name);
- return ERRNO_CODES.EEXIST;
- } catch (e) {}
- return FS.nodePermissions(dir, 'wx');
- },
- mayDelete: function (dir, name, isdir) {
- var node;
- try {
- node = FS.lookupNode(dir, name);
- } catch (e) {
- return e.errno;
- }
- var err = FS.nodePermissions(dir, 'wx');
- if (err) {
- return err;
- }
- if (isdir) {
- if (!FS.isDir(node.mode)) {
- return ERRNO_CODES.ENOTDIR;
- }
- if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
- return ERRNO_CODES.EBUSY;
- }
- } else {
- if (FS.isDir(node.mode)) {
- return ERRNO_CODES.EISDIR;
- }
- }
- return 0;
- },
- mayOpen: function (node, flags) {
- if (!node) {
- return ERRNO_CODES.ENOENT;
- }
- if (FS.isLink(node.mode)) {
- return ERRNO_CODES.ELOOP;
- } else if (FS.isDir(node.mode)) {
- if ((flags & 2097155) !== 0 || // opening for write
- (flags & 512)) {
- return ERRNO_CODES.EISDIR;
- }
- }
- return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
- },
- MAX_OPEN_FDS: 4096,
- nextfd: function (fd_start, fd_end) {
- fd_start = fd_start || 0;
- fd_end = fd_end || FS.MAX_OPEN_FDS;
- for (var fd = fd_start; fd <= fd_end; fd++) {
- if (!FS.streams[fd]) {
- return fd;
- }
- }
- throw new FS.ErrnoError(ERRNO_CODES.EMFILE);
- },
- getStream: function (fd) {
- return FS.streams[fd];
- },
- createStream: function (stream, fd_start, fd_end) {
- if (!FS.FSStream) {
- FS.FSStream = function () {};
- FS.FSStream.prototype = {};
- // compatibility
- Object.defineProperties(FS.FSStream.prototype, {
- object: {
- get: function () {
- return this.node;
- },
- set: function (val) {
- this.node = val;
- }
- },
- isRead: {
- get: function () {
- return (this.flags & 2097155) !== 1;
- }
- },
- isWrite: {
- get: function () {
- return (this.flags & 2097155) !== 0;
- }
- },
- isAppend: {
- get: function () {
- return (this.flags & 1024);
- }
- }
- });
- }
- if (stream.__proto__) {
- // reuse the object
- stream.__proto__ = FS.FSStream.prototype;
- } else {
- var newStream = new FS.FSStream();
- for (var p in stream) {
- newStream[p] = stream[p];
- }
- stream = newStream;
- }
- var fd = FS.nextfd(fd_start, fd_end);
- stream.fd = fd;
- FS.streams[fd] = stream;
- return stream;
- },
- closeStream: function (fd) {
- FS.streams[fd] = null;
- },
- getStreamFromPtr: function (ptr) {
- return FS.streams[ptr - 1];
- },
- getPtrForStream: function (stream) {
- return stream ? stream.fd + 1 : 0;
- },
- chrdev_stream_ops: {
- open: function (stream) {
- var device = FS.getDevice(stream.node.rdev);
- // override node's stream ops with the device's
- stream.stream_ops = device.stream_ops;
- // forward the open call
- if (stream.stream_ops.open) {
- stream.stream_ops.open(stream);
- }
- },
- llseek: function () {
- throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
- }
- },
- major: function (dev) {
- return ((dev) >> 8);
- },
- minor: function (dev) {
- return ((dev) & 0xff);
- },
- makedev: function (ma, mi) {
- return ((ma) << 8 | (mi));
- },
- registerDevice: function (dev, ops) {
- FS.devices[dev] = {
- stream_ops: ops
- };
- },
- getDevice: function (dev) {
- return FS.devices[dev];
- },
- getMounts: function (mount) {
- var mounts = [];
- var check = [mount];
- while (check.length) {
- var m = check.pop();
- mounts.push(m);
- check.push.apply(check, m.mounts);
- }
- return mounts;
- },
- syncfs: function (populate, callback) {
- if (typeof (populate) === 'function') {
- callback = populate;
- populate = false;
- }
- var mounts = FS.getMounts(FS.root.mount);
- var completed = 0;
- function done(err) {
- if (err) {
- if (!done.errored) {
- done.errored = true;
- return callback(err);
- }
- return;
- }
- if (++completed >= mounts.length) {
- callback(null);
- }
- };
- // sync all mounts
- mounts.forEach(function (mount) {
- if (!mount.type.syncfs) {
- return done(null);
- }
- mount.type.syncfs(mount, populate, done);
- });
- },
- mount: function (type, opts, mountpoint) {
- var root = mountpoint === '/';
- var pseudo = !mountpoint;
- var node;
- if (root && FS.root) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- } else if (!root && !pseudo) {
- var lookup = FS.lookupPath(mountpoint, {
- follow_mount: false
- });
- mountpoint = lookup.path; // use the absolute path
- node = lookup.node;
- if (FS.isMountpoint(node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- }
- if (!FS.isDir(node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
- }
- }
- var mount = {
- type: type,
- opts: opts,
- mountpoint: mountpoint,
- mounts: []
- };
- // create a root node for the fs
- var mountRoot = type.mount(mount);
- mountRoot.mount = mount;
- mount.root = mountRoot;
- if (root) {
- FS.root = mountRoot;
- } else if (node) {
- // set as a mountpoint
- node.mounted = mount;
- // add the new mount to the current mount's children
- if (node.mount) {
- node.mount.mounts.push(mount);
- }
- }
- return mountRoot;
- },
- unmount: function (mountpoint) {
- var lookup = FS.lookupPath(mountpoint, {
- follow_mount: false
- });
- if (!FS.isMountpoint(lookup.node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- // destroy the nodes for this mount, and all its child mounts
- var node = lookup.node;
- var mount = node.mounted;
- var mounts = FS.getMounts(mount);
- Object.keys(FS.nameTable).forEach(function (hash) {
- var current = FS.nameTable[hash];
- while (current) {
- var next = current.name_next;
- if (mounts.indexOf(current.mount) !== -1) {
- FS.destroyNode(current);
- }
- current = next;
- }
- });
- // no longer a mountpoint
- node.mounted = null;
- // remove this mount from the child mounts
- var idx = node.mount.mounts.indexOf(mount);
- assert(idx !== -1);
- node.mount.mounts.splice(idx, 1);
- },
- lookup: function (parent, name) {
- return parent.node_ops.lookup(parent, name);
- },
- mknod: function (path, mode, dev) {
- var lookup = FS.lookupPath(path, {
- parent: true
- });
- var parent = lookup.node;
- var name = PATH.basename(path);
- var err = FS.mayCreate(parent, name);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- if (!parent.node_ops.mknod) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- return parent.node_ops.mknod(parent, name, mode, dev);
- },
- create: function (path, mode) {
- mode = mode !== undefined ? mode : 438 /* 0666 */ ;
- mode &= 4095;
- mode |= 32768;
- return FS.mknod(path, mode, 0);
- },
- mkdir: function (path, mode) {
- mode = mode !== undefined ? mode : 511 /* 0777 */ ;
- mode &= 511 | 512;
- mode |= 16384;
- return FS.mknod(path, mode, 0);
- },
- mkdev: function (path, mode, dev) {
- if (typeof (dev) === 'undefined') {
- dev = mode;
- mode = 438 /* 0666 */ ;
- }
- mode |= 8192;
- return FS.mknod(path, mode, dev);
- },
- symlink: function (oldpath, newpath) {
- var lookup = FS.lookupPath(newpath, {
- parent: true
- });
- var parent = lookup.node;
- var newname = PATH.basename(newpath);
- var err = FS.mayCreate(parent, newname);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- if (!parent.node_ops.symlink) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- return parent.node_ops.symlink(parent, newname, oldpath);
- },
- rename: function (old_path, new_path) {
- var old_dirname = PATH.dirname(old_path);
- var new_dirname = PATH.dirname(new_path);
- var old_name = PATH.basename(old_path);
- var new_name = PATH.basename(new_path);
- // parents must exist
- var lookup, old_dir, new_dir;
- try {
- lookup = FS.lookupPath(old_path, {
- parent: true
- });
- old_dir = lookup.node;
- lookup = FS.lookupPath(new_path, {
- parent: true
- });
- new_dir = lookup.node;
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- }
- // need to be part of the same mount
- if (old_dir.mount !== new_dir.mount) {
- throw new FS.ErrnoError(ERRNO_CODES.EXDEV);
- }
- // source must exist
- var old_node = FS.lookupNode(old_dir, old_name);
- // old path should not be an ancestor of the new path
- var relative = PATH.relative(old_path, new_dirname);
- if (relative.charAt(0) !== '.') {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- // new path should not be an ancestor of the old path
- relative = PATH.relative(new_path, old_dirname);
- if (relative.charAt(0) !== '.') {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY);
- }
- // see if the new path already exists
- var new_node;
- try {
- new_node = FS.lookupNode(new_dir, new_name);
- } catch (e) {
- // not fatal
- }
- // early out if nothing needs to change
- if (old_node === new_node) {
- return;
- }
- // we'll need to delete the old entry
- var isdir = FS.isDir(old_node.mode);
- var err = FS.mayDelete(old_dir, old_name, isdir);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- // need delete permissions if we'll be overwriting.
- // need create permissions if new doesn't already exist.
- err = new_node ?
- FS.mayDelete(new_dir, new_name, isdir) :
- FS.mayCreate(new_dir, new_name);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- if (!old_dir.node_ops.rename) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- }
- // if we are going to change the parent, check write permissions
- if (new_dir !== old_dir) {
- err = FS.nodePermissions(old_dir, 'w');
- if (err) {
- throw new FS.ErrnoError(err);
- }
- }
- // remove the node from the lookup hash
- FS.hashRemoveNode(old_node);
- // do the underlying fs rename
- try {
- old_dir.node_ops.rename(old_node, new_dir, new_name);
- } catch (e) {
- throw e;
- } finally {
- // add the node back to the hash (in case node_ops.rename
- // changed its name)
- FS.hashAddNode(old_node);
- }
- },
- rmdir: function (path) {
- var lookup = FS.lookupPath(path, {
- parent: true
- });
- var parent = lookup.node;
- var name = PATH.basename(path);
- var node = FS.lookupNode(parent, name);
- var err = FS.mayDelete(parent, name, true);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- if (!parent.node_ops.rmdir) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- if (FS.isMountpoint(node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- }
- parent.node_ops.rmdir(parent, name);
- FS.destroyNode(node);
- },
- readdir: function (path) {
- var lookup = FS.lookupPath(path, {
- follow: true
- });
- var node = lookup.node;
- if (!node.node_ops.readdir) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
- }
- return node.node_ops.readdir(node);
- },
- unlink: function (path) {
- var lookup = FS.lookupPath(path, {
- parent: true
- });
- var parent = lookup.node;
- var name = PATH.basename(path);
- var node = FS.lookupNode(parent, name);
- var err = FS.mayDelete(parent, name, false);
- if (err) {
- // POSIX says unlink should set EPERM, not EISDIR
- if (err === ERRNO_CODES.EISDIR) err = ERRNO_CODES.EPERM;
- throw new FS.ErrnoError(err);
- }
- if (!parent.node_ops.unlink) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- if (FS.isMountpoint(node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EBUSY);
- }
- parent.node_ops.unlink(parent, name);
- FS.destroyNode(node);
- },
- readlink: function (path) {
- var lookup = FS.lookupPath(path);
- var link = lookup.node;
- if (!link.node_ops.readlink) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- return link.node_ops.readlink(link);
- },
- stat: function (path, dontFollow) {
- var lookup = FS.lookupPath(path, {
- follow: !dontFollow
- });
- var node = lookup.node;
- if (!node.node_ops.getattr) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- return node.node_ops.getattr(node);
- },
- lstat: function (path) {
- return FS.stat(path, true);
- },
- chmod: function (path, mode, dontFollow) {
- var node;
- if (typeof path === 'string') {
- var lookup = FS.lookupPath(path, {
- follow: !dontFollow
- });
- node = lookup.node;
- } else {
- node = path;
- }
- if (!node.node_ops.setattr) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- node.node_ops.setattr(node, {
- mode: (mode & 4095) | (node.mode & ~4095),
- timestamp: Date.now()
- });
- },
- lchmod: function (path, mode) {
- FS.chmod(path, mode, true);
- },
- fchmod: function (fd, mode) {
- var stream = FS.getStream(fd);
- if (!stream) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- FS.chmod(stream.node, mode);
- },
- chown: function (path, uid, gid, dontFollow) {
- var node;
- if (typeof path === 'string') {
- var lookup = FS.lookupPath(path, {
- follow: !dontFollow
- });
- node = lookup.node;
- } else {
- node = path;
- }
- if (!node.node_ops.setattr) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- node.node_ops.setattr(node, {
- timestamp: Date.now()
- // we ignore the uid / gid for now
- });
- },
- lchown: function (path, uid, gid) {
- FS.chown(path, uid, gid, true);
- },
- fchown: function (fd, uid, gid) {
- var stream = FS.getStream(fd);
- if (!stream) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- FS.chown(stream.node, uid, gid);
- },
- truncate: function (path, len) {
- if (len < 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var node;
- if (typeof path === 'string') {
- var lookup = FS.lookupPath(path, {
- follow: true
- });
- node = lookup.node;
- } else {
- node = path;
- }
- if (!node.node_ops.setattr) {
- throw new FS.ErrnoError(ERRNO_CODES.EPERM);
- }
- if (FS.isDir(node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
- }
- if (!FS.isFile(node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var err = FS.nodePermissions(node, 'w');
- if (err) {
- throw new FS.ErrnoError(err);
- }
- node.node_ops.setattr(node, {
- size: len,
- timestamp: Date.now()
- });
- },
- ftruncate: function (fd, len) {
- var stream = FS.getStream(fd);
- if (!stream) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- if ((stream.flags & 2097155) === 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- FS.truncate(stream.node, len);
- },
- utime: function (path, atime, mtime) {
- var lookup = FS.lookupPath(path, {
- follow: true
- });
- var node = lookup.node;
- node.node_ops.setattr(node, {
- timestamp: Math.max(atime, mtime)
- });
- },
- open: function (path, flags, mode, fd_start, fd_end) {
- flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
- mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
- if ((flags & 64)) {
- mode = (mode & 4095) | 32768;
- } else {
- mode = 0;
- }
- var node;
- if (typeof path === 'object') {
- node = path;
- } else {
- path = PATH.normalize(path);
- try {
- var lookup = FS.lookupPath(path, {
- follow: !(flags & 131072)
- });
- node = lookup.node;
- } catch (e) {
- // ignore
- }
- }
- // perhaps we need to create the node
- if ((flags & 64)) {
- if (node) {
- // if O_CREAT and O_EXCL are set, error out if the node already exists
- if ((flags & 128)) {
- throw new FS.ErrnoError(ERRNO_CODES.EEXIST);
- }
- } else {
- // node doesn't exist, try to create it
- node = FS.mknod(path, mode, 0);
- }
- }
- if (!node) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOENT);
- }
- // can't truncate a device
- if (FS.isChrdev(node.mode)) {
- flags &= ~512;
- }
- // check permissions
- var err = FS.mayOpen(node, flags);
- if (err) {
- throw new FS.ErrnoError(err);
- }
- // do truncation if necessary
- if ((flags & 512)) {
- FS.truncate(node, 0);
- }
- // we've already handled these, don't pass down to the underlying vfs
- flags &= ~(128 | 512);
- // register the stream with the filesystem
- var stream = FS.createStream({
- node: node,
- path: FS.getPath(node), // we want the absolute path to the node
- flags: flags,
- seekable: true,
- position: 0,
- stream_ops: node.stream_ops,
- // used by the file family libc calls (fopen, fwrite, ferror, etc.)
- ungotten: [],
- error: false
- }, fd_start, fd_end);
- // call the new stream's open function
- if (stream.stream_ops.open) {
- stream.stream_ops.open(stream);
- }
- if (Module['logReadFiles'] && !(flags & 1)) {
- if (!FS.readFiles) FS.readFiles = {};
- if (!(path in FS.readFiles)) {
- FS.readFiles[path] = 1;
- Module['printErr']('read file: ' + path);
- }
- }
- return stream;
- },
- close: function (stream) {
- try {
- if (stream.stream_ops.close) {
- stream.stream_ops.close(stream);
- }
- } catch (e) {
- throw e;
- } finally {
- FS.closeStream(stream.fd);
- }
- },
- llseek: function (stream, offset, whence) {
- if (!stream.seekable || !stream.stream_ops.llseek) {
- throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
- }
- return stream.stream_ops.llseek(stream, offset, whence);
- },
- read: function (stream, buffer, offset, length, position) {
- if (length < 0 || position < 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- if ((stream.flags & 2097155) === 1) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- if (FS.isDir(stream.node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
- }
- if (!stream.stream_ops.read) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var seeking = true;
- if (typeof position === 'undefined') {
- position = stream.position;
- seeking = false;
- } else if (!stream.seekable) {
- throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
- }
- var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
- if (!seeking) stream.position += bytesRead;
- return bytesRead;
- },
- write: function (stream, buffer, offset, length, position, canOwn) {
- if (length < 0 || position < 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- if ((stream.flags & 2097155) === 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- if (FS.isDir(stream.node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.EISDIR);
- }
- if (!stream.stream_ops.write) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var seeking = true;
- if (typeof position === 'undefined') {
- position = stream.position;
- seeking = false;
- } else if (!stream.seekable) {
- throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
- }
- if (stream.flags & 1024) {
- // seek to the end before writing in append mode
- FS.llseek(stream, 0, 2);
- }
- var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
- if (!seeking) stream.position += bytesWritten;
- return bytesWritten;
- },
- allocate: function (stream, offset, length) {
- if (offset < 0 || length <= 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- if ((stream.flags & 2097155) === 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EBADF);
- }
- if (!FS.isFile(stream.node.mode) && !FS.isDir(node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
- }
- if (!stream.stream_ops.allocate) {
- throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
- }
- stream.stream_ops.allocate(stream, offset, length);
- },
- mmap: function (stream, buffer, offset, length, position, prot, flags) {
- // TODO if PROT is PROT_WRITE, make sure we have write access
- if ((stream.flags & 2097155) === 1) {
- throw new FS.ErrnoError(ERRNO_CODES.EACCES);
- }
- if (!stream.stream_ops.mmap) {
- throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
- }
- return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
- },
- ioctl: function (stream, cmd, arg) {
- if (!stream.stream_ops.ioctl) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
- }
- return stream.stream_ops.ioctl(stream, cmd, arg);
- },
- readFile: function (path, opts) {
- opts = opts || {};
- opts.flags = opts.flags || 'r';
- opts.encoding = opts.encoding || 'binary';
- if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
- throw new Error('Invalid encoding type "' + opts.encoding + '"');
- }
- var ret;
- var stream = FS.open(path, opts.flags);
- var stat = FS.stat(path);
- var length = stat.size;
- var buf = new Uint8Array(length);
- FS.read(stream, buf, 0, length, 0);
- if (opts.encoding === 'utf8') {
- ret = '';
- var utf8 = new Runtime.UTF8Processor();
- for (var i = 0; i < length; i++) {
- ret += utf8.processCChar(buf[i]);
- }
- } else if (opts.encoding === 'binary') {
- ret = buf;
- }
- FS.close(stream);
- return ret;
- },
- writeFile: function (path, data, opts) {
- opts = opts || {};
- opts.flags = opts.flags || 'w';
- opts.encoding = opts.encoding || 'utf8';
- if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
- throw new Error('Invalid encoding type "' + opts.encoding + '"');
- }
- var stream = FS.open(path, opts.flags, opts.mode);
- if (opts.encoding === 'utf8') {
- var utf8 = new Runtime.UTF8Processor();
- var buf = new Uint8Array(utf8.processJSString(data));
- FS.write(stream, buf, 0, buf.length, 0, opts.canOwn);
- } else if (opts.encoding === 'binary') {
- FS.write(stream, data, 0, data.length, 0, opts.canOwn);
- }
- FS.close(stream);
- },
- cwd: function () {
- return FS.currentPath;
- },
- chdir: function (path) {
- var lookup = FS.lookupPath(path, {
- follow: true
- });
- if (!FS.isDir(lookup.node.mode)) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR);
- }
- var err = FS.nodePermissions(lookup.node, 'x');
- if (err) {
- throw new FS.ErrnoError(err);
- }
- FS.currentPath = lookup.path;
- },
- createDefaultDirectories: function () {
- FS.mkdir('/tmp');
- },
- createDefaultDevices: function () {
- // create /dev
- FS.mkdir('/dev');
- // setup /dev/null
- FS.registerDevice(FS.makedev(1, 3), {
- read: function () {
- return 0;
- },
- write: function () {
- return 0;
- }
- });
- FS.mkdev('/dev/null', FS.makedev(1, 3));
- // setup /dev/tty and /dev/tty1
- // stderr needs to print output using Module['printErr']
- // so we register a second tty just for it.
- TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
- TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
- FS.mkdev('/dev/tty', FS.makedev(5, 0));
- FS.mkdev('/dev/tty1', FS.makedev(6, 0));
- // we're not going to emulate the actual shm device,
- // just create the tmp dirs that reside in it commonly
- FS.mkdir('/dev/shm');
- FS.mkdir('/dev/shm/tmp');
- },
- createStandardStreams: function () {
- // TODO deprecate the old functionality of a single
- // input / output callback and that utilizes FS.createDevice
- // and instead require a unique set of stream ops
- // by default, we symlink the standard streams to the
- // default tty devices. however, if the standard streams
- // have been overwritten we create a unique device for
- // them instead.
- if (Module['stdin']) {
- FS.createDevice('/dev', 'stdin', Module['stdin']);
- } else {
- FS.symlink('/dev/tty', '/dev/stdin');
- }
- if (Module['stdout']) {
- FS.createDevice('/dev', 'stdout', null, Module['stdout']);
- } else {
- FS.symlink('/dev/tty', '/dev/stdout');
- }
- if (Module['stderr']) {
- FS.createDevice('/dev', 'stderr', null, Module['stderr']);
- } else {
- FS.symlink('/dev/tty1', '/dev/stderr');
- }
- // open default streams for the stdin, stdout and stderr devices
- var stdin = FS.open('/dev/stdin', 'r');
- HEAP32[((_stdin) >> 2)] = FS.getPtrForStream(stdin);
- assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
- var stdout = FS.open('/dev/stdout', 'w');
- HEAP32[((_stdout) >> 2)] = FS.getPtrForStream(stdout);
- assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
- var stderr = FS.open('/dev/stderr', 'w');
- HEAP32[((_stderr) >> 2)] = FS.getPtrForStream(stderr);
- assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
- },
- ensureErrnoError: function () {
- if (FS.ErrnoError) return;
- FS.ErrnoError = function ErrnoError(errno) {
- this.errno = errno;
- for (var key in ERRNO_CODES) {
- if (ERRNO_CODES[key] === errno) {
- this.code = key;
- break;
- }
- }
- this.message = ERRNO_MESSAGES[errno];
- };
- FS.ErrnoError.prototype = new Error();
- FS.ErrnoError.prototype.constructor = FS.ErrnoError;
- // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
- [ERRNO_CODES.ENOENT].forEach(function (code) {
- FS.genericErrors[code] = new FS.ErrnoError(code);
- FS.genericErrors[code].stack = '<generic error, no stack>';
- });
- },
- staticInit: function () {
- FS.ensureErrnoError();
- FS.nameTable = new Array(4096);
- FS.mount(MEMFS, {}, '/');
- FS.createDefaultDirectories();
- FS.createDefaultDevices();
- },
- init: function (input, output, error) {
- 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)');
- FS.init.initialized = true;
- FS.ensureErrnoError();
- // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
- Module['stdin'] = input || Module['stdin'];
- Module['stdout'] = output || Module['stdout'];
- Module['stderr'] = error || Module['stderr'];
- FS.createStandardStreams();
- },
- quit: function () {
- FS.init.initialized = false;
- for (var i = 0; i < FS.streams.length; i++) {
- var stream = FS.streams[i];
- if (!stream) {
- continue;
- }
- FS.close(stream);
- }
- },
- getMode: function (canRead, canWrite) {
- var mode = 0;
- if (canRead) mode |= 292 | 73;
- if (canWrite) mode |= 146;
- return mode;
- },
- joinPath: function (parts, forceRelative) {
- var path = PATH.join.apply(null, parts);
- if (forceRelative && path[0] == '/') path = path.substr(1);
- return path;
- },
- absolutePath: function (relative, base) {
- return PATH.resolve(base, relative);
- },
- standardizePath: function (path) {
- return PATH.normalize(path);
- },
- findObject: function (path, dontResolveLastLink) {
- var ret = FS.analyzePath(path, dontResolveLastLink);
- if (ret.exists) {
- return ret.object;
- } else {
- ___setErrNo(ret.error);
- return null;
- }
- },
- analyzePath: function (path, dontResolveLastLink) {
- // operate from within the context of the symlink's target
- try {
- var lookup = FS.lookupPath(path, {
- follow: !dontResolveLastLink
- });
- path = lookup.path;
- } catch (e) {}
- var ret = {
- isRoot: false,
- exists: false,
- error: 0,
- name: null,
- path: null,
- object: null,
- parentExists: false,
- parentPath: null,
- parentObject: null
- };
- try {
- var lookup = FS.lookupPath(path, {
- parent: true
- });
- ret.parentExists = true;
- ret.parentPath = lookup.path;
- ret.parentObject = lookup.node;
- ret.name = PATH.basename(path);
- lookup = FS.lookupPath(path, {
- follow: !dontResolveLastLink
- });
- ret.exists = true;
- ret.path = lookup.path;
- ret.object = lookup.node;
- ret.name = lookup.node.name;
- ret.isRoot = lookup.path === '/';
- } catch (e) {
- ret.error = e.errno;
- };
- return ret;
- },
- createFolder: function (parent, name, canRead, canWrite) {
- var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
- var mode = FS.getMode(canRead, canWrite);
- return FS.mkdir(path, mode);
- },
- createPath: function (parent, path, canRead, canWrite) {
- parent = typeof parent === 'string' ? parent : FS.getPath(parent);
- var parts = path.split('/').reverse();
- while (parts.length) {
- var part = parts.pop();
- if (!part) continue;
- var current = PATH.join2(parent, part);
- try {
- FS.mkdir(current);
- } catch (e) {
- // ignore EEXIST
- }
- parent = current;
- }
- return current;
- },
- createFile: function (parent, name, properties, canRead, canWrite) {
- var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
- var mode = FS.getMode(canRead, canWrite);
- return FS.create(path, mode);
- },
- createDataFile: function (parent, name, data, canRead, canWrite, canOwn) {
- var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
- var mode = FS.getMode(canRead, canWrite);
- var node = FS.create(path, mode);
- if (data) {
- if (typeof data === 'string') {
- var arr = new Array(data.length);
- for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
- data = arr;
- }
- // make sure we can write to the file
- FS.chmod(node, mode | 146);
- var stream = FS.open(node, 'w');
- FS.write(stream, data, 0, data.length, 0, canOwn);
- FS.close(stream);
- FS.chmod(node, mode);
- }
- return node;
- },
- createDevice: function (parent, name, input, output) {
- var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
- var mode = FS.getMode(!!input, !!output);
- if (!FS.createDevice.major) FS.createDevice.major = 64;
- var dev = FS.makedev(FS.createDevice.major++, 0);
- // Create a fake device that a set of stream ops to emulate
- // the old behavior.
- FS.registerDevice(dev, {
- open: function (stream) {
- stream.seekable = false;
- },
- close: function (stream) {
- // flush any pending line data
- if (output && output.buffer && output.buffer.length) {
- output(10);
- }
- },
- read: function (stream, buffer, offset, length, pos /* ignored */ ) {
- var bytesRead = 0;
- for (var i = 0; i < length; i++) {
- var result;
- try {
- result = input();
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- if (result === undefined && bytesRead === 0) {
- throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
- }
- if (result === null || result === undefined) break;
- bytesRead++;
- buffer[offset + i] = result;
- }
- if (bytesRead) {
- stream.node.timestamp = Date.now();
- }
- return bytesRead;
- },
- write: function (stream, buffer, offset, length, pos) {
- for (var i = 0; i < length; i++) {
- try {
- output(buffer[offset + i]);
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- }
- if (length) {
- stream.node.timestamp = Date.now();
- }
- return i;
- }
- });
- return FS.mkdev(path, mode, dev);
- },
- createLink: function (parent, name, target, canRead, canWrite) {
- var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
- return FS.symlink(target, path);
- },
- forceLoadFile: function (obj) {
- if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
- var success = true;
- if (typeof XMLHttpRequest !== 'undefined') {
- 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.");
- } else if (Module['read']) {
- // Command-line.
- try {
- // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
- // read() will try to parse UTF8.
- obj.contents = intArrayFromString(Module['read'](obj.url), true);
- } catch (e) {
- success = false;
- }
- } else {
- throw new Error('Cannot load without read() or XMLHttpRequest.');
- }
- if (!success) ___setErrNo(ERRNO_CODES.EIO);
- return success;
- },
- createLazyFile: function (parent, name, url, canRead, canWrite) {
- if (typeof XMLHttpRequest !== 'undefined') {
- if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
- // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
- function LazyUint8Array() {
- this.lengthKnown = false;
- this.chunks = []; // Loaded chunks. Index is the chunk number
- }
- LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
- if (idx > this.length - 1 || idx < 0) {
- return undefined;
- }
- var chunkOffset = idx % this.chunkSize;
- var chunkNum = Math.floor(idx / this.chunkSize);
- return this.getter(chunkNum)[chunkOffset];
- }
- LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
- this.getter = getter;
- }
- LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
- // Find length
- var xhr = new XMLHttpRequest();
- xhr.open('HEAD', url, false);
- xhr.send(null);
- if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
- var datalength = Number(xhr.getResponseHeader("Content-length"));
- var header;
- var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
- var chunkSize = 1024 * 1024; // Chunk size in bytes
- if (!hasByteServing) chunkSize = datalength;
- // Function to get a range from the remote URL.
- var doXHR = (function (from, to) {
- if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
- if (to > datalength - 1) throw new Error("only " + datalength + " bytes available! programmer error!");
- // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, false);
- if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
- // Some hints to the browser that we want binary data.
- if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
- if (xhr.overrideMimeType) {
- xhr.overrideMimeType('text/plain; charset=x-user-defined');
- }
- xhr.send(null);
- if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
- if (xhr.response !== undefined) {
- return new Uint8Array(xhr.response || []);
- } else {
- return intArrayFromString(xhr.responseText || '', true);
- }
- });
- var lazyArray = this;
- lazyArray.setDataGetter(function (chunkNum) {
- var start = chunkNum * chunkSize;
- var end = (chunkNum + 1) * chunkSize - 1; // including this byte
- end = Math.min(end, datalength - 1); // if datalength-1 is selected, this is the last block
- if (typeof (lazyArray.chunks[chunkNum]) === "undefined") {
- lazyArray.chunks[chunkNum] = doXHR(start, end);
- }
- if (typeof (lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
- return lazyArray.chunks[chunkNum];
- });
- this._length = datalength;
- this._chunkSize = chunkSize;
- this.lengthKnown = true;
- }
- var lazyArray = new LazyUint8Array();
- Object.defineProperty(lazyArray, "length", {
- get: function () {
- if (!this.lengthKnown) {
- this.cacheLength();
- }
- return this._length;
- }
- });
- Object.defineProperty(lazyArray, "chunkSize", {
- get: function () {
- if (!this.lengthKnown) {
- this.cacheLength();
- }
- return this._chunkSize;
- }
- });
- var properties = {
- isDevice: false,
- contents: lazyArray
- };
- } else {
- var properties = {
- isDevice: false,
- url: url
- };
- }
- var node = FS.createFile(parent, name, properties, canRead, canWrite);
- // This is a total hack, but I want to get this lazy file code out of the
- // core of MEMFS. If we want to keep this lazy file concept I feel it should
- // be its own thin LAZYFS proxying calls to MEMFS.
- if (properties.contents) {
- node.contents = properties.contents;
- } else if (properties.url) {
- node.contents = null;
- node.url = properties.url;
- }
- // override each stream op with one that tries to force load the lazy file first
- var stream_ops = {};
- var keys = Object.keys(node.stream_ops);
- keys.forEach(function (key) {
- var fn = node.stream_ops[key];
- stream_ops[key] = function forceLoadLazyFile() {
- if (!FS.forceLoadFile(node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- return fn.apply(null, arguments);
- };
- });
- // use a custom read function
- stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
- if (!FS.forceLoadFile(node)) {
- throw new FS.ErrnoError(ERRNO_CODES.EIO);
- }
- var contents = stream.node.contents;
- if (position >= contents.length)
- return 0;
- var size = Math.min(contents.length - position, length);
- assert(size >= 0);
- if (contents.slice) { // normal array
- for (var i = 0; i < size; i++) {
- buffer[offset + i] = contents[position + i];
- }
- } else {
- for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
- buffer[offset + i] = contents.get(position + i);
- }
- }
- return size;
- };
- node.stream_ops = stream_ops;
- return node;
- },
- createPreloadedFile: function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn) {
- Browser.init();
- // TODO we should allow people to just pass in a complete filename instead
- // of parent and name being that we just join them anyways
- var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent;
- function processData(byteArray) {
- function finish(byteArray) {
- if (!dontCreateFile) {
- FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
- }
- if (onload) onload();
- removeRunDependency('cp ' + fullname);
- }
- var handled = false;
- Module['preloadPlugins'].forEach(function (plugin) {
- if (handled) return;
- if (plugin['canHandle'](fullname)) {
- plugin['handle'](byteArray, fullname, finish, function () {
- if (onerror) onerror();
- removeRunDependency('cp ' + fullname);
- });
- handled = true;
- }
- });
- if (!handled) finish(byteArray);
- }
- addRunDependency('cp ' + fullname);
- if (typeof url == 'string') {
- Browser.asyncLoad(url, function (byteArray) {
- processData(byteArray);
- }, onerror);
- } else {
- processData(url);
- }
- },
- indexedDB: function () {
- return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
- },
- DB_NAME: function () {
- return 'EM_FS_' + window.location.pathname;
- },
- DB_VERSION: 20,
- DB_STORE_NAME: "FILE_DATA",
- saveFilesToDB: function (paths, onload, onerror) {
- onload = onload || function () {};
- onerror = onerror || function () {};
- var indexedDB = FS.indexedDB();
- try {
- var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
- } catch (e) {
- return onerror(e);
- }
- openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
- console.log('creating db');
- var db = openRequest.result;
- db.createObjectStore(FS.DB_STORE_NAME);
- };
- openRequest.onsuccess = function openRequest_onsuccess() {
- var db = openRequest.result;
- var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
- var files = transaction.objectStore(FS.DB_STORE_NAME);
- var ok = 0,
- fail = 0,
- total = paths.length;
- function finish() {
- if (fail == 0) onload();
- else onerror();
- }
- paths.forEach(function (path) {
- var putRequest = files.put(FS.analyzePath(path).object.contents, path);
- putRequest.onsuccess = function putRequest_onsuccess() {
- ok++;
- if (ok + fail == total) finish()
- };
- putRequest.onerror = function putRequest_onerror() {
- fail++;
- if (ok + fail == total) finish()
- };
- });
- transaction.onerror = onerror;
- };
- openRequest.onerror = onerror;
- },
- loadFilesFromDB: function (paths, onload, onerror) {
- onload = onload || function () {};
- onerror = onerror || function () {};
- var indexedDB = FS.indexedDB();
- try {
- var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
- } catch (e) {
- return onerror(e);
- }
- openRequest.onupgradeneeded = onerror; // no database to load from
- openRequest.onsuccess = function openRequest_onsuccess() {
- var db = openRequest.result;
- try {
- var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
- } catch (e) {
- onerror(e);
- return;
- }
- var files = transaction.objectStore(FS.DB_STORE_NAME);
- var ok = 0,
- fail = 0,
- total = paths.length;
- function finish() {
- if (fail == 0) onload();
- else onerror();
- }
- paths.forEach(function (path) {
- var getRequest = files.get(path);
- getRequest.onsuccess = function getRequest_onsuccess() {
- if (FS.analyzePath(path).exists) {
- FS.unlink(path);
- }
- FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
- ok++;
- if (ok + fail == total) finish();
- };
- getRequest.onerror = function getRequest_onerror() {
- fail++;
- if (ok + fail == total) finish()
- };
- });
- transaction.onerror = onerror;
- };
- openRequest.onerror = onerror;
- }
- };
- var PATH = {
- splitPath: function (filename) {
- var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
- return splitPathRe.exec(filename).slice(1);
- },
- normalizeArray: function (parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
- return parts;
- },
- normalize: function (path) {
- var isAbsolute = path.charAt(0) === '/',
- trailingSlash = path.substr(-1) === '/';
- // Normalize the path
- path = PATH.normalizeArray(path.split('/').filter(function (p) {
- return !!p;
- }), !isAbsolute).join('/');
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
- return (isAbsolute ? '/' : '') + path;
- },
- dirname: function (path) {
- var result = PATH.splitPath(path),
- root = result[0],
- dir = result[1];
- if (!root && !dir) {
- // No dirname whatsoever
- return '.';
- }
- if (dir) {
- // It has a dirname, strip trailing slash
- dir = dir.substr(0, dir.length - 1);
- }
- return root + dir;
- },
- basename: function (path) {
- // EMSCRIPTEN return '/'' for '/', not an empty string
- if (path === '/') return '/';
- var lastSlash = path.lastIndexOf('/');
- if (lastSlash === -1) return path;
- return path.substr(lastSlash + 1);
- },
- extname: function (path) {
- return PATH.splitPath(path)[3];
- },
- join: function () {
- var paths = Array.prototype.slice.call(arguments, 0);
- return PATH.normalize(paths.join('/'));
- },
- join2: function (l, r) {
- return PATH.normalize(l + '/' + r);
- },
- resolve: function () {
- var resolvedPath = '',
- resolvedAbsolute = false;
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : FS.cwd();
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
- resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function (p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
- },
- relative: function (from, to) {
- from = PATH.resolve(from).substr(1);
- to = PATH.resolve(to).substr(1);
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
- return outputParts.join('/');
- }
- };
- var Browser = {
- mainLoop: {
- scheduler: null,
- method: "",
- shouldPause: false,
- paused: false,
- queue: [],
- pause: function () {
- Browser.mainLoop.shouldPause = true;
- },
- resume: function () {
- if (Browser.mainLoop.paused) {
- Browser.mainLoop.paused = false;
- Browser.mainLoop.scheduler();
- }
- Browser.mainLoop.shouldPause = false;
- },
- updateStatus: function () {
- if (Module['setStatus']) {
- var message = Module['statusMessage'] || 'Please wait...';
- var remaining = Browser.mainLoop.remainingBlockers;
- var expected = Browser.mainLoop.expectedBlockers;
- if (remaining) {
- if (remaining < expected) {
- Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
- } else {
- Module['setStatus'](message);
- }
- } else {
- Module['setStatus']('');
- }
- }
- }
- },
- isFullScreen: false,
- pointerLock: false,
- moduleContextCreatedCallbacks: [],
- workers: [],
- init: function () {
- if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
- if (Browser.initted || ENVIRONMENT_IS_WORKER) return;
- Browser.initted = true;
- try {
- new Blob();
- Browser.hasBlobConstructor = true;
- } catch (e) {
- Browser.hasBlobConstructor = false;
- console.log("warning: no blob constructor, cannot create blobs with mimetypes");
- }
- Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
- Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
- if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
- console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
- Module.noImageDecoding = true;
- }
- // Support for plugins that can process preloaded files. You can add more of these to
- // your app by creating and appending to Module.preloadPlugins.
- //
- // Each plugin is asked if it can handle a file based on the file's name. If it can,
- // it is given the file's raw data. When it is done, it calls a callback with the file's
- // (possibly modified) data. For example, a plugin might decompress a file, or it
- // might create some side data structure for use later (like an Image element, etc.).
- var imagePlugin = {};
- imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
- return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
- };
- imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
- var b = null;
- if (Browser.hasBlobConstructor) {
- try {
- b = new Blob([byteArray], {
- type: Browser.getMimetype(name)
- });
- if (b.size !== byteArray.length) { // Safari bug #118630
- // Safari's Blob can only take an ArrayBuffer
- b = new Blob([(new Uint8Array(byteArray)).buffer], {
- type: Browser.getMimetype(name)
- });
- }
- } catch (e) {
- Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
- }
- }
- if (!b) {
- var bb = new Browser.BlobBuilder();
- bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
- b = bb.getBlob();
- }
- var url = Browser.URLObject.createObjectURL(b);
- var img = new Image();
- img.onload = function img_onload() {
- assert(img.complete, 'Image ' + name + ' could not be decoded');
- var canvas = document.createElement('canvas');
- canvas.width = img.width;
- canvas.height = img.height;
- var ctx = canvas.getContext('2d');
- ctx.drawImage(img, 0, 0);
- Module["preloadedImages"][name] = canvas;
- Browser.URLObject.revokeObjectURL(url);
- if (onload) onload(byteArray);
- };
- img.onerror = function img_onerror(event) {
- console.log('Image ' + url + ' could not be decoded');
- if (onerror) onerror();
- };
- img.src = url;
- };
- Module['preloadPlugins'].push(imagePlugin);
- var audioPlugin = {};
- audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
- return !Module.noAudioDecoding && name.substr(-4) in {
- '.ogg': 1,
- '.wav': 1,
- '.mp3': 1
- };
- };
- audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
- var done = false;
- function finish(audio) {
- if (done) return;
- done = true;
- Module["preloadedAudios"][name] = audio;
- if (onload) onload(byteArray);
- }
- function fail() {
- if (done) return;
- done = true;
- Module["preloadedAudios"][name] = new Audio(); // empty shim
- if (onerror) onerror();
- }
- if (Browser.hasBlobConstructor) {
- try {
- var b = new Blob([byteArray], {
- type: Browser.getMimetype(name)
- });
- } catch (e) {
- return fail();
- }
- var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
- var audio = new Audio();
- audio.addEventListener('canplaythrough', function () {
- finish(audio)
- }, false); // use addEventListener due to chromium bug 124926
- audio.onerror = function audio_onerror(event) {
- if (done) return;
- console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
- function encode64(data) {
- var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- var PAD = '=';
- var ret = '';
- var leftchar = 0;
- var leftbits = 0;
- for (var i = 0; i < data.length; i++) {
- leftchar = (leftchar << 8) | data[i];
- leftbits += 8;
- while (leftbits >= 6) {
- var curr = (leftchar >> (leftbits - 6)) & 0x3f;
- leftbits -= 6;
- ret += BASE[curr];
- }
- }
- if (leftbits == 2) {
- ret += BASE[(leftchar & 3) << 4];
- ret += PAD + PAD;
- } else if (leftbits == 4) {
- ret += BASE[(leftchar & 0xf) << 2];
- ret += PAD;
- }
- return ret;
- }
- audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
- finish(audio); // we don't wait for confirmation this worked - but it's worth trying
- };
- audio.src = url;
- // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
- Browser.safeSetTimeout(function () {
- finish(audio); // try to use it even though it is not necessarily ready to play
- }, 10000);
- } else {
- return fail();
- }
- };
- Module['preloadPlugins'].push(audioPlugin);
- // Canvas event setup
- var canvas = Module['canvas'];
- // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
- // Module['forcedAspectRatio'] = 4 / 3;
- canvas.requestPointerLock = canvas['requestPointerLock'] ||
- canvas['mozRequestPointerLock'] ||
- canvas['webkitRequestPointerLock'] ||
- canvas['msRequestPointerLock'] ||
- function () {};
- canvas.exitPointerLock = document['exitPointerLock'] ||
- document['mozExitPointerLock'] ||
- document['webkitExitPointerLock'] ||
- document['msExitPointerLock'] ||
- function () {}; // no-op if function does not exist
- canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
- function pointerLockChange() {
- Browser.pointerLock = document['pointerLockElement'] === canvas ||
- document['mozPointerLockElement'] === canvas ||
- document['webkitPointerLockElement'] === canvas ||
- document['msPointerLockElement'] === canvas;
- }
- document.addEventListener('pointerlockchange', pointerLockChange, false);
- document.addEventListener('mozpointerlockchange', pointerLockChange, false);
- document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
- document.addEventListener('mspointerlockchange', pointerLockChange, false);
- if (Module['elementPointerLock']) {
- canvas.addEventListener("click", function (ev) {
- if (!Browser.pointerLock && canvas.requestPointerLock) {
- canvas.requestPointerLock();
- ev.preventDefault();
- }
- }, false);
- }
- },
- createContext: function (canvas, useWebGL, setInModule, webGLContextAttributes) {
- var ctx;
- var errorInfo = '?';
- function onContextCreationError(event) {
- errorInfo = event.statusMessage || errorInfo;
- }
- try {
- if (useWebGL) {
- var contextAttributes = {
- antialias: false,
- alpha: false
- };
- if (webGLContextAttributes) {
- for (var attribute in webGLContextAttributes) {
- contextAttributes[attribute] = webGLContextAttributes[attribute];
- }
- }
- canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
- try {
- ['experimental-webgl', 'webgl'].some(function (webglId) {
- return ctx = canvas.getContext(webglId, contextAttributes);
- });
- } finally {
- canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
- }
- } else {
- ctx = canvas.getContext('2d');
- }
- if (!ctx) throw ':(';
- } catch (e) {
- Module.print('Could not create canvas: ' + [errorInfo, e]);
- return null;
- }
- if (useWebGL) {
- // Set the background of the WebGL canvas to black
- canvas.style.backgroundColor = "black";
- // Warn on context loss
- canvas.addEventListener('webglcontextlost', function (event) {
- alert('WebGL context lost. You will need to reload the page.');
- }, false);
- }
- if (setInModule) {
- GLctx = Module.ctx = ctx;
- Module.useWebGL = useWebGL;
- Browser.moduleContextCreatedCallbacks.forEach(function (callback) {
- callback()
- });
- Browser.init();
- }
- return ctx;
- },
- destroyContext: function (canvas, useWebGL, setInModule) {},
- fullScreenHandlersInstalled: false,
- lockPointer: undefined,
- resizeCanvas: undefined,
- requestFullScreen: function (lockPointer, resizeCanvas) {
- Browser.lockPointer = lockPointer;
- Browser.resizeCanvas = resizeCanvas;
- if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
- if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
- var canvas = Module['canvas'];
- var canvasContainer = canvas.parentNode;
- function fullScreenChange() {
- Browser.isFullScreen = false;
- if ((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
- document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
- document['fullScreenElement'] || document['fullscreenElement'] ||
- document['msFullScreenElement'] || document['msFullscreenElement'] ||
- document['webkitCurrentFullScreenElement']) === canvasContainer) {
- canvas.cancelFullScreen = document['cancelFullScreen'] ||
- document['mozCancelFullScreen'] ||
- document['webkitCancelFullScreen'] ||
- document['msExitFullscreen'] ||
- document['exitFullscreen'] ||
- function () {};
- canvas.cancelFullScreen = canvas.cancelFullScreen.bind(document);
- if (Browser.lockPointer) canvas.requestPointerLock();
- Browser.isFullScreen = true;
- if (Browser.resizeCanvas) Browser.setFullScreenCanvasSize();
- } else {
- // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
- var canvasContainer = canvas.parentNode;
- canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
- canvasContainer.parentNode.removeChild(canvasContainer);
- if (Browser.resizeCanvas) Browser.setWindowedCanvasSize();
- }
- if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullScreen);
- Browser.updateCanvasDimensions(canvas);
- }
- if (!Browser.fullScreenHandlersInstalled) {
- Browser.fullScreenHandlersInstalled = true;
- document.addEventListener('fullscreenchange', fullScreenChange, false);
- document.addEventListener('mozfullscreenchange', fullScreenChange, false);
- document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
- document.addEventListener('MSFullscreenChange', fullScreenChange, false);
- }
- // 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
- var canvasContainer = document.createElement("div");
- canvas.parentNode.insertBefore(canvasContainer, canvas);
- canvasContainer.appendChild(canvas);
- // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
- canvasContainer.requestFullScreen = canvasContainer['requestFullScreen'] ||
- canvasContainer['mozRequestFullScreen'] ||
- canvasContainer['msRequestFullscreen'] ||
- (canvasContainer['webkitRequestFullScreen'] ? function () {
- canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT'])
- } : null);
- canvasContainer.requestFullScreen();
- },
- requestAnimationFrame: function requestAnimationFrame(func) {
- if (typeof window === 'undefined') { // Provide fallback to setTimeout if window is undefined (e.g. in Node.js)
- setTimeout(func, 1000 / 60);
- } else {
- if (!window.requestAnimationFrame) {
- window.requestAnimationFrame = window['requestAnimationFrame'] ||
- window['mozRequestAnimationFrame'] ||
- window['webkitRequestAnimationFrame'] ||
- window['msRequestAnimationFrame'] ||
- window['oRequestAnimationFrame'] ||
- window['setTimeout'];
- }
- window.requestAnimationFrame(func);
- }
- },
- safeCallback: function (func) {
- return function () {
- if (!ABORT) return func.apply(null, arguments);
- };
- },
- safeRequestAnimationFrame: function (func) {
- return Browser.requestAnimationFrame(function () {
- if (!ABORT) func();
- });
- },
- safeSetTimeout: function (func, timeout) {
- return setTimeout(function () {
- if (!ABORT) func();
- }, timeout);
- },
- safeSetInterval: function (func, timeout) {
- return setInterval(function () {
- if (!ABORT) func();
- }, timeout);
- },
- getMimetype: function (name) {
- return {
- 'jpg': 'image/jpeg',
- 'jpeg': 'image/jpeg',
- 'png': 'image/png',
- 'bmp': 'image/bmp',
- 'ogg': 'audio/ogg',
- 'wav': 'audio/wav',
- 'mp3': 'audio/mpeg'
- }[name.substr(name.lastIndexOf('.') + 1)];
- },
- getUserMedia: function (func) {
- if (!window.getUserMedia) {
- window.getUserMedia = navigator['getUserMedia'] ||
- navigator['mozGetUserMedia'];
- }
- window.getUserMedia(func);
- },
- getMovementX: function (event) {
- return event['movementX'] ||
- event['mozMovementX'] ||
- event['webkitMovementX'] ||
- 0;
- },
- getMovementY: function (event) {
- return event['movementY'] ||
- event['mozMovementY'] ||
- event['webkitMovementY'] ||
- 0;
- },
- getMouseWheelDelta: function (event) {
- return Math.max(-1, Math.min(1, event.type === 'DOMMouseScroll' ? event.detail : -event.wheelDelta));
- },
- mouseX: 0,
- mouseY: 0,
- mouseMovementX: 0,
- mouseMovementY: 0,
- calculateMouseEvent: function (event) { // event should be mousemove, mousedown or mouseup
- if (Browser.pointerLock) {
- // When the pointer is locked, calculate the coordinates
- // based on the movement of the mouse.
- // Workaround for Firefox bug 764498
- if (event.type != 'mousemove' &&
- ('mozMovementX' in event)) {
- Browser.mouseMovementX = Browser.mouseMovementY = 0;
- } else {
- Browser.mouseMovementX = Browser.getMovementX(event);
- Browser.mouseMovementY = Browser.getMovementY(event);
- }
- // check if SDL is available
- if (typeof SDL != "undefined") {
- Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
- Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
- } else {
- // just add the mouse delta to the current absolut mouse position
- // FIXME: ideally this should be clamped against the canvas size and zero
- Browser.mouseX += Browser.mouseMovementX;
- Browser.mouseY += Browser.mouseMovementY;
- }
- } else {
- // Otherwise, calculate the movement based on the changes
- // in the coordinates.
- var rect = Module["canvas"].getBoundingClientRect();
- var x, y;
- // Neither .scrollX or .pageXOffset are defined in a spec, but
- // we prefer .scrollX because it is currently in a spec draft.
- // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
- var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
- var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
- if (event.type == 'touchstart' ||
- event.type == 'touchend' ||
- event.type == 'touchmove') {
- var t = event.touches.item(0);
- if (t) {
- x = t.pageX - (scrollX + rect.left);
- y = t.pageY - (scrollY + rect.top);
- } else {
- return;
- }
- } else {
- x = event.pageX - (scrollX + rect.left);
- y = event.pageY - (scrollY + rect.top);
- }
- // the canvas might be CSS-scaled compared to its backbuffer;
- // SDL-using content will want mouse coordinates in terms
- // of backbuffer units.
- var cw = Module["canvas"].width;
- var ch = Module["canvas"].height;
- x = x * (cw / rect.width);
- y = y * (ch / rect.height);
- Browser.mouseMovementX = x - Browser.mouseX;
- Browser.mouseMovementY = y - Browser.mouseY;
- Browser.mouseX = x;
- Browser.mouseY = y;
- }
- },
- xhrLoad: function (url, onload, onerror) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.responseType = 'arraybuffer';
- xhr.onload = function xhr_onload() {
- if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
- onload(xhr.response);
- } else {
- onerror();
- }
- };
- xhr.onerror = onerror;
- xhr.send(null);
- },
- asyncLoad: function (url, onload, onerror, noRunDep) {
- Browser.xhrLoad(url, function (arrayBuffer) {
- assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
- onload(new Uint8Array(arrayBuffer));
- if (!noRunDep) removeRunDependency('al ' + url);
- }, function (event) {
- if (onerror) {
- onerror();
- } else {
- throw 'Loading data file "' + url + '" failed.';
- }
- });
- if (!noRunDep) addRunDependency('al ' + url);
- },
- resizeListeners: [],
- updateResizeListeners: function () {
- var canvas = Module['canvas'];
- Browser.resizeListeners.forEach(function (listener) {
- listener(canvas.width, canvas.height);
- });
- },
- setCanvasSize: function (width, height, noUpdates) {
- var canvas = Module['canvas'];
- Browser.updateCanvasDimensions(canvas, width, height);
- if (!noUpdates) Browser.updateResizeListeners();
- },
- windowedWidth: 0,
- windowedHeight: 0,
- setFullScreenCanvasSize: function () {
- // check if SDL is available
- if (typeof SDL != "undefined") {
- var flags = HEAPU32[((SDL.screen + Runtime.QUANTUM_SIZE * 0) >> 2)];
- flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
- HEAP32[((SDL.screen + Runtime.QUANTUM_SIZE * 0) >> 2)] = flags
- }
- Browser.updateResizeListeners();
- },
- setWindowedCanvasSize: function () {
- // check if SDL is available
- if (typeof SDL != "undefined") {
- var flags = HEAPU32[((SDL.screen + Runtime.QUANTUM_SIZE * 0) >> 2)];
- flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
- HEAP32[((SDL.screen + Runtime.QUANTUM_SIZE * 0) >> 2)] = flags
- }
- Browser.updateResizeListeners();
- },
- updateCanvasDimensions: function (canvas, wNative, hNative) {
- if (wNative && hNative) {
- canvas.widthNative = wNative;
- canvas.heightNative = hNative;
- } else {
- wNative = canvas.widthNative;
- hNative = canvas.heightNative;
- }
- var w = wNative;
- var h = hNative;
- if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
- if (w / h < Module['forcedAspectRatio']) {
- w = Math.round(h * Module['forcedAspectRatio']);
- } else {
- h = Math.round(w / Module['forcedAspectRatio']);
- }
- }
- if (((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
- document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
- document['fullScreenElement'] || document['fullscreenElement'] ||
- document['msFullScreenElement'] || document['msFullscreenElement'] ||
- document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
- var factor = Math.min(screen.width / w, screen.height / h);
- w = Math.round(w * factor);
- h = Math.round(h * factor);
- }
- if (Browser.resizeCanvas) {
- if (canvas.width != w) canvas.width = w;
- if (canvas.height != h) canvas.height = h;
- if (typeof canvas.style != 'undefined') {
- canvas.style.removeProperty("width");
- canvas.style.removeProperty("height");
- }
- } else {
- if (canvas.width != wNative) canvas.width = wNative;
- if (canvas.height != hNative) canvas.height = hNative;
- if (typeof canvas.style != 'undefined') {
- if (w != wNative || h != hNative) {
- canvas.style.setProperty("width", w + "px", "important");
- canvas.style.setProperty("height", h + "px", "important");
- } else {
- canvas.style.removeProperty("width");
- canvas.style.removeProperty("height");
- }
- }
- }
- }
- };
- var _sqrt = Math_sqrt;
- function _mkport() {
- throw 'TODO'
- }
- var SOCKFS = {
- mount: function (mount) {
- return FS.createNode(null, '/', 16384 | 511 /* 0777 */ , 0);
- },
- createSocket: function (family, type, protocol) {
- var streaming = type == 1;
- if (protocol) {
- assert(streaming == (protocol == 6)); // if SOCK_STREAM, must be tcp
- }
- // create our internal socket structure
- var sock = {
- family: family,
- type: type,
- protocol: protocol,
- server: null,
- peers: {},
- pending: [],
- recv_queue: [],
- sock_ops: SOCKFS.websocket_sock_ops
- };
- // create the filesystem node to store the socket structure
- var name = SOCKFS.nextname();
- var node = FS.createNode(SOCKFS.root, name, 49152, 0);
- node.sock = sock;
- // and the wrapping stream that enables library functions such
- // as read and write to indirectly interact with the socket
- var stream = FS.createStream({
- path: name,
- node: node,
- flags: FS.modeStringToFlags('r+'),
- seekable: false,
- stream_ops: SOCKFS.stream_ops
- });
- // map the new stream to the socket structure (sockets have a 1:1
- // relationship with a stream)
- sock.stream = stream;
- return sock;
- },
- getSocket: function (fd) {
- var stream = FS.getStream(fd);
- if (!stream || !FS.isSocket(stream.node.mode)) {
- return null;
- }
- return stream.node.sock;
- },
- stream_ops: {
- poll: function (stream) {
- var sock = stream.node.sock;
- return sock.sock_ops.poll(sock);
- },
- ioctl: function (stream, request, varargs) {
- var sock = stream.node.sock;
- return sock.sock_ops.ioctl(sock, request, varargs);
- },
- read: function (stream, buffer, offset, length, position /* ignored */ ) {
- var sock = stream.node.sock;
- var msg = sock.sock_ops.recvmsg(sock, length);
- if (!msg) {
- // socket is closed
- return 0;
- }
- buffer.set(msg.buffer, offset);
- return msg.buffer.length;
- },
- write: function (stream, buffer, offset, length, position /* ignored */ ) {
- var sock = stream.node.sock;
- return sock.sock_ops.sendmsg(sock, buffer, offset, length);
- },
- close: function (stream) {
- var sock = stream.node.sock;
- sock.sock_ops.close(sock);
- }
- },
- nextname: function () {
- if (!SOCKFS.nextname.current) {
- SOCKFS.nextname.current = 0;
- }
- return 'socket[' + (SOCKFS.nextname.current++) + ']';
- },
- websocket_sock_ops: {
- createPeer: function (sock, addr, port) {
- var ws;
- if (typeof addr === 'object') {
- ws = addr;
- addr = null;
- port = null;
- }
- if (ws) {
- // for sockets that've already connected (e.g. we're the server)
- // we can inspect the _socket property for the address
- if (ws._socket) {
- addr = ws._socket.remoteAddress;
- port = ws._socket.remotePort;
- }
- // if we're just now initializing a connection to the remote,
- // inspect the url property
- else {
- var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
- if (!result) {
- throw new Error('WebSocket URL must be in the format ws(s)://address:port');
- }
- addr = result[1];
- port = parseInt(result[2], 10);
- }
- } else {
- // create the actual websocket object and connect
- try {
- var url = 'ws://' + addr + ':' + port;
- // the node ws library API is slightly different than the browser's
- var opts = ENVIRONMENT_IS_NODE ? {
- headers: {
- 'websocket-protocol': ['binary']
- }
- } : ['binary'];
- // If node we use the ws library.
- var WebSocket = ENVIRONMENT_IS_NODE ? require('ws') : window['WebSocket'];
- ws = new WebSocket(url, opts);
- ws.binaryType = 'arraybuffer';
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH);
- }
- }
- var peer = {
- addr: addr,
- port: port,
- socket: ws,
- dgram_send_queue: []
- };
- SOCKFS.websocket_sock_ops.addPeer(sock, peer);
- SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
- // if this is a bound dgram socket, send the port number first to allow
- // us to override the ephemeral port reported to us by remotePort on the
- // remote end.
- if (sock.type === 2 && typeof sock.sport !== 'undefined') {
- peer.dgram_send_queue.push(new Uint8Array([
- 255, 255, 255, 255,
- 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0), ((sock.sport & 0xff00) >> 8), (sock.sport & 0xff)
- ]));
- }
- return peer;
- },
- getPeer: function (sock, addr, port) {
- return sock.peers[addr + ':' + port];
- },
- addPeer: function (sock, peer) {
- sock.peers[peer.addr + ':' + peer.port] = peer;
- },
- removePeer: function (sock, peer) {
- delete sock.peers[peer.addr + ':' + peer.port];
- },
- handlePeerEvents: function (sock, peer) {
- var first = true;
- var handleOpen = function () {
- try {
- var queued = peer.dgram_send_queue.shift();
- while (queued) {
- peer.socket.send(queued);
- queued = peer.dgram_send_queue.shift();
- }
- } catch (e) {
- // not much we can do here in the way of proper error handling as we've already
- // lied and said this data was sent. shut it down.
- peer.socket.close();
- }
- };
- function handleMessage(data) {
- assert(typeof data !== 'string' && data.byteLength !== undefined); // must receive an ArrayBuffer
- data = new Uint8Array(data); // make a typed array view on the array buffer
- // if this is the port message, override the peer's port with it
- var wasfirst = first;
- first = false;
- if (wasfirst &&
- data.length === 10 &&
- data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
- data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) && data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
- // update the peer's port and it's key in the peer map
- var newport = ((data[8] << 8) | data[9]);
- SOCKFS.websocket_sock_ops.removePeer(sock, peer);
- peer.port = newport;
- SOCKFS.websocket_sock_ops.addPeer(sock, peer);
- return;
- }
- sock.recv_queue.push({
- addr: peer.addr,
- port: peer.port,
- data: data
- });
- };
- if (ENVIRONMENT_IS_NODE) {
- peer.socket.on('open', handleOpen);
- peer.socket.on('message', function (data, flags) {
- if (!flags.binary) {
- return;
- }
- handleMessage((new Uint8Array(data)).buffer); // copy from node Buffer -> ArrayBuffer
- });
- peer.socket.on('error', function () {
- // don't throw
- });
- } else {
- peer.socket.onopen = handleOpen;
- peer.socket.onmessage = function peer_socket_onmessage(event) {
- handleMessage(event.data);
- };
- }
- },
- poll: function (sock) {
- if (sock.type === 1 && sock.server) {
- // listen sockets should only say they're available for reading
- // if there are pending clients.
- return sock.pending.length ? (64 | 1) : 0;
- }
- var mask = 0;
- var dest = sock.type === 1 ? // we only care about the socket state for connection-based sockets
- SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
- null;
- if (sock.recv_queue.length ||
- !dest || // connection-less sockets are always ready to read
- (dest && dest.socket.readyState === dest.socket.CLOSING) ||
- (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
- mask |= (64 | 1);
- }
- if (!dest || // connection-less sockets are always ready to write
- (dest && dest.socket.readyState === dest.socket.OPEN)) {
- mask |= 4;
- }
- if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
- (dest && dest.socket.readyState === dest.socket.CLOSED)) {
- mask |= 16;
- }
- return mask;
- },
- ioctl: function (sock, request, arg) {
- switch (request) {
- case 21531:
- var bytes = 0;
- if (sock.recv_queue.length) {
- bytes = sock.recv_queue[0].data.length;
- }
- HEAP32[((arg) >> 2)] = bytes;
- return 0;
- default:
- return ERRNO_CODES.EINVAL;
- }
- },
- close: function (sock) {
- // if we've spawned a listen server, close it
- if (sock.server) {
- try {
- sock.server.close();
- } catch (e) {}
- sock.server = null;
- }
- // close any peer connections
- var peers = Object.keys(sock.peers);
- for (var i = 0; i < peers.length; i++) {
- var peer = sock.peers[peers[i]];
- try {
- peer.socket.close();
- } catch (e) {}
- SOCKFS.websocket_sock_ops.removePeer(sock, peer);
- }
- return 0;
- },
- bind: function (sock, addr, port) {
- if (typeof sock.saddr !== 'undefined' || typeof sock.sport !== 'undefined') {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already bound
- }
- sock.saddr = addr;
- sock.sport = port || _mkport();
- // in order to emulate dgram sockets, we need to launch a listen server when
- // binding on a connection-less socket
- // note: this is only required on the server side
- if (sock.type === 2) {
- // close the existing server if it exists
- if (sock.server) {
- sock.server.close();
- sock.server = null;
- }
- // swallow error operation not supported error that occurs when binding in the
- // browser where this isn't supported
- try {
- sock.sock_ops.listen(sock, 0);
- } catch (e) {
- if (!(e instanceof FS.ErrnoError)) throw e;
- if (e.errno !== ERRNO_CODES.EOPNOTSUPP) throw e;
- }
- }
- },
- connect: function (sock, addr, port) {
- if (sock.server) {
- throw new FS.ErrnoError(ERRNO_CODS.EOPNOTSUPP);
- }
- // TODO autobind
- // if (!sock.addr && sock.type == 2) {
- // }
- // early out if we're already connected / in the middle of connecting
- if (typeof sock.daddr !== 'undefined' && typeof sock.dport !== 'undefined') {
- var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
- if (dest) {
- if (dest.socket.readyState === dest.socket.CONNECTING) {
- throw new FS.ErrnoError(ERRNO_CODES.EALREADY);
- } else {
- throw new FS.ErrnoError(ERRNO_CODES.EISCONN);
- }
- }
- }
- // add the socket to our peer list and set our
- // destination address / port to match
- var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
- sock.daddr = peer.addr;
- sock.dport = peer.port;
- // always "fail" in non-blocking mode
- throw new FS.ErrnoError(ERRNO_CODES.EINPROGRESS);
- },
- listen: function (sock, backlog) {
- if (!ENVIRONMENT_IS_NODE) {
- throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
- }
- if (sock.server) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL); // already listening
- }
- var WebSocketServer = require('ws').Server;
- var host = sock.saddr;
- sock.server = new WebSocketServer({
- host: host,
- port: sock.sport
- // TODO support backlog
- });
- sock.server.on('connection', function (ws) {
- if (sock.type === 1) {
- var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
- // create a peer on the new socket
- var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
- newsock.daddr = peer.addr;
- newsock.dport = peer.port;
- // push to queue for accept to pick up
- sock.pending.push(newsock);
- } else {
- // create a peer on the listen socket so calling sendto
- // with the listen socket and an address will resolve
- // to the correct client
- SOCKFS.websocket_sock_ops.createPeer(sock, ws);
- }
- });
- sock.server.on('closed', function () {
- sock.server = null;
- });
- sock.server.on('error', function () {
- // don't throw
- });
- },
- accept: function (listensock) {
- if (!listensock.server) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- var newsock = listensock.pending.shift();
- newsock.stream.flags = listensock.stream.flags;
- return newsock;
- },
- getname: function (sock, peer) {
- var addr, port;
- if (peer) {
- if (sock.daddr === undefined || sock.dport === undefined) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
- }
- addr = sock.daddr;
- port = sock.dport;
- } else {
- // TODO saddr and sport will be set for bind()'d UDP sockets, but what
- // should we be returning for TCP sockets that've been connect()'d?
- addr = sock.saddr || 0;
- port = sock.sport || 0;
- }
- return {
- addr: addr,
- port: port
- };
- },
- sendmsg: function (sock, buffer, offset, length, addr, port) {
- if (sock.type === 2) {
- // connection-less sockets will honor the message address,
- // and otherwise fall back to the bound destination address
- if (addr === undefined || port === undefined) {
- addr = sock.daddr;
- port = sock.dport;
- }
- // if there was no address to fall back to, error out
- if (addr === undefined || port === undefined) {
- throw new FS.ErrnoError(ERRNO_CODES.EDESTADDRREQ);
- }
- } else {
- // connection-based sockets will only use the bound
- addr = sock.daddr;
- port = sock.dport;
- }
- // find the peer for the destination address
- var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
- // early out if not connected with a connection-based socket
- if (sock.type === 1) {
- if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
- throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
- } else if (dest.socket.readyState === dest.socket.CONNECTING) {
- throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
- }
- }
- // create a copy of the incoming data to send, as the WebSocket API
- // doesn't work entirely with an ArrayBufferView, it'll just send
- // the entire underlying buffer
- var data;
- if (buffer instanceof Array || buffer instanceof ArrayBuffer) {
- data = buffer.slice(offset, offset + length);
- } else { // ArrayBufferView
- data = buffer.buffer.slice(buffer.byteOffset + offset, buffer.byteOffset + offset + length);
- }
- // if we're emulating a connection-less dgram socket and don't have
- // a cached connection, queue the buffer to send upon connect and
- // lie, saying the data was sent now.
- if (sock.type === 2) {
- if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
- // if we're not connected, open a new connection
- if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
- dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
- }
- dest.dgram_send_queue.push(data);
- return length;
- }
- }
- try {
- // send the actual data
- dest.socket.send(data);
- return length;
- } catch (e) {
- throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
- }
- },
- recvmsg: function (sock, length) {
- // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
- if (sock.type === 1 && sock.server) {
- // tcp servers should not be recv()'ing on the listen socket
- throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
- }
- var queued = sock.recv_queue.shift();
- if (!queued) {
- if (sock.type === 1) {
- var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
- if (!dest) {
- // if we have a destination address but are not connected, error out
- throw new FS.ErrnoError(ERRNO_CODES.ENOTCONN);
- } else if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
- // return null if the socket has closed
- return null;
- } else {
- // else, our socket is in a valid state but truly has nothing available
- throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
- }
- } else {
- throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
- }
- }
- // queued.data will be an ArrayBuffer if it's unadulterated, but if it's
- // requeued TCP data it'll be an ArrayBufferView
- var queuedLength = queued.data.byteLength || queued.data.length;
- var queuedOffset = queued.data.byteOffset || 0;
- var queuedBuffer = queued.data.buffer || queued.data;
- var bytesRead = Math.min(length, queuedLength);
- var res = {
- buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
- addr: queued.addr,
- port: queued.port
- };
- // push back any unread data for TCP connections
- if (sock.type === 1 && bytesRead < queuedLength) {
- var bytesRemaining = queuedLength - bytesRead;
- queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
- sock.recv_queue.unshift(queued);
- }
- return res;
- }
- }
- };
- function _send(fd, buf, len, flags) {
- var sock = SOCKFS.getSocket(fd);
- if (!sock) {
- ___setErrNo(ERRNO_CODES.EBADF);
- return -1;
- }
- // TODO honor flags
- return _write(fd, buf, len);
- }
- function _pwrite(fildes, buf, nbyte, offset) {
- // ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
- var stream = FS.getStream(fildes);
- if (!stream) {
- ___setErrNo(ERRNO_CODES.EBADF);
- return -1;
- }
- try {
- var slab = HEAP8;
- return FS.write(stream, slab, buf, nbyte, offset);
- } catch (e) {
- FS.handleFSError(e);
- return -1;
- }
- }
- function _write(fildes, buf, nbyte) {
- // ssize_t write(int fildes, const void *buf, size_t nbyte);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/write.html
- var stream = FS.getStream(fildes);
- if (!stream) {
- ___setErrNo(ERRNO_CODES.EBADF);
- return -1;
- }
- try {
- var slab = HEAP8;
- return FS.write(stream, slab, buf, nbyte);
- } catch (e) {
- FS.handleFSError(e);
- return -1;
- }
- }
- function _fileno(stream) {
- // int fileno(FILE *stream);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/fileno.html
- stream = FS.getStreamFromPtr(stream);
- if (!stream) return -1;
- return stream.fd;
- }
- function _fwrite(ptr, size, nitems, stream) {
- // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/fwrite.html
- var bytesToWrite = nitems * size;
- if (bytesToWrite == 0) return 0;
- var fd = _fileno(stream);
- var bytesWritten = _write(fd, ptr, bytesToWrite);
- if (bytesWritten == -1) {
- var streamObj = FS.getStreamFromPtr(stream);
- if (streamObj) streamObj.error = true;
- return 0;
- } else {
- return Math.floor(bytesWritten / size);
- }
- }
- Module["_strlen"] = _strlen;
- function __reallyNegative(x) {
- return x < 0 || (x === 0 && (1 / x) === -Infinity);
- }
- function __formatString(format, varargs) {
- var textIndex = format;
- var argIndex = 0;
- function getNextArg(type) {
- // NOTE: Explicitly ignoring type safety. Otherwise this fails:
- // int x = 4; printf("%c\n", (char)x);
- var ret;
- if (type === 'double') {
- ret = (HEAP32[((tempDoublePtr) >> 2)] = HEAP32[(((varargs) + (argIndex)) >> 2)], HEAP32[(((tempDoublePtr) + (4)) >> 2)] = HEAP32[(((varargs) + ((argIndex) + (4))) >> 2)], (+(HEAPF64[(tempDoublePtr) >> 3])));
- } else if (type == 'i64') {
- ret = [HEAP32[(((varargs) + (argIndex)) >> 2)],
- HEAP32[(((varargs) + (argIndex + 4)) >> 2)]
- ];
- } else {
- type = 'i32'; // varargs are always i32, i64, or double
- ret = HEAP32[(((varargs) + (argIndex)) >> 2)];
- }
- argIndex += Runtime.getNativeFieldSize(type);
- return ret;
- }
- var ret = [];
- var curr, next, currArg;
- while (1) {
- var startTextIndex = textIndex;
- curr = HEAP8[(textIndex)];
- if (curr === 0) break;
- next = HEAP8[((textIndex + 1) | 0)];
- if (curr == 37) {
- // Handle flags.
- var flagAlwaysSigned = false;
- var flagLeftAlign = false;
- var flagAlternative = false;
- var flagZeroPad = false;
- var flagPadSign = false;
- flagsLoop: while (1) {
- switch (next) {
- case 43:
- flagAlwaysSigned = true;
- break;
- case 45:
- flagLeftAlign = true;
- break;
- case 35:
- flagAlternative = true;
- break;
- case 48:
- if (flagZeroPad) {
- break flagsLoop;
- } else {
- flagZeroPad = true;
- break;
- }
- case 32:
- flagPadSign = true;
- break;
- default:
- break flagsLoop;
- }
- textIndex++;
- next = HEAP8[((textIndex + 1) | 0)];
- }
- // Handle width.
- var width = 0;
- if (next == 42) {
- width = getNextArg('i32');
- textIndex++;
- next = HEAP8[((textIndex + 1) | 0)];
- } else {
- while (next >= 48 && next <= 57) {
- width = width * 10 + (next - 48);
- textIndex++;
- next = HEAP8[((textIndex + 1) | 0)];
- }
- }
- // Handle precision.
- var precisionSet = false,
- precision = -1;
- if (next == 46) {
- precision = 0;
- precisionSet = true;
- textIndex++;
- next = HEAP8[((textIndex + 1) | 0)];
- if (next == 42) {
- precision = getNextArg('i32');
- textIndex++;
- } else {
- while (1) {
- var precisionChr = HEAP8[((textIndex + 1) | 0)];
- if (precisionChr < 48 ||
- precisionChr > 57) break;
- precision = precision * 10 + (precisionChr - 48);
- textIndex++;
- }
- }
- next = HEAP8[((textIndex + 1) | 0)];
- }
- if (precision < 0) {
- precision = 6; // Standard default.
- precisionSet = false;
- }
- // Handle integer sizes. WARNING: These assume a 32-bit architecture!
- var argSize;
- switch (String.fromCharCode(next)) {
- case 'h':
- var nextNext = HEAP8[((textIndex + 2) | 0)];
- if (nextNext == 104) {
- textIndex++;
- argSize = 1; // char (actually i32 in varargs)
- } else {
- argSize = 2; // short (actually i32 in varargs)
- }
- break;
- case 'l':
- var nextNext = HEAP8[((textIndex + 2) | 0)];
- if (nextNext == 108) {
- textIndex++;
- argSize = 8; // long long
- } else {
- argSize = 4; // long
- }
- break;
- case 'L': // long long
- case 'q': // int64_t
- case 'j': // intmax_t
- argSize = 8;
- break;
- case 'z': // size_t
- case 't': // ptrdiff_t
- case 'I': // signed ptrdiff_t or unsigned size_t
- argSize = 4;
- break;
- default:
- argSize = null;
- }
- if (argSize) textIndex++;
- next = HEAP8[((textIndex + 1) | 0)];
- // Handle type specifier.
- switch (String.fromCharCode(next)) {
- case 'd':
- case 'i':
- case 'u':
- case 'o':
- case 'x':
- case 'X':
- case 'p':
- {
- // Integer.
- var signed = next == 100 || next == 105;
- argSize = argSize || 4;
- var currArg = getNextArg('i' + (argSize * 8));
- var origArg = currArg;
- var argText;
- // Flatten i64-1 [low, high] into a (slightly rounded) double
- if (argSize == 8) {
- currArg = Runtime.makeBigInt(currArg[0], currArg[1], next == 117);
- }
- // Truncate to requested size.
- if (argSize <= 4) {
- var limit = Math.pow(256, argSize) - 1;
- currArg = (signed ? reSign : unSign)(currArg & limit, argSize * 8);
- }
- // Format the number.
- var currAbsArg = Math.abs(currArg);
- var prefix = '';
- if (next == 100 || next == 105) {
- if (argSize == 8 && i64Math) argText = i64Math.stringify(origArg[0], origArg[1], null);
- else
- argText = reSign(currArg, 8 * argSize, 1).toString(10);
- } else if (next == 117) {
- if (argSize == 8 && i64Math) argText = i64Math.stringify(origArg[0], origArg[1], true);
- else
- argText = unSign(currArg, 8 * argSize, 1).toString(10);
- currArg = Math.abs(currArg);
- } else if (next == 111) {
- argText = (flagAlternative ? '0' : '') + currAbsArg.toString(8);
- } else if (next == 120 || next == 88) {
- prefix = (flagAlternative && currArg != 0) ? '0x' : '';
- if (argSize == 8 && i64Math) {
- if (origArg[1]) {
- argText = (origArg[1] >>> 0).toString(16);
- var lower = (origArg[0] >>> 0).toString(16);
- while (lower.length < 8) lower = '0' + lower;
- argText += lower;
- } else {
- argText = (origArg[0] >>> 0).toString(16);
- }
- } else
- if (currArg < 0) {
- // Represent negative numbers in hex as 2's complement.
- currArg = -currArg;
- argText = (currAbsArg - 1).toString(16);
- var buffer = [];
- for (var i = 0; i < argText.length; i++) {
- buffer.push((0xF - parseInt(argText[i], 16)).toString(16));
- }
- argText = buffer.join('');
- while (argText.length < argSize * 2) argText = 'f' + argText;
- } else {
- argText = currAbsArg.toString(16);
- }
- if (next == 88) {
- prefix = prefix.toUpperCase();
- argText = argText.toUpperCase();
- }
- } else if (next == 112) {
- if (currAbsArg === 0) {
- argText = '(nil)';
- } else {
- prefix = '0x';
- argText = currAbsArg.toString(16);
- }
- }
- if (precisionSet) {
- while (argText.length < precision) {
- argText = '0' + argText;
- }
- }
- // Add sign if needed
- if (currArg >= 0) {
- if (flagAlwaysSigned) {
- prefix = '+' + prefix;
- } else if (flagPadSign) {
- prefix = ' ' + prefix;
- }
- }
- // Move sign to prefix so we zero-pad after the sign
- if (argText.charAt(0) == '-') {
- prefix = '-' + prefix;
- argText = argText.substr(1);
- }
- // Add padding.
- while (prefix.length + argText.length < width) {
- if (flagLeftAlign) {
- argText += ' ';
- } else {
- if (flagZeroPad) {
- argText = '0' + argText;
- } else {
- prefix = ' ' + prefix;
- }
- }
- }
- // Insert the result into the buffer.
- argText = prefix + argText;
- argText.split('').forEach(function (chr) {
- ret.push(chr.charCodeAt(0));
- });
- break;
- }
- case 'f':
- case 'F':
- case 'e':
- case 'E':
- case 'g':
- case 'G':
- {
- // Float.
- var currArg = getNextArg('double');
- var argText;
- if (isNaN(currArg)) {
- argText = 'nan';
- flagZeroPad = false;
- } else if (!isFinite(currArg)) {
- argText = (currArg < 0 ? '-' : '') + 'inf';
- flagZeroPad = false;
- } else {
- var isGeneral = false;
- var effectivePrecision = Math.min(precision, 20);
- // Convert g/G to f/F or e/E, as per:
- // http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
- if (next == 103 || next == 71) {
- isGeneral = true;
- precision = precision || 1;
- var exponent = parseInt(currArg.toExponential(effectivePrecision).split('e')[1], 10);
- if (precision > exponent && exponent >= -4) {
- next = ((next == 103) ? 'f' : 'F').charCodeAt(0);
- precision -= exponent + 1;
- } else {
- next = ((next == 103) ? 'e' : 'E').charCodeAt(0);
- precision--;
- }
- effectivePrecision = Math.min(precision, 20);
- }
- if (next == 101 || next == 69) {
- argText = currArg.toExponential(effectivePrecision);
- // Make sure the exponent has at least 2 digits.
- if (/[eE][-+]\d$/.test(argText)) {
- argText = argText.slice(0, -1) + '0' + argText.slice(-1);
- }
- } else if (next == 102 || next == 70) {
- argText = currArg.toFixed(effectivePrecision);
- if (currArg === 0 && __reallyNegative(currArg)) {
- argText = '-' + argText;
- }
- }
- var parts = argText.split('e');
- if (isGeneral && !flagAlternative) {
- // Discard trailing zeros and periods.
- while (parts[0].length > 1 && parts[0].indexOf('.') != -1 &&
- (parts[0].slice(-1) == '0' || parts[0].slice(-1) == '.')) {
- parts[0] = parts[0].slice(0, -1);
- }
- } else {
- // Make sure we have a period in alternative mode.
- if (flagAlternative && argText.indexOf('.') == -1) parts[0] += '.';
- // Zero pad until required precision.
- while (precision > effectivePrecision++) parts[0] += '0';
- }
- argText = parts[0] + (parts.length > 1 ? 'e' + parts[1] : '');
- // Capitalize 'E' if needed.
- if (next == 69) argText = argText.toUpperCase();
- // Add sign.
- if (currArg >= 0) {
- if (flagAlwaysSigned) {
- argText = '+' + argText;
- } else if (flagPadSign) {
- argText = ' ' + argText;
- }
- }
- }
- // Add padding.
- while (argText.length < width) {
- if (flagLeftAlign) {
- argText += ' ';
- } else {
- if (flagZeroPad && (argText[0] == '-' || argText[0] == '+')) {
- argText = argText[0] + '0' + argText.slice(1);
- } else {
- argText = (flagZeroPad ? '0' : ' ') + argText;
- }
- }
- }
- // Adjust case.
- if (next < 97) argText = argText.toUpperCase();
- // Insert the result into the buffer.
- argText.split('').forEach(function (chr) {
- ret.push(chr.charCodeAt(0));
- });
- break;
- }
- case 's':
- {
- // String.
- var arg = getNextArg('i8*');
- var argLength = arg ? _strlen(arg) : '(null)'.length;
- if (precisionSet) argLength = Math.min(argLength, precision);
- if (!flagLeftAlign) {
- while (argLength < width--) {
- ret.push(32);
- }
- }
- if (arg) {
- for (var i = 0; i < argLength; i++) {
- ret.push(HEAPU8[((arg++) | 0)]);
- }
- } else {
- ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true));
- }
- if (flagLeftAlign) {
- while (argLength < width--) {
- ret.push(32);
- }
- }
- break;
- }
- case 'c':
- {
- // Character.
- if (flagLeftAlign) ret.push(getNextArg('i8'));
- while (--width > 0) {
- ret.push(32);
- }
- if (!flagLeftAlign) ret.push(getNextArg('i8'));
- break;
- }
- case 'n':
- {
- // Write the length written so far to the next parameter.
- var ptr = getNextArg('i32*');
- HEAP32[((ptr) >> 2)] = ret.length;
- break;
- }
- case '%':
- {
- // Literal percent sign.
- ret.push(curr);
- break;
- }
- default:
- {
- // Unknown specifiers remain untouched.
- for (var i = startTextIndex; i < textIndex + 2; i++) {
- ret.push(HEAP8[(i)]);
- }
- }
- }
- textIndex += 2;
- // TODO: Support a/A (hex float) and m (last error) specifiers.
- // TODO: Support %1${specifier} for arg selection.
- } else {
- ret.push(curr);
- textIndex += 1;
- }
- }
- return ret;
- }
- function _fprintf(stream, format, varargs) {
- // int fprintf(FILE *restrict stream, const char *restrict format, ...);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
- var result = __formatString(format, varargs);
- var stack = Runtime.stackSave();
- var ret = _fwrite(allocate(result, 'i8', ALLOC_STACK), 1, result.length, stream);
- Runtime.stackRestore(stack);
- return ret;
- }
- function _printf(format, varargs) {
- // int printf(const char *restrict format, ...);
- // http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html
- var stdout = HEAP32[((_stdout) >> 2)];
- return _fprintf(stdout, format, varargs);
- }
- function _emscripten_memcpy_big(dest, src, num) {
- HEAPU8.set(HEAPU8.subarray(src, src + num), dest);
- return dest;
- }
- Module["_memcpy"] = _memcpy;
- Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, resizeCanvas) {
- Browser.requestFullScreen(lockPointer, resizeCanvas)
- };
- Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) {
- Browser.requestAnimationFrame(func)
- };
- Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) {
- Browser.setCanvasSize(width, height, noUpdates)
- };
- Module["pauseMainLoop"] = function Module_pauseMainLoop() {
- Browser.mainLoop.pause()
- };
- Module["resumeMainLoop"] = function Module_resumeMainLoop() {
- Browser.mainLoop.resume()
- };
- Module["getUserMedia"] = function Module_getUserMedia() {
- Browser.getUserMedia()
- }
- FS.staticInit();
- __ATINIT__.unshift({
- func: function () {
- if (!Module["noFSInit"] && !FS.init.initialized) FS.init()
- }
- });
- __ATMAIN__.push({
- func: function () {
- FS.ignorePermissions = false
- }
- });
- __ATEXIT__.push({
- func: function () {
- FS.quit()
- }
- });
- Module["FS_createFolder"] = FS.createFolder;
- Module["FS_createPath"] = FS.createPath;
- Module["FS_createDataFile"] = FS.createDataFile;
- Module["FS_createPreloadedFile"] = FS.createPreloadedFile;
- Module["FS_createLazyFile"] = FS.createLazyFile;
- Module["FS_createLink"] = FS.createLink;
- Module["FS_createDevice"] = FS.createDevice;
- ___errno_state = Runtime.staticAlloc(4);
- HEAP32[((___errno_state) >> 2)] = 0;
- __ATINIT__.unshift({
- func: function () {
- TTY.init()
- }
- });
- __ATEXIT__.push({
- func: function () {
- TTY.shutdown()
- }
- });
- TTY.utf8 = new Runtime.UTF8Processor();
- if (ENVIRONMENT_IS_NODE) {
- var fs = require("fs");
- NODEFS.staticInit();
- }
- __ATINIT__.push({
- func: function () {
- SOCKFS.root = FS.mount(SOCKFS, {}, null);
- }
- });
- STACK_BASE = STACKTOP = Runtime.alignMemory(STATICTOP);
- staticSealed = true; // seal the static portion of memory
- STACK_MAX = STACK_BASE + 5242880;
- DYNAMIC_BASE = DYNAMICTOP = Runtime.alignMemory(STACK_MAX);
- assert(DYNAMIC_BASE < TOTAL_MEMORY, "TOTAL_MEMORY not big enough for stack");
- var Math_min = Math.min;
- function asmPrintInt(x, y) {
- Module.print('int ' + x + ',' + y); // + ' ' + new Error().stack);
- }
- function asmPrintFloat(x, y) {
- Module.print('float ' + x + ',' + y); // + ' ' + new Error().stack);
- }
- // EMSCRIPTEN_START_ASM
- var asm = (function (global, env, buffer) {
- "use asm";
- var a = new global.Int8Array(buffer);
- var b = new global.Int16Array(buffer);
- var c = new global.Int32Array(buffer);
- var d = new global.Uint8Array(buffer);
- var e = new global.Uint16Array(buffer);
- var f = new global.Uint32Array(buffer);
- var g = new global.Float32Array(buffer);
- var h = new global.Float64Array(buffer);
- var i = env.STACKTOP | 0;
- var j = env.STACK_MAX | 0;
- var k = env.tempDoublePtr | 0;
- var l = env.ABORT | 0;
- var m = 0;
- var n = 0;
- var o = 0;
- var p = 0;
- var q = +env.NaN,
- r = +env.Infinity;
- var s = 0,
- t = 0,
- u = 0,
- v = 0,
- w = 0.0,
- x = 0,
- y = 0,
- z = 0,
- A = 0.0;
- var B = 0;
- var C = 0;
- var D = 0;
- var E = 0;
- var F = 0;
- var G = 0;
- var H = 0;
- var I = 0;
- var J = 0;
- var K = 0;
- var L = global.Math.floor;
- var M = global.Math.abs;
- var N = global.Math.sqrt;
- var O = global.Math.pow;
- var P = global.Math.cos;
- var Q = global.Math.sin;
- var R = global.Math.tan;
- var S = global.Math.acos;
- var T = global.Math.asin;
- var U = global.Math.atan;
- var V = global.Math.atan2;
- var W = global.Math.exp;
- var X = global.Math.log;
- var Y = global.Math.ceil;
- var Z = global.Math.imul;
- var _ = env.abort;
- var $ = env.assert;
- var aa = env.asmPrintInt;
- var ba = env.asmPrintFloat;
- var ca = env.min;
- var da = env._llvm_lifetime_start;
- var ea = env._free;
- var fa = env.__formatString;
- var ga = env._printf;
- var ha = env._send;
- var ia = env._pwrite;
- var ja = env.___setErrNo;
- var ka = env._fwrite;
- var la = env._malloc;
- var ma = env._mkport;
- var na = env._fprintf;
- var oa = env.__reallyNegative;
- var pa = env._llvm_lifetime_end;
- var qa = env._fileno;
- var ra = env._sqrt;
- var sa = env._fflush;
- var ta = env._write;
- var ua = env._emscripten_memcpy_big;
- var va = 0.0;
- // EMSCRIPTEN_START_FUNCS
- function wa(a) {
- a = a | 0;
- var b = 0;
- b = i;
- i = i + a | 0;
- i = i + 7 & -8;
- return b | 0
- }
- function xa() {
- return i | 0
- }
- function ya(a) {
- a = a | 0;
- i = a
- }
- function za(a, b) {
- a = a | 0;
- b = b | 0;
- if ((m | 0) == 0) {
- m = a;
- n = b
- }
- }
- function Aa(b) {
- b = b | 0;
- a[k] = a[b];
- a[k + 1 | 0] = a[b + 1 | 0];
- a[k + 2 | 0] = a[b + 2 | 0];
- a[k + 3 | 0] = a[b + 3 | 0]
- }
- function Ba(b) {
- b = b | 0;
- a[k] = a[b];
- a[k + 1 | 0] = a[b + 1 | 0];
- a[k + 2 | 0] = a[b + 2 | 0];
- a[k + 3 | 0] = a[b + 3 | 0];
- a[k + 4 | 0] = a[b + 4 | 0];
- a[k + 5 | 0] = a[b + 5 | 0];
- a[k + 6 | 0] = a[b + 6 | 0];
- a[k + 7 | 0] = a[b + 7 | 0]
- }
- function Ca(a) {
- a = a | 0;
- B = a
- }
- function Da(a) {
- a = a | 0;
- C = a
- }
- function Ea(a) {
- a = a | 0;
- D = a
- }
- function Fa(a) {
- a = a | 0;
- E = a
- }
- function Ga(a) {
- a = a | 0;
- F = a
- }
- function Ha(a) {
- a = a | 0;
- G = a
- }
- function Ia(a) {
- a = a | 0;
- H = a
- }
- function Ja(a) {
- a = a | 0;
- I = a
- }
- function Ka(a) {
- a = a | 0;
- J = a
- }
- function La(a) {
- a = a | 0;
- K = a
- }
- function Ma(a, b, c) {
- a = a | 0;
- b = b | 0;
- c = +c;
- var d = 0,
- e = 0,
- f = 0,
- g = 0,
- j = 0,
- k = 0,
- l = 0,
- m = 0,
- n = 0,
- o = 0,
- p = 0,
- q = 0,
- r = 0.0,
- s = 0.0,
- t = 0.0,
- u = 0.0,
- v = 0.0,
- w = 0,
- x = 0;
- d = i;
- e = (a | 0) > 0;
- if (e) {
- f = 0
- } else {
- i = d;
- return
- }
- while (1) {
- g = f + 1 | 0;
- if ((g | 0) < (a | 0)) {
- j = b + (f * 56 | 0) | 0;
- k = b + (f * 56 | 0) + 8 | 0;
- l = b + (f * 56 | 0) + 16 | 0;
- m = b + (f * 56 | 0) + 24 | 0;
- n = b + (f * 56 | 0) + 32 | 0;
- o = b + (f * 56 | 0) + 40 | 0;
- p = b + (f * 56 | 0) + 48 | 0;
- q = g;
- do {
- r = +h[j >> 3] - +h[b + (q * 56 | 0) >> 3];
- s = +h[k >> 3] - +h[b + (q * 56 | 0) + 8 >> 3];
- t = +h[l >> 3] - +h[b + (q * 56 | 0) + 16 >> 3];
- u = +N(+(r * r + s * s + t * t));
- v = c / (u * u * u);
- w = b + (q * 56 | 0) + 48 | 0;
- h[m >> 3] = +h[m >> 3] - v * r * +h[w >> 3];
- h[n >> 3] = +h[n >> 3] - v * s * +h[w >> 3];
- h[o >> 3] = +h[o >> 3] - v * t * +h[w >> 3];
- w = b + (q * 56 | 0) + 24 | 0;
- h[w >> 3] = +h[w >> 3] + v * r * +h[p >> 3];
- w = b + (q * 56 | 0) + 32 | 0;
- h[w >> 3] = +h[w >> 3] + v * s * +h[p >> 3];
- w = b + (q * 56 | 0) + 40 | 0;
- h[w >> 3] = +h[w >> 3] + v * t * +h[p >> 3];
- q = q + 1 | 0;
- } while ((q | 0) != (a | 0))
- }
- if ((g | 0) == (a | 0)) {
- break
- } else {
- f = g
- }
- }
- if (e) {
- x = 0
- } else {
- i = d;
- return
- }
- do {
- e = b + (x * 56 | 0) | 0;
- h[e >> 3] = +h[e >> 3] + +h[b + (x * 56 | 0) + 24 >> 3] * c;
- e = b + (x * 56 | 0) + 8 | 0;
- h[e >> 3] = +h[e >> 3] + +h[b + (x * 56 | 0) + 32 >> 3] * c;
- e = b + (x * 56 | 0) + 16 | 0;
- h[e >> 3] = +h[e >> 3] + +h[b + (x * 56 | 0) + 40 >> 3] * c;
- x = x + 1 | 0;
- } while ((x | 0) != (a | 0));
- i = d;
- return
- }
- function Na(a, b) {
- a = a | 0;
- b = b | 0;
- var d = 0,
- e = 0.0,
- f = 0.0,
- g = 0.0,
- j = 0.0,
- l = 0.0,
- m = 0.0,
- n = 0.0,
- o = 0.0,
- p = 0,
- q = 0,
- r = 0.0,
- s = 0.0,
- t = 0,
- u = 0.0,
- v = 0.0,
- w = 0.0,
- x = 0.0,
- y = 0,
- z = 0.0,
- A = 0.0,
- B = 0,
- C = 0.0;
- b = i;
- i = i + 8 | 0;
- a = b;
- d = i;
- i = i + 8 | 0;
- e = +h[56 >> 3];
- f = +h[112 >> 3];
- g = +h[168 >> 3];
- j = +h[224 >> 3];
- l = +h[280 >> 3];
- m = e * +h[40 >> 3] + 0.0 + f * +h[96 >> 3] + g * +h[152 >> 3] + j * +h[208 >> 3] + l * +h[264 >> 3];
- n = e * +h[48 >> 3] + 0.0 + f * +h[104 >> 3] + g * +h[160 >> 3] + j * +h[216 >> 3] + l * +h[272 >> 3];
- 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;
- h[32 >> 3] = o;
- l = -m / 39.47841760435743;
- h[40 >> 3] = l;
- m = -n / 39.47841760435743;
- h[48 >> 3] = m;
- n = m;
- m = l;
- l = o;
- o = e;
- e = 0.0;
- p = 0;
- while (1) {
- j = e + o * .5 * (l * l + m * m + n * n);
- q = p + 1 | 0;
- if ((q | 0) < 5) {
- g = +h[8 + (p * 56 | 0) >> 3];
- f = +h[16 + (p * 56 | 0) >> 3];
- r = +h[24 + (p * 56 | 0) >> 3];
- s = j;
- t = q;
- while (1) {
- u = g - +h[8 + (t * 56 | 0) >> 3];
- v = f - +h[16 + (t * 56 | 0) >> 3];
- w = r - +h[24 + (t * 56 | 0) >> 3];
- x = +N(+(u * u + v * v + w * w));
- w = s - o * +h[56 + (t * 56 | 0) >> 3] / x;
- y = t + 1 | 0;
- if ((y | 0) == 5) {
- z = w;
- break
- } else {
- t = y;
- s = w
- }
- }
- } else {
- z = j
- } if ((q | 0) == 5) {
- break
- }
- n = +h[48 + (q * 56 | 0) >> 3];
- m = +h[40 + (q * 56 | 0) >> 3];
- l = +h[32 + (q * 56 | 0) >> 3];
- o = +h[56 + (q * 56 | 0) >> 3];
- e = z;
- p = q
- }
- p = d;
- h[k >> 3] = z;
- c[p >> 2] = c[k >> 2];
- c[p + 4 >> 2] = c[k + 4 >> 2];
- ga(288, d | 0) | 0;
- d = 1;
- while (1) {
- Ma(5, 8, .01);
- p = d + 1 | 0;
- if ((p | 0) == 5000001) {
- A = 0.0;
- B = 0;
- break
- } else {
- d = p
- }
- }
- while (1) {
- z = +h[56 + (B * 56 | 0) >> 3];
- e = +h[32 + (B * 56 | 0) >> 3];
- o = +h[40 + (B * 56 | 0) >> 3];
- l = +h[48 + (B * 56 | 0) >> 3];
- m = A + z * .5 * (e * e + o * o + l * l);
- d = B + 1 | 0;
- if ((d | 0) < 5) {
- l = +h[8 + (B * 56 | 0) >> 3];
- o = +h[16 + (B * 56 | 0) >> 3];
- e = +h[24 + (B * 56 | 0) >> 3];
- n = m;
- p = d;
- while (1) {
- s = l - +h[8 + (p * 56 | 0) >> 3];
- r = o - +h[16 + (p * 56 | 0) >> 3];
- f = e - +h[24 + (p * 56 | 0) >> 3];
- g = +N(+(s * s + r * r + f * f));
- f = n - z * +h[56 + (p * 56 | 0) >> 3] / g;
- t = p + 1 | 0;
- if ((t | 0) == 5) {
- C = f;
- break
- } else {
- p = t;
- n = f
- }
- }
- } else {
- C = m
- } if ((d | 0) == 5) {
- break
- } else {
- A = C;
- B = d
- }
- }
- B = a;
- h[k >> 3] = C;
- c[B >> 2] = c[k >> 2];
- c[B + 4 >> 2] = c[k + 4 >> 2];
- ga(288, a | 0) | 0;
- i = b;
- return 0
- }
- function Oa() {}
- function Pa(b, d, e) {
- b = b | 0;
- d = d | 0;
- e = e | 0;
- var f = 0,
- g = 0,
- h = 0,
- i = 0;
- f = b + e | 0;
- if ((e | 0) >= 20) {
- d = d & 255;
- g = b & 3;
- h = d | d << 8 | d << 16 | d << 24;
- i = f & ~3;
- if (g) {
- g = b + 4 - g | 0;
- while ((b | 0) < (g | 0)) {
- a[b] = d;
- b = b + 1 | 0
- }
- }
- while ((b | 0) < (i | 0)) {
- c[b >> 2] = h;
- b = b + 4 | 0
- }
- }
- while ((b | 0) < (f | 0)) {
- a[b] = d;
- b = b + 1 | 0
- }
- return b - e | 0
- }
- function Qa(b) {
- b = b | 0;
- var c = 0;
- c = b;
- while (a[c] | 0) {
- c = c + 1 | 0
- }
- return c - b | 0
- }
- function Ra(b, d, e) {
- b = b | 0;
- d = d | 0;
- e = e | 0;
- var f = 0;
- if ((e | 0) >= 4096) return ua(b | 0, d | 0, e | 0) | 0;
- f = b | 0;
- if ((b & 3) == (d & 3)) {
- while (b & 3) {
- if ((e | 0) == 0) return f | 0;
- a[b] = a[d] | 0;
- b = b + 1 | 0;
- d = d + 1 | 0;
- e = e - 1 | 0
- }
- while ((e | 0) >= 4) {
- c[b >> 2] = c[d >> 2];
- b = b + 4 | 0;
- d = d + 4 | 0;
- e = e - 4 | 0
- }
- }
- while ((e | 0) > 0) {
- a[b] = a[d] | 0;
- b = b + 1 | 0;
- d = d + 1 | 0;
- e = e - 1 | 0
- }
- return f | 0
- }
- // EMSCRIPTEN_END_FUNCS
- return {
- _strlen: Qa,
- _memcpy: Ra,
- _main: Na,
- _memset: Pa,
- runPostSets: Oa,
- stackAlloc: wa,
- stackSave: xa,
- stackRestore: ya,
- setThrew: za,
- setTempRet0: Ca,
- setTempRet1: Da,
- setTempRet2: Ea,
- setTempRet3: Fa,
- setTempRet4: Ga,
- setTempRet5: Ha,
- setTempRet6: Ia,
- setTempRet7: Ja,
- setTempRet8: Ka,
- setTempRet9: La
- }
- })
- // EMSCRIPTEN_END_ASM
- ({
- "Math": Math,
- "Int8Array": Int8Array,
- "Int16Array": Int16Array,
- "Int32Array": Int32Array,
- "Uint8Array": Uint8Array,
- "Uint16Array": Uint16Array,
- "Uint32Array": Uint32Array,
- "Float32Array": Float32Array,
- "Float64Array": Float64Array
- }, {
- "abort": abort,
- "assert": assert,
- "asmPrintInt": asmPrintInt,
- "asmPrintFloat": asmPrintFloat,
- "min": Math_min,
- "_llvm_lifetime_start": _llvm_lifetime_start,
- "_free": _free,
- "__formatString": __formatString,
- "_printf": _printf,
- "_send": _send,
- "_pwrite": _pwrite,
- "___setErrNo": ___setErrNo,
- "_fwrite": _fwrite,
- "_malloc": _malloc,
- "_mkport": _mkport,
- "_fprintf": _fprintf,
- "__reallyNegative": __reallyNegative,
- "_llvm_lifetime_end": _llvm_lifetime_end,
- "_fileno": _fileno,
- "_sqrt": _sqrt,
- "_fflush": _fflush,
- "_write": _write,
- "_emscripten_memcpy_big": _emscripten_memcpy_big,
- "STACKTOP": STACKTOP,
- "STACK_MAX": STACK_MAX,
- "tempDoublePtr": tempDoublePtr,
- "ABORT": ABORT,
- "NaN": NaN,
- "Infinity": Infinity
- }, buffer);
- var _strlen = Module["_strlen"] = asm["_strlen"];
- var _memcpy = Module["_memcpy"] = asm["_memcpy"];
- var _main = Module["_main"] = asm["_main"];
- var _memset = Module["_memset"] = asm["_memset"];
- var runPostSets = Module["runPostSets"] = asm["runPostSets"];
- Runtime.stackAlloc = function (size) {
- return asm['stackAlloc'](size)
- };
- Runtime.stackSave = function () {
- return asm['stackSave']()
- };
- Runtime.stackRestore = function (top) {
- asm['stackRestore'](top)
- };
- // Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
- var i64Math = null;
- // === Auto-generated postamble setup entry stuff ===
- if (memoryInitializer) {
- if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) {
- var data = Module['readBinary'](memoryInitializer);
- HEAPU8.set(data, STATIC_BASE);
- } else {
- addRunDependency('memory initializer');
- Browser.asyncLoad(memoryInitializer, function (data) {
- HEAPU8.set(data, STATIC_BASE);
- removeRunDependency('memory initializer');
- }, function (data) {
- throw 'could not load memory initializer ' + memoryInitializer;
- });
- }
- }
- function ExitStatus(status) {
- this.name = "ExitStatus";
- this.message = "Program terminated with exit(" + status + ")";
- this.status = status;
- };
- ExitStatus.prototype = new Error();
- ExitStatus.prototype.constructor = ExitStatus;
- var initialStackTop;
- var preloadStartTime = null;
- var calledMain = false;
- dependenciesFulfilled = function runCaller() {
- // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
- if (!Module['calledRun'] && shouldRunNow) run();
- if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
- }
- Module['callMain'] = Module.callMain = function callMain(args) {
- assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on __ATMAIN__)');
- assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
- args = args || [];
- if (ENVIRONMENT_IS_WEB && preloadStartTime !== null) {
- Module.printErr('preload time: ' + (Date.now() - preloadStartTime) + ' ms');
- }
- ensureInitRuntime();
- var argc = args.length + 1;
- function pad() {
- for (var i = 0; i < 4 - 1; i++) {
- argv.push(0);
- }
- }
- var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_NORMAL)];
- pad();
- for (var i = 0; i < argc - 1; i = i + 1) {
- argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_NORMAL));
- pad();
- }
- argv.push(0);
- argv = allocate(argv, 'i32', ALLOC_NORMAL);
- initialStackTop = STACKTOP;
- try {
- var ret = Module['_main'](argc, argv, 0);
- // if we're not running an evented main loop, it's time to exit
- if (!Module['noExitRuntime']) {
- exit(ret);
- }
- } catch (e) {
- if (e instanceof ExitStatus) {
- // exit() throws this once it's done to make sure execution
- // has been stopped completely
- return;
- } else if (e == 'SimulateInfiniteLoop') {
- // running an evented main loop, don't immediately exit
- Module['noExitRuntime'] = true;
- return;
- } else {
- if (e && typeof e === 'object' && e.stack) Module.printErr('exception thrown: ' + [e, e.stack]);
- throw e;
- }
- } finally {
- calledMain = true;
- }
- }
- function run(args) {
- args = args || Module['arguments'];
- if (preloadStartTime === null) preloadStartTime = Date.now();
- if (runDependencies > 0) {
- Module.printErr('run() called, but dependencies remain, so not running');
- return;
- }
- preRun();
- if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
- if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
- function doRun() {
- if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
- Module['calledRun'] = true;
- ensureInitRuntime();
- preMain();
- if (Module['_main'] && shouldRunNow) {
- Module['callMain'](args);
- }
- postRun();
- }
- if (Module['setStatus']) {
- Module['setStatus']('Running...');
- setTimeout(function () {
- setTimeout(function () {
- Module['setStatus']('');
- }, 1);
- if (!ABORT) doRun();
- }, 1);
- } else {
- doRun();
- }
- }
- Module['run'] = Module.run = run;
- function exit(status) {
- ABORT = true;
- EXITSTATUS = status;
- STACKTOP = initialStackTop;
- // exit the runtime
- exitRuntime();
- // TODO We should handle this differently based on environment.
- // In the browser, the best we can do is throw an exception
- // to halt execution, but in node we could process.exit and
- // I'd imagine SM shell would have something equivalent.
- // This would let us set a proper exit status (which
- // would be great for checking test exit statuses).
- // https://github.com/kripken/emscripten/issues/1371
- // throw an exception to halt the current execution
- throw new ExitStatus(status);
- }
- Module['exit'] = Module.exit = exit;
- function abort(text) {
- if (text) {
- Module.print(text);
- Module.printErr(text);
- }
- ABORT = true;
- EXITSTATUS = 1;
- var extra = '\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.';
- throw 'abort() at ' + stackTrace() + extra;
- }
- Module['abort'] = Module.abort = abort;
- // {{PRE_RUN_ADDITIONS}}
- if (Module['preInit']) {
- if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
- while (Module['preInit'].length > 0) {
- Module['preInit'].pop()();
- }
- }
- // shouldRunNow refers to calling main(), not run().
- var shouldRunNow = true;
- if (Module['noInitialRun']) {
- shouldRunNow = false;
- }
- run();
- // {{POST_RUN_ADDITIONS}}
- // {{MODULE_ADDITIONS}}
- ////////////////////////////////////////////////////////////////////////////////
- // Runner
- ////////////////////////////////////////////////////////////////////////////////
- var __time_after = top.JetStream.goodTime();
- top.JetStream.reportResult(__time_after - __time_before);
|