rhino3dm.js 314 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743
  1. var rhino3dm = (() => {
  2. var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
  3. if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;
  4. return (
  5. function(config) {
  6. var rhino3dm = config || {};
  7. // The Module object: Our interface to the outside world. We import
  8. // and export values on it. There are various ways Module can be used:
  9. // 1. Not defined. We create it here
  10. // 2. A function parameter, function(Module) { ..generated code.. }
  11. // 3. pre-run appended it, var Module = {}; ..generated code..
  12. // 4. External script tag defines var Module.
  13. // We need to check if Module already exists (e.g. case 3 above).
  14. // Substitution will be replaced with actual code on later stage of the build,
  15. // this way Closure Compiler will not mangle it (e.g. case 4. above).
  16. // Note that if you want to run closure, and also to use Module
  17. // after the generated code, you will need to define var Module = {};
  18. // before the code. Then that object will be used in the code, and you
  19. // can continue to use Module afterwards as well.
  20. var Module = typeof rhino3dm != 'undefined' ? rhino3dm : {};
  21. // See https://caniuse.com/mdn-javascript_builtins_object_assign
  22. // See https://caniuse.com/mdn-javascript_builtins_bigint64array
  23. // Set up the promise that indicates the Module is initialized
  24. var readyPromiseResolve, readyPromiseReject;
  25. Module['ready'] = new Promise(function(resolve, reject) {
  26. readyPromiseResolve = resolve;
  27. readyPromiseReject = reject;
  28. });
  29. ["_main","_fflush","___getTypeName","__embind_initialize_bindings","onRuntimeInitialized"].forEach((prop) => {
  30. if (!Object.getOwnPropertyDescriptor(Module['ready'], prop)) {
  31. Object.defineProperty(Module['ready'], prop, {
  32. get: () => abort('You are getting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js'),
  33. set: () => abort('You are setting ' + prop + ' on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js'),
  34. });
  35. }
  36. });
  37. // --pre-jses are emitted after the Module integration code, so that they can
  38. // refer to Module (if they choose; they can also define Module)
  39. // {{PRE_JSES}}
  40. // Sometimes an existing Module object exists with properties
  41. // meant to overwrite the default module functionality. Here
  42. // we collect those properties and reapply _after_ we configure
  43. // the current environment's defaults to avoid having to be so
  44. // defensive during initialization.
  45. var moduleOverrides = Object.assign({}, Module);
  46. var arguments_ = [];
  47. var thisProgram = './this.program';
  48. var quit_ = (status, toThrow) => {
  49. throw toThrow;
  50. };
  51. // Determine the runtime environment we are in. You can customize this by
  52. // setting the ENVIRONMENT setting at compile time (see settings.js).
  53. // Attempt to auto-detect the environment
  54. var ENVIRONMENT_IS_WEB = typeof window == 'object';
  55. var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function';
  56. // N.b. Electron.js environment is simultaneously a NODE-environment, but
  57. // also a web environment.
  58. var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
  59. var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  60. if (Module['ENVIRONMENT']) {
  61. throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)');
  62. }
  63. // `/` should be present at the end if `scriptDirectory` is not empty
  64. var scriptDirectory = '';
  65. function locateFile(path) {
  66. if (Module['locateFile']) {
  67. return Module['locateFile'](path, scriptDirectory);
  68. }
  69. return scriptDirectory + path;
  70. }
  71. // Hooks that are implemented differently in different runtime environments.
  72. var read_,
  73. readAsync,
  74. readBinary,
  75. setWindowTitle;
  76. // Normally we don't log exceptions but instead let them bubble out the top
  77. // level where the embedding environment (e.g. the browser) can handle
  78. // them.
  79. // However under v8 and node we sometimes exit the process direcly in which case
  80. // its up to use us to log the exception before exiting.
  81. // If we fix https://github.com/emscripten-core/emscripten/issues/15080
  82. // this may no longer be needed under node.
  83. function logExceptionOnExit(e) {
  84. if (e instanceof ExitStatus) return;
  85. let toLog = e;
  86. if (e && typeof e == 'object' && e.stack) {
  87. toLog = [e, e.stack];
  88. }
  89. err('exiting due to exception: ' + toLog);
  90. }
  91. if (ENVIRONMENT_IS_NODE) {
  92. if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  93. // `require()` is no-op in an ESM module, use `createRequire()` to construct
  94. // the require()` function. This is only necessary for multi-environment
  95. // builds, `-sENVIRONMENT=node` emits a static import declaration instead.
  96. // TODO: Swap all `require()`'s with `import()`'s?
  97. // These modules will usually be used on Node.js. Load them eagerly to avoid
  98. // the complexity of lazy-loading.
  99. var fs = require('fs');
  100. var nodePath = require('path');
  101. if (ENVIRONMENT_IS_WORKER) {
  102. scriptDirectory = nodePath.dirname(scriptDirectory) + '/';
  103. } else {
  104. scriptDirectory = __dirname + '/';
  105. }
  106. // include: node_shell_read.js
  107. read_ = (filename, binary) => {
  108. // We need to re-wrap `file://` strings to URLs. Normalizing isn't
  109. // necessary in that case, the path should already be absolute.
  110. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  111. return fs.readFileSync(filename, binary ? undefined : 'utf8');
  112. };
  113. readBinary = (filename) => {
  114. var ret = read_(filename, true);
  115. if (!ret.buffer) {
  116. ret = new Uint8Array(ret);
  117. }
  118. assert(ret.buffer);
  119. return ret;
  120. };
  121. readAsync = (filename, onload, onerror) => {
  122. // See the comment in the `read_` function.
  123. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  124. fs.readFile(filename, function(err, data) {
  125. if (err) onerror(err);
  126. else onload(data.buffer);
  127. });
  128. };
  129. // end include: node_shell_read.js
  130. if (process['argv'].length > 1) {
  131. thisProgram = process['argv'][1].replace(/\\/g, '/');
  132. }
  133. arguments_ = process['argv'].slice(2);
  134. // MODULARIZE will export the module in the proper place outside, we don't need to export here
  135. process['on']('uncaughtException', function(ex) {
  136. // suppress ExitStatus exceptions from showing an error
  137. if (!(ex instanceof ExitStatus)) {
  138. throw ex;
  139. }
  140. });
  141. // Without this older versions of node (< v15) will log unhandled rejections
  142. // but return 0, which is not normally the desired behaviour. This is
  143. // not be needed with node v15 and about because it is now the default
  144. // behaviour:
  145. // See https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode
  146. process['on']('unhandledRejection', function(reason) { throw reason; });
  147. quit_ = (status, toThrow) => {
  148. if (keepRuntimeAlive()) {
  149. process['exitCode'] = status;
  150. throw toThrow;
  151. }
  152. logExceptionOnExit(toThrow);
  153. process['exit'](status);
  154. };
  155. Module['inspect'] = function () { return '[Emscripten Module object]'; };
  156. } else
  157. if (ENVIRONMENT_IS_SHELL) {
  158. if ((typeof process == 'object' && typeof require === 'function') || typeof window == 'object' || typeof importScripts == 'function') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  159. if (typeof read != 'undefined') {
  160. read_ = function shell_read(f) {
  161. return read(f);
  162. };
  163. }
  164. readBinary = function readBinary(f) {
  165. let data;
  166. if (typeof readbuffer == 'function') {
  167. return new Uint8Array(readbuffer(f));
  168. }
  169. data = read(f, 'binary');
  170. assert(typeof data == 'object');
  171. return data;
  172. };
  173. readAsync = function readAsync(f, onload, onerror) {
  174. setTimeout(() => onload(readBinary(f)), 0);
  175. };
  176. if (typeof scriptArgs != 'undefined') {
  177. arguments_ = scriptArgs;
  178. } else if (typeof arguments != 'undefined') {
  179. arguments_ = arguments;
  180. }
  181. if (typeof quit == 'function') {
  182. quit_ = (status, toThrow) => {
  183. logExceptionOnExit(toThrow);
  184. quit(status);
  185. };
  186. }
  187. if (typeof print != 'undefined') {
  188. // Prefer to use print/printErr where they exist, as they usually work better.
  189. if (typeof console == 'undefined') console = /** @type{!Console} */({});
  190. console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
  191. console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr != 'undefined' ? printErr : print);
  192. }
  193. } else
  194. // Note that this includes Node.js workers when relevant (pthreads is enabled).
  195. // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
  196. // ENVIRONMENT_IS_NODE.
  197. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  198. if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
  199. scriptDirectory = self.location.href;
  200. } else if (typeof document != 'undefined' && document.currentScript) { // web
  201. scriptDirectory = document.currentScript.src;
  202. }
  203. // When MODULARIZE, this JS may be executed later, after document.currentScript
  204. // is gone, so we saved it, and we use it here instead of any other info.
  205. if (_scriptDir) {
  206. scriptDirectory = _scriptDir;
  207. }
  208. // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
  209. // otherwise, slice off the final part of the url to find the script directory.
  210. // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
  211. // and scriptDirectory will correctly be replaced with an empty string.
  212. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),
  213. // they are removed because they could contain a slash.
  214. if (scriptDirectory.indexOf('blob:') !== 0) {
  215. scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf('/')+1);
  216. } else {
  217. scriptDirectory = '';
  218. }
  219. if (!(typeof window == 'object' || typeof importScripts == 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  220. // Differentiate the Web Worker from the Node Worker case, as reading must
  221. // be done differently.
  222. {
  223. // include: web_or_worker_shell_read.js
  224. read_ = (url) => {
  225. var xhr = new XMLHttpRequest();
  226. xhr.open('GET', url, false);
  227. xhr.send(null);
  228. return xhr.responseText;
  229. }
  230. if (ENVIRONMENT_IS_WORKER) {
  231. readBinary = (url) => {
  232. var xhr = new XMLHttpRequest();
  233. xhr.open('GET', url, false);
  234. xhr.responseType = 'arraybuffer';
  235. xhr.send(null);
  236. return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
  237. };
  238. }
  239. readAsync = (url, onload, onerror) => {
  240. var xhr = new XMLHttpRequest();
  241. xhr.open('GET', url, true);
  242. xhr.responseType = 'arraybuffer';
  243. xhr.onload = () => {
  244. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  245. onload(xhr.response);
  246. return;
  247. }
  248. onerror();
  249. };
  250. xhr.onerror = onerror;
  251. xhr.send(null);
  252. }
  253. // end include: web_or_worker_shell_read.js
  254. }
  255. setWindowTitle = (title) => document.title = title;
  256. } else
  257. {
  258. throw new Error('environment detection error');
  259. }
  260. var out = Module['print'] || console.log.bind(console);
  261. var err = Module['printErr'] || console.warn.bind(console);
  262. // Merge back in the overrides
  263. Object.assign(Module, moduleOverrides);
  264. // Free the object hierarchy contained in the overrides, this lets the GC
  265. // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
  266. moduleOverrides = null;
  267. checkIncomingModuleAPI();
  268. // Emit code to handle expected values on the Module object. This applies Module.x
  269. // to the proper local x. This has two benefits: first, we only emit it if it is
  270. // expected to arrive, and second, by using a local everywhere else that can be
  271. // minified.
  272. if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
  273. if (Module['thisProgram']) thisProgram = Module['thisProgram'];legacyModuleProp('thisProgram', 'thisProgram');
  274. if (Module['quit']) quit_ = Module['quit'];legacyModuleProp('quit', 'quit_');
  275. // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
  276. // Assertions on removed incoming Module JS APIs.
  277. assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
  278. assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
  279. assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
  280. assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
  281. assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)');
  282. assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
  283. assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
  284. assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)');
  285. assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
  286. legacyModuleProp('read', 'read_');
  287. legacyModuleProp('readAsync', 'readAsync');
  288. legacyModuleProp('readBinary', 'readBinary');
  289. legacyModuleProp('setWindowTitle', 'setWindowTitle');
  290. var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
  291. var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
  292. var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
  293. var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
  294. assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add 'shell' to `-sENVIRONMENT` to enable.");
  295. // include: support.js
  296. var STACK_ALIGN = 16;
  297. var POINTER_SIZE = 4;
  298. function getNativeTypeSize(type) {
  299. switch (type) {
  300. case 'i1': case 'i8': case 'u8': return 1;
  301. case 'i16': case 'u16': return 2;
  302. case 'i32': case 'u32': return 4;
  303. case 'i64': case 'u64': return 8;
  304. case 'float': return 4;
  305. case 'double': return 8;
  306. default: {
  307. if (type[type.length - 1] === '*') {
  308. return POINTER_SIZE;
  309. }
  310. if (type[0] === 'i') {
  311. const bits = Number(type.substr(1));
  312. assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
  313. return bits / 8;
  314. }
  315. return 0;
  316. }
  317. }
  318. }
  319. // include: runtime_debug.js
  320. function legacyModuleProp(prop, newName) {
  321. if (!Object.getOwnPropertyDescriptor(Module, prop)) {
  322. Object.defineProperty(Module, prop, {
  323. configurable: true,
  324. get: function() {
  325. abort('Module.' + prop + ' has been replaced with plain ' + newName + ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)');
  326. }
  327. });
  328. }
  329. }
  330. function ignoredModuleProp(prop) {
  331. if (Object.getOwnPropertyDescriptor(Module, prop)) {
  332. abort('`Module.' + prop + '` was supplied but `' + prop + '` not included in INCOMING_MODULE_JS_API');
  333. }
  334. }
  335. // forcing the filesystem exports a few things by default
  336. function isExportedByForceFilesystem(name) {
  337. return name === 'FS_createPath' ||
  338. name === 'FS_createDataFile' ||
  339. name === 'FS_createPreloadedFile' ||
  340. name === 'FS_unlink' ||
  341. name === 'addRunDependency' ||
  342. // The old FS has some functionality that WasmFS lacks.
  343. name === 'FS_createLazyFile' ||
  344. name === 'FS_createDevice' ||
  345. name === 'removeRunDependency';
  346. }
  347. function missingGlobal(sym, msg) {
  348. Object.defineProperty(globalThis, sym, {
  349. configurable: true,
  350. get: function() {
  351. warnOnce('`' + sym + '` is not longer defined by emscripten. ' + msg);
  352. return undefined;
  353. }
  354. });
  355. }
  356. missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer');
  357. function missingLibrarySymbol(sym) {
  358. if (typeof globalThis !== 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
  359. Object.defineProperty(globalThis, sym, {
  360. configurable: true,
  361. get: function() {
  362. // Can't `abort()` here because it would break code that does runtime
  363. // checks. e.g. `if (typeof SDL === 'undefined')`.
  364. var msg = '`' + sym + '` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line';
  365. // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in
  366. // library.js, which means $name for a JS name with no prefix, or name
  367. // for a JS name like _name.
  368. var librarySymbol = sym;
  369. if (!librarySymbol.startsWith('_')) {
  370. librarySymbol = '$' + sym;
  371. }
  372. msg += " (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=" + librarySymbol + ")";
  373. if (isExportedByForceFilesystem(sym)) {
  374. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  375. }
  376. warnOnce(msg);
  377. return undefined;
  378. }
  379. });
  380. }
  381. }
  382. function unexportedRuntimeSymbol(sym) {
  383. if (!Object.getOwnPropertyDescriptor(Module, sym)) {
  384. Object.defineProperty(Module, sym, {
  385. configurable: true,
  386. get: function() {
  387. var msg = "'" + sym + "' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)";
  388. if (isExportedByForceFilesystem(sym)) {
  389. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  390. }
  391. abort(msg);
  392. }
  393. });
  394. }
  395. }
  396. // end include: runtime_debug.js
  397. // end include: support.js
  398. // === Preamble library stuff ===
  399. // Documentation for the public APIs defined in this file must be updated in:
  400. // site/source/docs/api_reference/preamble.js.rst
  401. // A prebuilt local version of the documentation is available at:
  402. // site/build/text/docs/api_reference/preamble.js.txt
  403. // You can also build docs locally as HTML or other formats in site/
  404. // An online HTML version (which may be of a different version of Emscripten)
  405. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  406. var wasmBinary;
  407. if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];legacyModuleProp('wasmBinary', 'wasmBinary');
  408. var noExitRuntime = Module['noExitRuntime'] || true;legacyModuleProp('noExitRuntime', 'noExitRuntime');
  409. if (typeof WebAssembly != 'object') {
  410. abort('no native wasm support detected');
  411. }
  412. // Wasm globals
  413. var wasmMemory;
  414. //========================================
  415. // Runtime essentials
  416. //========================================
  417. // whether we are quitting the application. no code should run after this.
  418. // set in exit() and abort()
  419. var ABORT = false;
  420. // set by exit() and abort(). Passed to 'onExit' handler.
  421. // NOTE: This is also used as the process return code code in shell environments
  422. // but only when noExitRuntime is false.
  423. var EXITSTATUS;
  424. /** @type {function(*, string=)} */
  425. function assert(condition, text) {
  426. if (!condition) {
  427. abort('Assertion failed' + (text ? ': ' + text : ''));
  428. }
  429. }
  430. // We used to include malloc/free by default in the past. Show a helpful error in
  431. // builds with assertions.
  432. // include: runtime_strings.js
  433. // runtime_strings.js: String related runtime functions that are part of both
  434. // MINIMAL_RUNTIME and regular runtime.
  435. var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;
  436. /**
  437. * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given
  438. * array that contains uint8 values, returns a copy of that string as a
  439. * Javascript String object.
  440. * heapOrArray is either a regular array, or a JavaScript typed array view.
  441. * @param {number} idx
  442. * @param {number=} maxBytesToRead
  443. * @return {string}
  444. */
  445. function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) {
  446. var endIdx = idx + maxBytesToRead;
  447. var endPtr = idx;
  448. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  449. // null terminator by itself. Also, use the length info to avoid running tiny
  450. // strings through TextDecoder, since .subarray() allocates garbage.
  451. // (As a tiny code save trick, compare endPtr against endIdx using a negation,
  452. // so that undefined means Infinity)
  453. while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
  454. if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
  455. return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
  456. }
  457. var str = '';
  458. // If building with TextDecoder, we have already computed the string length
  459. // above, so test loop end condition against that
  460. while (idx < endPtr) {
  461. // For UTF8 byte structure, see:
  462. // http://en.wikipedia.org/wiki/UTF-8#Description
  463. // https://www.ietf.org/rfc/rfc2279.txt
  464. // https://tools.ietf.org/html/rfc3629
  465. var u0 = heapOrArray[idx++];
  466. if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
  467. var u1 = heapOrArray[idx++] & 63;
  468. if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
  469. var u2 = heapOrArray[idx++] & 63;
  470. if ((u0 & 0xF0) == 0xE0) {
  471. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  472. } else {
  473. if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');
  474. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
  475. }
  476. if (u0 < 0x10000) {
  477. str += String.fromCharCode(u0);
  478. } else {
  479. var ch = u0 - 0x10000;
  480. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  481. }
  482. }
  483. return str;
  484. }
  485. /**
  486. * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the
  487. * emscripten HEAP, returns a copy of that string as a Javascript String object.
  488. *
  489. * @param {number} ptr
  490. * @param {number=} maxBytesToRead - An optional length that specifies the
  491. * maximum number of bytes to read. You can omit this parameter to scan the
  492. * string until the first \0 byte. If maxBytesToRead is passed, and the string
  493. * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the
  494. * string will cut short at that byte index (i.e. maxBytesToRead will not
  495. * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing
  496. * frequent uses of UTF8ToString() with and without maxBytesToRead may throw
  497. * JS JIT optimizations off, so it is worth to consider consistently using one
  498. * @return {string}
  499. */
  500. function UTF8ToString(ptr, maxBytesToRead) {
  501. return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
  502. }
  503. /**
  504. * Copies the given Javascript String object 'str' to the given byte array at
  505. * address 'outIdx', encoded in UTF8 form and null-terminated. The copy will
  506. * require at most str.length*4+1 bytes of space in the HEAP. Use the function
  507. * lengthBytesUTF8 to compute the exact number of bytes (excluding null
  508. * terminator) that this function will write.
  509. *
  510. * @param {string} str - The Javascript string to copy.
  511. * @param {ArrayBufferView|Array<number>} heap - The array to copy to. Each
  512. * index in this array is assumed
  513. * to be one 8-byte element.
  514. * @param {number} outIdx - The starting offset in the array to begin the copying.
  515. * @param {number} maxBytesToWrite - The maximum number of bytes this function
  516. * can write to the array. This count should
  517. * include the null terminator, i.e. if
  518. * maxBytesToWrite=1, only the null terminator
  519. * will be written and nothing else.
  520. * maxBytesToWrite=0 does not write any bytes
  521. * to the output, not even the null
  522. * terminator.
  523. * @return {number} The number of bytes written, EXCLUDING the null terminator.
  524. */
  525. function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
  526. // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
  527. // undefined and false each don't write out any bytes.
  528. if (!(maxBytesToWrite > 0))
  529. return 0;
  530. var startIdx = outIdx;
  531. var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
  532. for (var i = 0; i < str.length; ++i) {
  533. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  534. // unit, not a Unicode code point of the character! So decode
  535. // UTF16->UTF32->UTF8.
  536. // See http://unicode.org/faq/utf_bom.html#utf16-3
  537. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
  538. // and https://www.ietf.org/rfc/rfc2279.txt
  539. // and https://tools.ietf.org/html/rfc3629
  540. var u = str.charCodeAt(i); // possibly a lead surrogate
  541. if (u >= 0xD800 && u <= 0xDFFF) {
  542. var u1 = str.charCodeAt(++i);
  543. u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
  544. }
  545. if (u <= 0x7F) {
  546. if (outIdx >= endIdx) break;
  547. heap[outIdx++] = u;
  548. } else if (u <= 0x7FF) {
  549. if (outIdx + 1 >= endIdx) break;
  550. heap[outIdx++] = 0xC0 | (u >> 6);
  551. heap[outIdx++] = 0x80 | (u & 63);
  552. } else if (u <= 0xFFFF) {
  553. if (outIdx + 2 >= endIdx) break;
  554. heap[outIdx++] = 0xE0 | (u >> 12);
  555. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  556. heap[outIdx++] = 0x80 | (u & 63);
  557. } else {
  558. if (outIdx + 3 >= endIdx) break;
  559. if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).');
  560. heap[outIdx++] = 0xF0 | (u >> 18);
  561. heap[outIdx++] = 0x80 | ((u >> 12) & 63);
  562. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  563. heap[outIdx++] = 0x80 | (u & 63);
  564. }
  565. }
  566. // Null-terminate the pointer to the buffer.
  567. heap[outIdx] = 0;
  568. return outIdx - startIdx;
  569. }
  570. /**
  571. * Copies the given Javascript String object 'str' to the emscripten HEAP at
  572. * address 'outPtr', null-terminated and encoded in UTF8 form. The copy will
  573. * require at most str.length*4+1 bytes of space in the HEAP.
  574. * Use the function lengthBytesUTF8 to compute the exact number of bytes
  575. * (excluding null terminator) that this function will write.
  576. *
  577. * @return {number} The number of bytes written, EXCLUDING the null terminator.
  578. */
  579. function stringToUTF8(str, outPtr, maxBytesToWrite) {
  580. assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  581. return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
  582. }
  583. /**
  584. * Returns the number of bytes the given Javascript string takes if encoded as a
  585. * UTF8 byte array, EXCLUDING the null terminator byte.
  586. *
  587. * @param {string} str - JavaScript string to operator on
  588. * @return {number} Length, in bytes, of the UTF8 encoded string.
  589. */
  590. function lengthBytesUTF8(str) {
  591. var len = 0;
  592. for (var i = 0; i < str.length; ++i) {
  593. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  594. // unit, not a Unicode code point of the character! So decode
  595. // UTF16->UTF32->UTF8.
  596. // See http://unicode.org/faq/utf_bom.html#utf16-3
  597. var c = str.charCodeAt(i); // possibly a lead surrogate
  598. if (c <= 0x7F) {
  599. len++;
  600. } else if (c <= 0x7FF) {
  601. len += 2;
  602. } else if (c >= 0xD800 && c <= 0xDFFF) {
  603. len += 4; ++i;
  604. } else {
  605. len += 3;
  606. }
  607. }
  608. return len;
  609. }
  610. // end include: runtime_strings.js
  611. // Memory management
  612. var HEAP,
  613. /** @type {!Int8Array} */
  614. HEAP8,
  615. /** @type {!Uint8Array} */
  616. HEAPU8,
  617. /** @type {!Int16Array} */
  618. HEAP16,
  619. /** @type {!Uint16Array} */
  620. HEAPU16,
  621. /** @type {!Int32Array} */
  622. HEAP32,
  623. /** @type {!Uint32Array} */
  624. HEAPU32,
  625. /** @type {!Float32Array} */
  626. HEAPF32,
  627. /** @type {!Float64Array} */
  628. HEAPF64;
  629. function updateMemoryViews() {
  630. var b = wasmMemory.buffer;
  631. Module['HEAP8'] = HEAP8 = new Int8Array(b);
  632. Module['HEAP16'] = HEAP16 = new Int16Array(b);
  633. Module['HEAP32'] = HEAP32 = new Int32Array(b);
  634. Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
  635. Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
  636. Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
  637. Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
  638. Module['HEAPF64'] = HEAPF64 = new Float64Array(b);
  639. }
  640. var STACK_SIZE = 65536;
  641. if (Module['STACK_SIZE']) assert(STACK_SIZE === Module['STACK_SIZE'], 'the stack size can no longer be determined at runtime')
  642. var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;legacyModuleProp('INITIAL_MEMORY', 'INITIAL_MEMORY');
  643. assert(INITIAL_MEMORY >= STACK_SIZE, 'INITIAL_MEMORY should be larger than STACK_SIZE, was ' + INITIAL_MEMORY + '! (STACK_SIZE=' + STACK_SIZE + ')');
  644. // check for full engine support (use string 'subarray' to avoid closure compiler confusion)
  645. assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined,
  646. 'JS engine does not provide full typed array support');
  647. // If memory is defined in wasm, the user can't provide it.
  648. assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally');
  649. assert(INITIAL_MEMORY == 16777216, 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically');
  650. // include: runtime_init_table.js
  651. // In regular non-RELOCATABLE mode the table is exported
  652. // from the wasm module and this will be assigned once
  653. // the exports are available.
  654. var wasmTable;
  655. // end include: runtime_init_table.js
  656. // include: runtime_stack_check.js
  657. // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
  658. function writeStackCookie() {
  659. var max = _emscripten_stack_get_end();
  660. assert((max & 3) == 0);
  661. // If the stack ends at address zero we write our cookies 4 bytes into the
  662. // stack. This prevents interference with the (separate) address-zero check
  663. // below.
  664. if (max == 0) {
  665. max += 4;
  666. }
  667. // The stack grow downwards towards _emscripten_stack_get_end.
  668. // We write cookies to the final two words in the stack and detect if they are
  669. // ever overwritten.
  670. HEAPU32[((max)>>2)] = 0x2135467;
  671. HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE;
  672. // Also test the global address 0 for integrity.
  673. HEAPU32[0] = 0x63736d65; /* 'emsc' */
  674. }
  675. function checkStackCookie() {
  676. if (ABORT) return;
  677. var max = _emscripten_stack_get_end();
  678. // See writeStackCookie().
  679. if (max == 0) {
  680. max += 4;
  681. }
  682. var cookie1 = HEAPU32[((max)>>2)];
  683. var cookie2 = HEAPU32[(((max)+(4))>>2)];
  684. if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) {
  685. abort('Stack overflow! Stack cookie has been overwritten at ' + ptrToString(max) + ', expected hex dwords 0x89BACDFE and 0x2135467, but received ' + ptrToString(cookie2) + ' ' + ptrToString(cookie1));
  686. }
  687. // Also test the global address 0 for integrity.
  688. if (HEAPU32[0] !== 0x63736d65 /* 'emsc' */) {
  689. abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
  690. }
  691. }
  692. // end include: runtime_stack_check.js
  693. // include: runtime_assertions.js
  694. // Endianness check
  695. (function() {
  696. var h16 = new Int16Array(1);
  697. var h8 = new Int8Array(h16.buffer);
  698. h16[0] = 0x6373;
  699. if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)';
  700. })();
  701. // end include: runtime_assertions.js
  702. var __ATPRERUN__ = []; // functions called before the runtime is initialized
  703. var __ATINIT__ = []; // functions called during startup
  704. var __ATEXIT__ = []; // functions called during shutdown
  705. var __ATPOSTRUN__ = []; // functions called after the main() is called
  706. var runtimeInitialized = false;
  707. function keepRuntimeAlive() {
  708. return noExitRuntime;
  709. }
  710. function preRun() {
  711. if (Module['preRun']) {
  712. if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  713. while (Module['preRun'].length) {
  714. addOnPreRun(Module['preRun'].shift());
  715. }
  716. }
  717. callRuntimeCallbacks(__ATPRERUN__);
  718. }
  719. function initRuntime() {
  720. assert(!runtimeInitialized);
  721. runtimeInitialized = true;
  722. checkStackCookie();
  723. SOCKFS.root = FS.mount(SOCKFS, {}, null);
  724. if (!Module["noFSInit"] && !FS.init.initialized)
  725. FS.init();
  726. FS.ignorePermissions = false;
  727. TTY.init();
  728. callRuntimeCallbacks(__ATINIT__);
  729. }
  730. function postRun() {
  731. checkStackCookie();
  732. if (Module['postRun']) {
  733. if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  734. while (Module['postRun'].length) {
  735. addOnPostRun(Module['postRun'].shift());
  736. }
  737. }
  738. callRuntimeCallbacks(__ATPOSTRUN__);
  739. }
  740. function addOnPreRun(cb) {
  741. __ATPRERUN__.unshift(cb);
  742. }
  743. function addOnInit(cb) {
  744. __ATINIT__.unshift(cb);
  745. }
  746. function addOnExit(cb) {
  747. }
  748. function addOnPostRun(cb) {
  749. __ATPOSTRUN__.unshift(cb);
  750. }
  751. // include: runtime_math.js
  752. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  753. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
  754. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
  755. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  756. assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  757. assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  758. assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  759. assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  760. // end include: runtime_math.js
  761. // A counter of dependencies for calling run(). If we need to
  762. // do asynchronous work before running, increment this and
  763. // decrement it. Incrementing must happen in a place like
  764. // Module.preRun (used by emcc to add file preloading).
  765. // Note that you can add dependencies in preRun, even though
  766. // it happens right before run - run will be postponed until
  767. // the dependencies are met.
  768. var runDependencies = 0;
  769. var runDependencyWatcher = null;
  770. var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
  771. var runDependencyTracking = {};
  772. function getUniqueRunDependency(id) {
  773. var orig = id;
  774. while (1) {
  775. if (!runDependencyTracking[id]) return id;
  776. id = orig + Math.random();
  777. }
  778. }
  779. function addRunDependency(id) {
  780. runDependencies++;
  781. if (Module['monitorRunDependencies']) {
  782. Module['monitorRunDependencies'](runDependencies);
  783. }
  784. if (id) {
  785. assert(!runDependencyTracking[id]);
  786. runDependencyTracking[id] = 1;
  787. if (runDependencyWatcher === null && typeof setInterval != 'undefined') {
  788. // Check for missing dependencies every few seconds
  789. runDependencyWatcher = setInterval(function() {
  790. if (ABORT) {
  791. clearInterval(runDependencyWatcher);
  792. runDependencyWatcher = null;
  793. return;
  794. }
  795. var shown = false;
  796. for (var dep in runDependencyTracking) {
  797. if (!shown) {
  798. shown = true;
  799. err('still waiting on run dependencies:');
  800. }
  801. err('dependency: ' + dep);
  802. }
  803. if (shown) {
  804. err('(end of list)');
  805. }
  806. }, 10000);
  807. }
  808. } else {
  809. err('warning: run dependency added without ID');
  810. }
  811. }
  812. function removeRunDependency(id) {
  813. runDependencies--;
  814. if (Module['monitorRunDependencies']) {
  815. Module['monitorRunDependencies'](runDependencies);
  816. }
  817. if (id) {
  818. assert(runDependencyTracking[id]);
  819. delete runDependencyTracking[id];
  820. } else {
  821. err('warning: run dependency removed without ID');
  822. }
  823. if (runDependencies == 0) {
  824. if (runDependencyWatcher !== null) {
  825. clearInterval(runDependencyWatcher);
  826. runDependencyWatcher = null;
  827. }
  828. if (dependenciesFulfilled) {
  829. var callback = dependenciesFulfilled;
  830. dependenciesFulfilled = null;
  831. callback(); // can add another dependenciesFulfilled
  832. }
  833. }
  834. }
  835. /** @param {string|number=} what */
  836. function abort(what) {
  837. if (Module['onAbort']) {
  838. Module['onAbort'](what);
  839. }
  840. what = 'Aborted(' + what + ')';
  841. // TODO(sbc): Should we remove printing and leave it up to whoever
  842. // catches the exception?
  843. err(what);
  844. ABORT = true;
  845. EXITSTATUS = 1;
  846. // Use a wasm runtime error, because a JS error might be seen as a foreign
  847. // exception, which means we'd run destructors on it. We need the error to
  848. // simply make the program stop.
  849. // FIXME This approach does not work in Wasm EH because it currently does not assume
  850. // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
  851. // a trap or not based on a hidden field within the object. So at the moment
  852. // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
  853. // allows this in the wasm spec.
  854. // Suppress closure compiler warning here. Closure compiler's builtin extern
  855. // defintion for WebAssembly.RuntimeError claims it takes no arguments even
  856. // though it can.
  857. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
  858. /** @suppress {checkTypes} */
  859. var e = new WebAssembly.RuntimeError(what);
  860. readyPromiseReject(e);
  861. // Throw the error whether or not MODULARIZE is set because abort is used
  862. // in code paths apart from instantiation where an exception is expected
  863. // to be thrown when abort is called.
  864. throw e;
  865. }
  866. // {{MEM_INITIALIZER}}
  867. // include: memoryprofiler.js
  868. // end include: memoryprofiler.js
  869. // include: URIUtils.js
  870. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  871. var dataURIPrefix = 'data:application/octet-stream;base64,';
  872. // Indicates whether filename is a base64 data URI.
  873. function isDataURI(filename) {
  874. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  875. return filename.startsWith(dataURIPrefix);
  876. }
  877. // Indicates whether filename is delivered via file protocol (as opposed to http/https)
  878. function isFileURI(filename) {
  879. return filename.startsWith('file://');
  880. }
  881. // end include: URIUtils.js
  882. /** @param {boolean=} fixedasm */
  883. function createExportWrapper(name, fixedasm) {
  884. return function() {
  885. var displayName = name;
  886. var asm = fixedasm;
  887. if (!fixedasm) {
  888. asm = Module['asm'];
  889. }
  890. assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization');
  891. if (!asm[name]) {
  892. assert(asm[name], 'exported native function `' + displayName + '` not found');
  893. }
  894. return asm[name].apply(null, arguments);
  895. };
  896. }
  897. var wasmBinaryFile;
  898. wasmBinaryFile = 'rhino3dm.wasm';
  899. if (!isDataURI(wasmBinaryFile)) {
  900. wasmBinaryFile = locateFile(wasmBinaryFile);
  901. }
  902. function getBinary(file) {
  903. try {
  904. if (file == wasmBinaryFile && wasmBinary) {
  905. return new Uint8Array(wasmBinary);
  906. }
  907. if (readBinary) {
  908. return readBinary(file);
  909. }
  910. throw "both async and sync fetching of the wasm failed";
  911. }
  912. catch (err) {
  913. abort(err);
  914. }
  915. }
  916. function getBinaryPromise() {
  917. // If we don't have the binary yet, try to to load it asynchronously.
  918. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
  919. // See https://github.com/github/fetch/pull/92#issuecomment-140665932
  920. // Cordova or Electron apps are typically loaded from a file:// url.
  921. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR.
  922. if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
  923. if (typeof fetch == 'function'
  924. && !isFileURI(wasmBinaryFile)
  925. ) {
  926. return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
  927. if (!response['ok']) {
  928. throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
  929. }
  930. return response['arrayBuffer']();
  931. }).catch(function () {
  932. return getBinary(wasmBinaryFile);
  933. });
  934. }
  935. else {
  936. if (readAsync) {
  937. // fetch is not available or url is file => try XHR (readAsync uses XHR internally)
  938. return new Promise(function(resolve, reject) {
  939. readAsync(wasmBinaryFile, function(response) { resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))) }, reject)
  940. });
  941. }
  942. }
  943. }
  944. // Otherwise, getBinary should be able to get it synchronously
  945. return Promise.resolve().then(function() { return getBinary(wasmBinaryFile); });
  946. }
  947. // Create the wasm instance.
  948. // Receives the wasm imports, returns the exports.
  949. function createWasm() {
  950. // prepare imports
  951. var info = {
  952. 'env': asmLibraryArg,
  953. 'wasi_snapshot_preview1': asmLibraryArg,
  954. };
  955. // Load the wasm module and create an instance of using native support in the JS engine.
  956. // handle a generated wasm instance, receiving its exports and
  957. // performing other necessary setup
  958. /** @param {WebAssembly.Module=} module*/
  959. function receiveInstance(instance, module) {
  960. var exports = instance.exports;
  961. Module['asm'] = exports;
  962. wasmMemory = Module['asm']['memory'];
  963. assert(wasmMemory, "memory not found in wasm exports");
  964. // This assertion doesn't hold when emscripten is run in --post-link
  965. // mode.
  966. // TODO(sbc): Read INITIAL_MEMORY out of the wasm file in post-link mode.
  967. //assert(wasmMemory.buffer.byteLength === 16777216);
  968. updateMemoryViews();
  969. wasmTable = Module['asm']['__indirect_function_table'];
  970. assert(wasmTable, "table not found in wasm exports");
  971. addOnInit(Module['asm']['__wasm_call_ctors']);
  972. removeRunDependency('wasm-instantiate');
  973. }
  974. // wait for the pthread pool (if any)
  975. addRunDependency('wasm-instantiate');
  976. // Prefer streaming instantiation if available.
  977. // Async compilation can be confusing when an error on the page overwrites Module
  978. // (for example, if the order of elements is wrong, and the one defining Module is
  979. // later), so we save Module and check it later.
  980. var trueModule = Module;
  981. function receiveInstantiationResult(result) {
  982. // 'result' is a ResultObject object which has both the module and instance.
  983. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  984. assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
  985. trueModule = null;
  986. // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.
  987. // When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
  988. receiveInstance(result['instance']);
  989. }
  990. function instantiateArrayBuffer(receiver) {
  991. return getBinaryPromise().then(function(binary) {
  992. return WebAssembly.instantiate(binary, info);
  993. }).then(function (instance) {
  994. return instance;
  995. }).then(receiver, function(reason) {
  996. err('failed to asynchronously prepare wasm: ' + reason);
  997. // Warn on some common problems.
  998. if (isFileURI(wasmBinaryFile)) {
  999. err('warning: Loading from a file URI (' + wasmBinaryFile + ') is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing');
  1000. }
  1001. abort(reason);
  1002. });
  1003. }
  1004. function instantiateAsync() {
  1005. if (!wasmBinary &&
  1006. typeof WebAssembly.instantiateStreaming == 'function' &&
  1007. !isDataURI(wasmBinaryFile) &&
  1008. // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
  1009. !isFileURI(wasmBinaryFile) &&
  1010. // Avoid instantiateStreaming() on Node.js environment for now, as while
  1011. // Node.js v18.1.0 implements it, it does not have a full fetch()
  1012. // implementation yet.
  1013. //
  1014. // Reference:
  1015. // https://github.com/emscripten-core/emscripten/pull/16917
  1016. !ENVIRONMENT_IS_NODE &&
  1017. typeof fetch == 'function') {
  1018. return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
  1019. // Suppress closure warning here since the upstream definition for
  1020. // instantiateStreaming only allows Promise<Repsponse> rather than
  1021. // an actual Response.
  1022. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
  1023. /** @suppress {checkTypes} */
  1024. var result = WebAssembly.instantiateStreaming(response, info);
  1025. return result.then(
  1026. receiveInstantiationResult,
  1027. function(reason) {
  1028. // We expect the most common failure cause to be a bad MIME type for the binary,
  1029. // in which case falling back to ArrayBuffer instantiation should work.
  1030. err('wasm streaming compile failed: ' + reason);
  1031. err('falling back to ArrayBuffer instantiation');
  1032. return instantiateArrayBuffer(receiveInstantiationResult);
  1033. });
  1034. });
  1035. } else {
  1036. return instantiateArrayBuffer(receiveInstantiationResult);
  1037. }
  1038. }
  1039. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  1040. // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
  1041. // to any other async startup actions they are performing.
  1042. // Also pthreads and wasm workers initialize the wasm instance through this path.
  1043. if (Module['instantiateWasm']) {
  1044. try {
  1045. var exports = Module['instantiateWasm'](info, receiveInstance);
  1046. return exports;
  1047. } catch(e) {
  1048. err('Module.instantiateWasm callback failed with error: ' + e);
  1049. // If instantiation fails, reject the module ready promise.
  1050. readyPromiseReject(e);
  1051. }
  1052. }
  1053. // If instantiation fails, reject the module ready promise.
  1054. instantiateAsync().catch(readyPromiseReject);
  1055. return {}; // no exports yet; we'll fill them in later
  1056. }
  1057. // Globals used by JS i64 conversions (see makeSetValue)
  1058. var tempDouble;
  1059. var tempI64;
  1060. // === Body ===
  1061. var ASM_CONSTS = {
  1062. };
  1063. /** @constructor */
  1064. function ExitStatus(status) {
  1065. this.name = 'ExitStatus';
  1066. this.message = 'Program terminated with exit(' + status + ')';
  1067. this.status = status;
  1068. }
  1069. function callRuntimeCallbacks(callbacks) {
  1070. while (callbacks.length > 0) {
  1071. // Pass the module as the first argument.
  1072. callbacks.shift()(Module);
  1073. }
  1074. }
  1075. /**
  1076. * @param {number} ptr
  1077. * @param {string} type
  1078. */
  1079. function getValue(ptr, type = 'i8') {
  1080. if (type.endsWith('*')) type = '*';
  1081. switch (type) {
  1082. case 'i1': return HEAP8[((ptr)>>0)];
  1083. case 'i8': return HEAP8[((ptr)>>0)];
  1084. case 'i16': return HEAP16[((ptr)>>1)];
  1085. case 'i32': return HEAP32[((ptr)>>2)];
  1086. case 'i64': return HEAP32[((ptr)>>2)];
  1087. case 'float': return HEAPF32[((ptr)>>2)];
  1088. case 'double': return HEAPF64[((ptr)>>3)];
  1089. case '*': return HEAPU32[((ptr)>>2)];
  1090. default: abort('invalid type for getValue: ' + type);
  1091. }
  1092. return null;
  1093. }
  1094. function ptrToString(ptr) {
  1095. assert(typeof ptr === 'number');
  1096. return '0x' + ptr.toString(16).padStart(8, '0');
  1097. }
  1098. /**
  1099. * @param {number} ptr
  1100. * @param {number} value
  1101. * @param {string} type
  1102. */
  1103. function setValue(ptr, value, type = 'i8') {
  1104. if (type.endsWith('*')) type = '*';
  1105. switch (type) {
  1106. case 'i1': HEAP8[((ptr)>>0)] = value; break;
  1107. case 'i8': HEAP8[((ptr)>>0)] = value; break;
  1108. case 'i16': HEAP16[((ptr)>>1)] = value; break;
  1109. case 'i32': HEAP32[((ptr)>>2)] = value; break;
  1110. case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)] = tempI64[0],HEAP32[(((ptr)+(4))>>2)] = tempI64[1]); break;
  1111. case 'float': HEAPF32[((ptr)>>2)] = value; break;
  1112. case 'double': HEAPF64[((ptr)>>3)] = value; break;
  1113. case '*': HEAPU32[((ptr)>>2)] = value; break;
  1114. default: abort('invalid type for setValue: ' + type);
  1115. }
  1116. }
  1117. function warnOnce(text) {
  1118. if (!warnOnce.shown) warnOnce.shown = {};
  1119. if (!warnOnce.shown[text]) {
  1120. warnOnce.shown[text] = 1;
  1121. if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;
  1122. err(text);
  1123. }
  1124. }
  1125. function ___assert_fail(condition, filename, line, func) {
  1126. abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
  1127. }
  1128. /** @constructor */
  1129. function ExceptionInfo(excPtr) {
  1130. this.excPtr = excPtr;
  1131. this.ptr = excPtr - 24;
  1132. this.set_type = function(type) {
  1133. HEAPU32[(((this.ptr)+(4))>>2)] = type;
  1134. };
  1135. this.get_type = function() {
  1136. return HEAPU32[(((this.ptr)+(4))>>2)];
  1137. };
  1138. this.set_destructor = function(destructor) {
  1139. HEAPU32[(((this.ptr)+(8))>>2)] = destructor;
  1140. };
  1141. this.get_destructor = function() {
  1142. return HEAPU32[(((this.ptr)+(8))>>2)];
  1143. };
  1144. this.set_refcount = function(refcount) {
  1145. HEAP32[((this.ptr)>>2)] = refcount;
  1146. };
  1147. this.set_caught = function (caught) {
  1148. caught = caught ? 1 : 0;
  1149. HEAP8[(((this.ptr)+(12))>>0)] = caught;
  1150. };
  1151. this.get_caught = function () {
  1152. return HEAP8[(((this.ptr)+(12))>>0)] != 0;
  1153. };
  1154. this.set_rethrown = function (rethrown) {
  1155. rethrown = rethrown ? 1 : 0;
  1156. HEAP8[(((this.ptr)+(13))>>0)] = rethrown;
  1157. };
  1158. this.get_rethrown = function () {
  1159. return HEAP8[(((this.ptr)+(13))>>0)] != 0;
  1160. };
  1161. // Initialize native structure fields. Should be called once after allocated.
  1162. this.init = function(type, destructor) {
  1163. this.set_adjusted_ptr(0);
  1164. this.set_type(type);
  1165. this.set_destructor(destructor);
  1166. this.set_refcount(0);
  1167. this.set_caught(false);
  1168. this.set_rethrown(false);
  1169. }
  1170. this.add_ref = function() {
  1171. var value = HEAP32[((this.ptr)>>2)];
  1172. HEAP32[((this.ptr)>>2)] = value + 1;
  1173. };
  1174. // Returns true if last reference released.
  1175. this.release_ref = function() {
  1176. var prev = HEAP32[((this.ptr)>>2)];
  1177. HEAP32[((this.ptr)>>2)] = prev - 1;
  1178. assert(prev > 0);
  1179. return prev === 1;
  1180. };
  1181. this.set_adjusted_ptr = function(adjustedPtr) {
  1182. HEAPU32[(((this.ptr)+(16))>>2)] = adjustedPtr;
  1183. };
  1184. this.get_adjusted_ptr = function() {
  1185. return HEAPU32[(((this.ptr)+(16))>>2)];
  1186. };
  1187. // Get pointer which is expected to be received by catch clause in C++ code. It may be adjusted
  1188. // when the pointer is casted to some of the exception object base classes (e.g. when virtual
  1189. // inheritance is used). When a pointer is thrown this method should return the thrown pointer
  1190. // itself.
  1191. this.get_exception_ptr = function() {
  1192. // Work around a fastcomp bug, this code is still included for some reason in a build without
  1193. // exceptions support.
  1194. var isPointer = ___cxa_is_pointer_type(this.get_type());
  1195. if (isPointer) {
  1196. return HEAPU32[((this.excPtr)>>2)];
  1197. }
  1198. var adjusted = this.get_adjusted_ptr();
  1199. if (adjusted !== 0) return adjusted;
  1200. return this.excPtr;
  1201. };
  1202. }
  1203. var exceptionLast = 0;
  1204. var uncaughtExceptionCount = 0;
  1205. function ___cxa_throw(ptr, type, destructor) {
  1206. var info = new ExceptionInfo(ptr);
  1207. // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.
  1208. info.init(type, destructor);
  1209. exceptionLast = ptr;
  1210. uncaughtExceptionCount++;
  1211. throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch.";
  1212. }
  1213. function getRandomDevice() {
  1214. if (typeof crypto == 'object' && typeof crypto['getRandomValues'] == 'function') {
  1215. // for modern web browsers
  1216. var randomBuffer = new Uint8Array(1);
  1217. return () => { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
  1218. } else
  1219. if (ENVIRONMENT_IS_NODE) {
  1220. // for nodejs with or without crypto support included
  1221. try {
  1222. var crypto_module = require('crypto');
  1223. // nodejs has crypto support
  1224. return () => crypto_module['randomBytes'](1)[0];
  1225. } catch (e) {
  1226. // nodejs doesn't have crypto support
  1227. }
  1228. }
  1229. // we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096
  1230. return () => abort("no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: function(array) { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };");
  1231. }
  1232. var PATH = {isAbs:(path) => path.charAt(0) === '/',splitPath:(filename) => {
  1233. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  1234. return splitPathRe.exec(filename).slice(1);
  1235. },normalizeArray:(parts, allowAboveRoot) => {
  1236. // if the path tries to go above the root, `up` ends up > 0
  1237. var up = 0;
  1238. for (var i = parts.length - 1; i >= 0; i--) {
  1239. var last = parts[i];
  1240. if (last === '.') {
  1241. parts.splice(i, 1);
  1242. } else if (last === '..') {
  1243. parts.splice(i, 1);
  1244. up++;
  1245. } else if (up) {
  1246. parts.splice(i, 1);
  1247. up--;
  1248. }
  1249. }
  1250. // if the path is allowed to go above the root, restore leading ..s
  1251. if (allowAboveRoot) {
  1252. for (; up; up--) {
  1253. parts.unshift('..');
  1254. }
  1255. }
  1256. return parts;
  1257. },normalize:(path) => {
  1258. var isAbsolute = PATH.isAbs(path),
  1259. trailingSlash = path.substr(-1) === '/';
  1260. // Normalize the path
  1261. path = PATH.normalizeArray(path.split('/').filter((p) => !!p), !isAbsolute).join('/');
  1262. if (!path && !isAbsolute) {
  1263. path = '.';
  1264. }
  1265. if (path && trailingSlash) {
  1266. path += '/';
  1267. }
  1268. return (isAbsolute ? '/' : '') + path;
  1269. },dirname:(path) => {
  1270. var result = PATH.splitPath(path),
  1271. root = result[0],
  1272. dir = result[1];
  1273. if (!root && !dir) {
  1274. // No dirname whatsoever
  1275. return '.';
  1276. }
  1277. if (dir) {
  1278. // It has a dirname, strip trailing slash
  1279. dir = dir.substr(0, dir.length - 1);
  1280. }
  1281. return root + dir;
  1282. },basename:(path) => {
  1283. // EMSCRIPTEN return '/'' for '/', not an empty string
  1284. if (path === '/') return '/';
  1285. path = PATH.normalize(path);
  1286. path = path.replace(/\/$/, "");
  1287. var lastSlash = path.lastIndexOf('/');
  1288. if (lastSlash === -1) return path;
  1289. return path.substr(lastSlash+1);
  1290. },join:function() {
  1291. var paths = Array.prototype.slice.call(arguments);
  1292. return PATH.normalize(paths.join('/'));
  1293. },join2:(l, r) => {
  1294. return PATH.normalize(l + '/' + r);
  1295. }};
  1296. var PATH_FS = {resolve:function() {
  1297. var resolvedPath = '',
  1298. resolvedAbsolute = false;
  1299. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1300. var path = (i >= 0) ? arguments[i] : FS.cwd();
  1301. // Skip empty and invalid entries
  1302. if (typeof path != 'string') {
  1303. throw new TypeError('Arguments to path.resolve must be strings');
  1304. } else if (!path) {
  1305. return ''; // an invalid portion invalidates the whole thing
  1306. }
  1307. resolvedPath = path + '/' + resolvedPath;
  1308. resolvedAbsolute = PATH.isAbs(path);
  1309. }
  1310. // At this point the path should be resolved to a full absolute path, but
  1311. // handle relative paths to be safe (might happen when process.cwd() fails)
  1312. resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter((p) => !!p), !resolvedAbsolute).join('/');
  1313. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1314. },relative:(from, to) => {
  1315. from = PATH_FS.resolve(from).substr(1);
  1316. to = PATH_FS.resolve(to).substr(1);
  1317. function trim(arr) {
  1318. var start = 0;
  1319. for (; start < arr.length; start++) {
  1320. if (arr[start] !== '') break;
  1321. }
  1322. var end = arr.length - 1;
  1323. for (; end >= 0; end--) {
  1324. if (arr[end] !== '') break;
  1325. }
  1326. if (start > end) return [];
  1327. return arr.slice(start, end - start + 1);
  1328. }
  1329. var fromParts = trim(from.split('/'));
  1330. var toParts = trim(to.split('/'));
  1331. var length = Math.min(fromParts.length, toParts.length);
  1332. var samePartsLength = length;
  1333. for (var i = 0; i < length; i++) {
  1334. if (fromParts[i] !== toParts[i]) {
  1335. samePartsLength = i;
  1336. break;
  1337. }
  1338. }
  1339. var outputParts = [];
  1340. for (var i = samePartsLength; i < fromParts.length; i++) {
  1341. outputParts.push('..');
  1342. }
  1343. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1344. return outputParts.join('/');
  1345. }};
  1346. /** @type {function(string, boolean=, number=)} */
  1347. function intArrayFromString(stringy, dontAddNull, length) {
  1348. var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
  1349. var u8array = new Array(len);
  1350. var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
  1351. if (dontAddNull) u8array.length = numBytesWritten;
  1352. return u8array;
  1353. }
  1354. var TTY = {ttys:[],init:function () {
  1355. // https://github.com/emscripten-core/emscripten/pull/1555
  1356. // if (ENVIRONMENT_IS_NODE) {
  1357. // // currently, FS.init does not distinguish if process.stdin is a file or TTY
  1358. // // device, it always assumes it's a TTY device. because of this, we're forcing
  1359. // // process.stdin to UTF8 encoding to at least make stdin reading compatible
  1360. // // with text files until FS.init can be refactored.
  1361. // process['stdin']['setEncoding']('utf8');
  1362. // }
  1363. },shutdown:function() {
  1364. // https://github.com/emscripten-core/emscripten/pull/1555
  1365. // if (ENVIRONMENT_IS_NODE) {
  1366. // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
  1367. // // 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
  1368. // // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
  1369. // // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
  1370. // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
  1371. // process['stdin']['pause']();
  1372. // }
  1373. },register:function(dev, ops) {
  1374. TTY.ttys[dev] = { input: [], output: [], ops: ops };
  1375. FS.registerDevice(dev, TTY.stream_ops);
  1376. },stream_ops:{open:function(stream) {
  1377. var tty = TTY.ttys[stream.node.rdev];
  1378. if (!tty) {
  1379. throw new FS.ErrnoError(43);
  1380. }
  1381. stream.tty = tty;
  1382. stream.seekable = false;
  1383. },close:function(stream) {
  1384. // flush any pending line data
  1385. stream.tty.ops.fsync(stream.tty);
  1386. },fsync:function(stream) {
  1387. stream.tty.ops.fsync(stream.tty);
  1388. },read:function(stream, buffer, offset, length, pos /* ignored */) {
  1389. if (!stream.tty || !stream.tty.ops.get_char) {
  1390. throw new FS.ErrnoError(60);
  1391. }
  1392. var bytesRead = 0;
  1393. for (var i = 0; i < length; i++) {
  1394. var result;
  1395. try {
  1396. result = stream.tty.ops.get_char(stream.tty);
  1397. } catch (e) {
  1398. throw new FS.ErrnoError(29);
  1399. }
  1400. if (result === undefined && bytesRead === 0) {
  1401. throw new FS.ErrnoError(6);
  1402. }
  1403. if (result === null || result === undefined) break;
  1404. bytesRead++;
  1405. buffer[offset+i] = result;
  1406. }
  1407. if (bytesRead) {
  1408. stream.node.timestamp = Date.now();
  1409. }
  1410. return bytesRead;
  1411. },write:function(stream, buffer, offset, length, pos) {
  1412. if (!stream.tty || !stream.tty.ops.put_char) {
  1413. throw new FS.ErrnoError(60);
  1414. }
  1415. try {
  1416. for (var i = 0; i < length; i++) {
  1417. stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
  1418. }
  1419. } catch (e) {
  1420. throw new FS.ErrnoError(29);
  1421. }
  1422. if (length) {
  1423. stream.node.timestamp = Date.now();
  1424. }
  1425. return i;
  1426. }},default_tty_ops:{get_char:function(tty) {
  1427. if (!tty.input.length) {
  1428. var result = null;
  1429. if (ENVIRONMENT_IS_NODE) {
  1430. // we will read data by chunks of BUFSIZE
  1431. var BUFSIZE = 256;
  1432. var buf = Buffer.alloc(BUFSIZE);
  1433. var bytesRead = 0;
  1434. try {
  1435. bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE, -1);
  1436. } catch(e) {
  1437. // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
  1438. // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
  1439. if (e.toString().includes('EOF')) bytesRead = 0;
  1440. else throw e;
  1441. }
  1442. if (bytesRead > 0) {
  1443. result = buf.slice(0, bytesRead).toString('utf-8');
  1444. } else {
  1445. result = null;
  1446. }
  1447. } else
  1448. if (typeof window != 'undefined' &&
  1449. typeof window.prompt == 'function') {
  1450. // Browser.
  1451. result = window.prompt('Input: '); // returns null on cancel
  1452. if (result !== null) {
  1453. result += '\n';
  1454. }
  1455. } else if (typeof readline == 'function') {
  1456. // Command line.
  1457. result = readline();
  1458. if (result !== null) {
  1459. result += '\n';
  1460. }
  1461. }
  1462. if (!result) {
  1463. return null;
  1464. }
  1465. tty.input = intArrayFromString(result, true);
  1466. }
  1467. return tty.input.shift();
  1468. },put_char:function(tty, val) {
  1469. if (val === null || val === 10) {
  1470. out(UTF8ArrayToString(tty.output, 0));
  1471. tty.output = [];
  1472. } else {
  1473. if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
  1474. }
  1475. },fsync:function(tty) {
  1476. if (tty.output && tty.output.length > 0) {
  1477. out(UTF8ArrayToString(tty.output, 0));
  1478. tty.output = [];
  1479. }
  1480. }},default_tty1_ops:{put_char:function(tty, val) {
  1481. if (val === null || val === 10) {
  1482. err(UTF8ArrayToString(tty.output, 0));
  1483. tty.output = [];
  1484. } else {
  1485. if (val != 0) tty.output.push(val);
  1486. }
  1487. },fsync:function(tty) {
  1488. if (tty.output && tty.output.length > 0) {
  1489. err(UTF8ArrayToString(tty.output, 0));
  1490. tty.output = [];
  1491. }
  1492. }}};
  1493. function zeroMemory(address, size) {
  1494. HEAPU8.fill(0, address, address + size);
  1495. return address;
  1496. }
  1497. function alignMemory(size, alignment) {
  1498. assert(alignment, "alignment argument is required");
  1499. return Math.ceil(size / alignment) * alignment;
  1500. }
  1501. function mmapAlloc(size) {
  1502. abort('internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported');
  1503. }
  1504. var MEMFS = {ops_table:null,mount:function(mount) {
  1505. return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  1506. },createNode:function(parent, name, mode, dev) {
  1507. if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
  1508. // no supported
  1509. throw new FS.ErrnoError(63);
  1510. }
  1511. if (!MEMFS.ops_table) {
  1512. MEMFS.ops_table = {
  1513. dir: {
  1514. node: {
  1515. getattr: MEMFS.node_ops.getattr,
  1516. setattr: MEMFS.node_ops.setattr,
  1517. lookup: MEMFS.node_ops.lookup,
  1518. mknod: MEMFS.node_ops.mknod,
  1519. rename: MEMFS.node_ops.rename,
  1520. unlink: MEMFS.node_ops.unlink,
  1521. rmdir: MEMFS.node_ops.rmdir,
  1522. readdir: MEMFS.node_ops.readdir,
  1523. symlink: MEMFS.node_ops.symlink
  1524. },
  1525. stream: {
  1526. llseek: MEMFS.stream_ops.llseek
  1527. }
  1528. },
  1529. file: {
  1530. node: {
  1531. getattr: MEMFS.node_ops.getattr,
  1532. setattr: MEMFS.node_ops.setattr
  1533. },
  1534. stream: {
  1535. llseek: MEMFS.stream_ops.llseek,
  1536. read: MEMFS.stream_ops.read,
  1537. write: MEMFS.stream_ops.write,
  1538. allocate: MEMFS.stream_ops.allocate,
  1539. mmap: MEMFS.stream_ops.mmap,
  1540. msync: MEMFS.stream_ops.msync
  1541. }
  1542. },
  1543. link: {
  1544. node: {
  1545. getattr: MEMFS.node_ops.getattr,
  1546. setattr: MEMFS.node_ops.setattr,
  1547. readlink: MEMFS.node_ops.readlink
  1548. },
  1549. stream: {}
  1550. },
  1551. chrdev: {
  1552. node: {
  1553. getattr: MEMFS.node_ops.getattr,
  1554. setattr: MEMFS.node_ops.setattr
  1555. },
  1556. stream: FS.chrdev_stream_ops
  1557. }
  1558. };
  1559. }
  1560. var node = FS.createNode(parent, name, mode, dev);
  1561. if (FS.isDir(node.mode)) {
  1562. node.node_ops = MEMFS.ops_table.dir.node;
  1563. node.stream_ops = MEMFS.ops_table.dir.stream;
  1564. node.contents = {};
  1565. } else if (FS.isFile(node.mode)) {
  1566. node.node_ops = MEMFS.ops_table.file.node;
  1567. node.stream_ops = MEMFS.ops_table.file.stream;
  1568. node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
  1569. // When the byte data of the file is populated, this will point to either a typed array, or a normal JS array. Typed arrays are preferred
  1570. // for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
  1571. // penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
  1572. node.contents = null;
  1573. } else if (FS.isLink(node.mode)) {
  1574. node.node_ops = MEMFS.ops_table.link.node;
  1575. node.stream_ops = MEMFS.ops_table.link.stream;
  1576. } else if (FS.isChrdev(node.mode)) {
  1577. node.node_ops = MEMFS.ops_table.chrdev.node;
  1578. node.stream_ops = MEMFS.ops_table.chrdev.stream;
  1579. }
  1580. node.timestamp = Date.now();
  1581. // add the new node to the parent
  1582. if (parent) {
  1583. parent.contents[name] = node;
  1584. parent.timestamp = node.timestamp;
  1585. }
  1586. return node;
  1587. },getFileDataAsTypedArray:function(node) {
  1588. if (!node.contents) return new Uint8Array(0);
  1589. if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
  1590. return new Uint8Array(node.contents);
  1591. },expandFileStorage:function(node, newCapacity) {
  1592. var prevCapacity = node.contents ? node.contents.length : 0;
  1593. if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
  1594. // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
  1595. // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
  1596. // avoid overshooting the allocation cap by a very large margin.
  1597. var CAPACITY_DOUBLING_MAX = 1024 * 1024;
  1598. newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>> 0);
  1599. if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
  1600. var oldContents = node.contents;
  1601. node.contents = new Uint8Array(newCapacity); // Allocate new storage.
  1602. if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
  1603. },resizeFileStorage:function(node, newSize) {
  1604. if (node.usedBytes == newSize) return;
  1605. if (newSize == 0) {
  1606. node.contents = null; // Fully decommit when requesting a resize to zero.
  1607. node.usedBytes = 0;
  1608. } else {
  1609. var oldContents = node.contents;
  1610. node.contents = new Uint8Array(newSize); // Allocate new storage.
  1611. if (oldContents) {
  1612. node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
  1613. }
  1614. node.usedBytes = newSize;
  1615. }
  1616. },node_ops:{getattr:function(node) {
  1617. var attr = {};
  1618. // device numbers reuse inode numbers.
  1619. attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
  1620. attr.ino = node.id;
  1621. attr.mode = node.mode;
  1622. attr.nlink = 1;
  1623. attr.uid = 0;
  1624. attr.gid = 0;
  1625. attr.rdev = node.rdev;
  1626. if (FS.isDir(node.mode)) {
  1627. attr.size = 4096;
  1628. } else if (FS.isFile(node.mode)) {
  1629. attr.size = node.usedBytes;
  1630. } else if (FS.isLink(node.mode)) {
  1631. attr.size = node.link.length;
  1632. } else {
  1633. attr.size = 0;
  1634. }
  1635. attr.atime = new Date(node.timestamp);
  1636. attr.mtime = new Date(node.timestamp);
  1637. attr.ctime = new Date(node.timestamp);
  1638. // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
  1639. // but this is not required by the standard.
  1640. attr.blksize = 4096;
  1641. attr.blocks = Math.ceil(attr.size / attr.blksize);
  1642. return attr;
  1643. },setattr:function(node, attr) {
  1644. if (attr.mode !== undefined) {
  1645. node.mode = attr.mode;
  1646. }
  1647. if (attr.timestamp !== undefined) {
  1648. node.timestamp = attr.timestamp;
  1649. }
  1650. if (attr.size !== undefined) {
  1651. MEMFS.resizeFileStorage(node, attr.size);
  1652. }
  1653. },lookup:function(parent, name) {
  1654. throw FS.genericErrors[44];
  1655. },mknod:function(parent, name, mode, dev) {
  1656. return MEMFS.createNode(parent, name, mode, dev);
  1657. },rename:function(old_node, new_dir, new_name) {
  1658. // if we're overwriting a directory at new_name, make sure it's empty.
  1659. if (FS.isDir(old_node.mode)) {
  1660. var new_node;
  1661. try {
  1662. new_node = FS.lookupNode(new_dir, new_name);
  1663. } catch (e) {
  1664. }
  1665. if (new_node) {
  1666. for (var i in new_node.contents) {
  1667. throw new FS.ErrnoError(55);
  1668. }
  1669. }
  1670. }
  1671. // do the internal rewiring
  1672. delete old_node.parent.contents[old_node.name];
  1673. old_node.parent.timestamp = Date.now()
  1674. old_node.name = new_name;
  1675. new_dir.contents[new_name] = old_node;
  1676. new_dir.timestamp = old_node.parent.timestamp;
  1677. old_node.parent = new_dir;
  1678. },unlink:function(parent, name) {
  1679. delete parent.contents[name];
  1680. parent.timestamp = Date.now();
  1681. },rmdir:function(parent, name) {
  1682. var node = FS.lookupNode(parent, name);
  1683. for (var i in node.contents) {
  1684. throw new FS.ErrnoError(55);
  1685. }
  1686. delete parent.contents[name];
  1687. parent.timestamp = Date.now();
  1688. },readdir:function(node) {
  1689. var entries = ['.', '..'];
  1690. for (var key in node.contents) {
  1691. if (!node.contents.hasOwnProperty(key)) {
  1692. continue;
  1693. }
  1694. entries.push(key);
  1695. }
  1696. return entries;
  1697. },symlink:function(parent, newname, oldpath) {
  1698. var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
  1699. node.link = oldpath;
  1700. return node;
  1701. },readlink:function(node) {
  1702. if (!FS.isLink(node.mode)) {
  1703. throw new FS.ErrnoError(28);
  1704. }
  1705. return node.link;
  1706. }},stream_ops:{read:function(stream, buffer, offset, length, position) {
  1707. var contents = stream.node.contents;
  1708. if (position >= stream.node.usedBytes) return 0;
  1709. var size = Math.min(stream.node.usedBytes - position, length);
  1710. assert(size >= 0);
  1711. if (size > 8 && contents.subarray) { // non-trivial, and typed array
  1712. buffer.set(contents.subarray(position, position + size), offset);
  1713. } else {
  1714. for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
  1715. }
  1716. return size;
  1717. },write:function(stream, buffer, offset, length, position, canOwn) {
  1718. // The data buffer should be a typed array view
  1719. assert(!(buffer instanceof ArrayBuffer));
  1720. // If the buffer is located in main memory (HEAP), and if
  1721. // memory can grow, we can't hold on to references of the
  1722. // memory buffer, as they may get invalidated. That means we
  1723. // need to do copy its contents.
  1724. if (buffer.buffer === HEAP8.buffer) {
  1725. canOwn = false;
  1726. }
  1727. if (!length) return 0;
  1728. var node = stream.node;
  1729. node.timestamp = Date.now();
  1730. if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
  1731. if (canOwn) {
  1732. assert(position === 0, 'canOwn must imply no weird position inside the file');
  1733. node.contents = buffer.subarray(offset, offset + length);
  1734. node.usedBytes = length;
  1735. return length;
  1736. } else if (node.usedBytes === 0 && position === 0) { // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
  1737. node.contents = buffer.slice(offset, offset + length);
  1738. node.usedBytes = length;
  1739. return length;
  1740. } else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
  1741. node.contents.set(buffer.subarray(offset, offset + length), position);
  1742. return length;
  1743. }
  1744. }
  1745. // Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
  1746. MEMFS.expandFileStorage(node, position+length);
  1747. if (node.contents.subarray && buffer.subarray) {
  1748. // Use typed array write which is available.
  1749. node.contents.set(buffer.subarray(offset, offset + length), position);
  1750. } else {
  1751. for (var i = 0; i < length; i++) {
  1752. node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
  1753. }
  1754. }
  1755. node.usedBytes = Math.max(node.usedBytes, position + length);
  1756. return length;
  1757. },llseek:function(stream, offset, whence) {
  1758. var position = offset;
  1759. if (whence === 1) {
  1760. position += stream.position;
  1761. } else if (whence === 2) {
  1762. if (FS.isFile(stream.node.mode)) {
  1763. position += stream.node.usedBytes;
  1764. }
  1765. }
  1766. if (position < 0) {
  1767. throw new FS.ErrnoError(28);
  1768. }
  1769. return position;
  1770. },allocate:function(stream, offset, length) {
  1771. MEMFS.expandFileStorage(stream.node, offset + length);
  1772. stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
  1773. },mmap:function(stream, length, position, prot, flags) {
  1774. if (!FS.isFile(stream.node.mode)) {
  1775. throw new FS.ErrnoError(43);
  1776. }
  1777. var ptr;
  1778. var allocated;
  1779. var contents = stream.node.contents;
  1780. // Only make a new copy when MAP_PRIVATE is specified.
  1781. if (!(flags & 2) && contents.buffer === HEAP8.buffer) {
  1782. // We can't emulate MAP_SHARED when the file is not backed by the
  1783. // buffer we're mapping to (e.g. the HEAP buffer).
  1784. allocated = false;
  1785. ptr = contents.byteOffset;
  1786. } else {
  1787. // Try to avoid unnecessary slices.
  1788. if (position > 0 || position + length < contents.length) {
  1789. if (contents.subarray) {
  1790. contents = contents.subarray(position, position + length);
  1791. } else {
  1792. contents = Array.prototype.slice.call(contents, position, position + length);
  1793. }
  1794. }
  1795. allocated = true;
  1796. ptr = mmapAlloc(length);
  1797. if (!ptr) {
  1798. throw new FS.ErrnoError(48);
  1799. }
  1800. HEAP8.set(contents, ptr);
  1801. }
  1802. return { ptr: ptr, allocated: allocated };
  1803. },msync:function(stream, buffer, offset, length, mmapFlags) {
  1804. MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
  1805. // should we check if bytesWritten and length are the same?
  1806. return 0;
  1807. }}};
  1808. /** @param {boolean=} noRunDep */
  1809. function asyncLoad(url, onload, onerror, noRunDep) {
  1810. var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : '';
  1811. readAsync(url, (arrayBuffer) => {
  1812. assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
  1813. onload(new Uint8Array(arrayBuffer));
  1814. if (dep) removeRunDependency(dep);
  1815. }, (event) => {
  1816. if (onerror) {
  1817. onerror();
  1818. } else {
  1819. throw 'Loading data file "' + url + '" failed.';
  1820. }
  1821. });
  1822. if (dep) addRunDependency(dep);
  1823. }
  1824. var ERRNO_MESSAGES = {0:"Success",1:"Arg list too long",2:"Permission denied",3:"Address already in use",4:"Address not available",5:"Address family not supported by protocol family",6:"No more processes",7:"Socket already connected",8:"Bad file number",9:"Trying to read unreadable message",10:"Mount device busy",11:"Operation canceled",12:"No children",13:"Connection aborted",14:"Connection refused",15:"Connection reset by peer",16:"File locking deadlock error",17:"Destination address required",18:"Math arg out of domain of func",19:"Quota exceeded",20:"File exists",21:"Bad address",22:"File too large",23:"Host is unreachable",24:"Identifier removed",25:"Illegal byte sequence",26:"Connection already in progress",27:"Interrupted system call",28:"Invalid argument",29:"I/O error",30:"Socket is already connected",31:"Is a directory",32:"Too many symbolic links",33:"Too many open files",34:"Too many links",35:"Message too long",36:"Multihop attempted",37:"File or path name too long",38:"Network interface is not configured",39:"Connection reset by network",40:"Network is unreachable",41:"Too many open files in system",42:"No buffer space available",43:"No such device",44:"No such file or directory",45:"Exec format error",46:"No record locks available",47:"The link has been severed",48:"Not enough core",49:"No message of desired type",50:"Protocol not available",51:"No space left on device",52:"Function not implemented",53:"Socket is not connected",54:"Not a directory",55:"Directory not empty",56:"State not recoverable",57:"Socket operation on non-socket",59:"Not a typewriter",60:"No such device or address",61:"Value too large for defined data type",62:"Previous owner died",63:"Not super-user",64:"Broken pipe",65:"Protocol error",66:"Unknown protocol",67:"Protocol wrong type for socket",68:"Math result not representable",69:"Read only file system",70:"Illegal seek",71:"No such process",72:"Stale file handle",73:"Connection timed out",74:"Text file busy",75:"Cross-device link",100:"Device not a stream",101:"Bad font file fmt",102:"Invalid slot",103:"Invalid request code",104:"No anode",105:"Block device required",106:"Channel number out of range",107:"Level 3 halted",108:"Level 3 reset",109:"Link number out of range",110:"Protocol driver not attached",111:"No CSI structure available",112:"Level 2 halted",113:"Invalid exchange",114:"Invalid request descriptor",115:"Exchange full",116:"No data (for no delay io)",117:"Timer expired",118:"Out of streams resources",119:"Machine is not on the network",120:"Package not installed",121:"The object is remote",122:"Advertise error",123:"Srmount error",124:"Communication error on send",125:"Cross mount point (not really error)",126:"Given log. name not unique",127:"f.d. invalid for this operation",128:"Remote address changed",129:"Can access a needed shared lib",130:"Accessing a corrupted shared lib",131:".lib section in a.out corrupted",132:"Attempting to link in too many libs",133:"Attempting to exec a shared library",135:"Streams pipe error",136:"Too many users",137:"Socket type not supported",138:"Not supported",139:"Protocol family not supported",140:"Can't send after socket shutdown",141:"Too many references",142:"Host is down",148:"No medium (in tape drive)",156:"Level 2 not synchronized"};
  1825. var ERRNO_CODES = {};
  1826. function withStackSave(f) {
  1827. var stack = stackSave();
  1828. var ret = f();
  1829. stackRestore(stack);
  1830. return ret;
  1831. }
  1832. function demangle(func) {
  1833. warnOnce('warning: build with -sDEMANGLE_SUPPORT to link in libcxxabi demangling');
  1834. return func;
  1835. }
  1836. function demangleAll(text) {
  1837. var regex =
  1838. /\b_Z[\w\d_]+/g;
  1839. return text.replace(regex,
  1840. function(x) {
  1841. var y = demangle(x);
  1842. return x === y ? x : (y + ' [' + x + ']');
  1843. });
  1844. }
  1845. var FS = {root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path, opts = {}) => {
  1846. path = PATH_FS.resolve(path);
  1847. if (!path) return { path: '', node: null };
  1848. var defaults = {
  1849. follow_mount: true,
  1850. recurse_count: 0
  1851. };
  1852. opts = Object.assign(defaults, opts)
  1853. if (opts.recurse_count > 8) { // max recursive lookup of 8
  1854. throw new FS.ErrnoError(32);
  1855. }
  1856. // split the absolute path
  1857. var parts = path.split('/').filter((p) => !!p);
  1858. // start at the root
  1859. var current = FS.root;
  1860. var current_path = '/';
  1861. for (var i = 0; i < parts.length; i++) {
  1862. var islast = (i === parts.length-1);
  1863. if (islast && opts.parent) {
  1864. // stop resolving
  1865. break;
  1866. }
  1867. current = FS.lookupNode(current, parts[i]);
  1868. current_path = PATH.join2(current_path, parts[i]);
  1869. // jump to the mount's root node if this is a mountpoint
  1870. if (FS.isMountpoint(current)) {
  1871. if (!islast || (islast && opts.follow_mount)) {
  1872. current = current.mounted.root;
  1873. }
  1874. }
  1875. // by default, lookupPath will not follow a symlink if it is the final path component.
  1876. // setting opts.follow = true will override this behavior.
  1877. if (!islast || opts.follow) {
  1878. var count = 0;
  1879. while (FS.isLink(current.mode)) {
  1880. var link = FS.readlink(current_path);
  1881. current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
  1882. var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 });
  1883. current = lookup.node;
  1884. if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
  1885. throw new FS.ErrnoError(32);
  1886. }
  1887. }
  1888. }
  1889. }
  1890. return { path: current_path, node: current };
  1891. },getPath:(node) => {
  1892. var path;
  1893. while (true) {
  1894. if (FS.isRoot(node)) {
  1895. var mount = node.mount.mountpoint;
  1896. if (!path) return mount;
  1897. return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
  1898. }
  1899. path = path ? node.name + '/' + path : node.name;
  1900. node = node.parent;
  1901. }
  1902. },hashName:(parentid, name) => {
  1903. var hash = 0;
  1904. for (var i = 0; i < name.length; i++) {
  1905. hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
  1906. }
  1907. return ((parentid + hash) >>> 0) % FS.nameTable.length;
  1908. },hashAddNode:(node) => {
  1909. var hash = FS.hashName(node.parent.id, node.name);
  1910. node.name_next = FS.nameTable[hash];
  1911. FS.nameTable[hash] = node;
  1912. },hashRemoveNode:(node) => {
  1913. var hash = FS.hashName(node.parent.id, node.name);
  1914. if (FS.nameTable[hash] === node) {
  1915. FS.nameTable[hash] = node.name_next;
  1916. } else {
  1917. var current = FS.nameTable[hash];
  1918. while (current) {
  1919. if (current.name_next === node) {
  1920. current.name_next = node.name_next;
  1921. break;
  1922. }
  1923. current = current.name_next;
  1924. }
  1925. }
  1926. },lookupNode:(parent, name) => {
  1927. var errCode = FS.mayLookup(parent);
  1928. if (errCode) {
  1929. throw new FS.ErrnoError(errCode, parent);
  1930. }
  1931. var hash = FS.hashName(parent.id, name);
  1932. for (var node = FS.nameTable[hash]; node; node = node.name_next) {
  1933. var nodeName = node.name;
  1934. if (node.parent.id === parent.id && nodeName === name) {
  1935. return node;
  1936. }
  1937. }
  1938. // if we failed to find it in the cache, call into the VFS
  1939. return FS.lookup(parent, name);
  1940. },createNode:(parent, name, mode, rdev) => {
  1941. assert(typeof parent == 'object')
  1942. var node = new FS.FSNode(parent, name, mode, rdev);
  1943. FS.hashAddNode(node);
  1944. return node;
  1945. },destroyNode:(node) => {
  1946. FS.hashRemoveNode(node);
  1947. },isRoot:(node) => {
  1948. return node === node.parent;
  1949. },isMountpoint:(node) => {
  1950. return !!node.mounted;
  1951. },isFile:(mode) => {
  1952. return (mode & 61440) === 32768;
  1953. },isDir:(mode) => {
  1954. return (mode & 61440) === 16384;
  1955. },isLink:(mode) => {
  1956. return (mode & 61440) === 40960;
  1957. },isChrdev:(mode) => {
  1958. return (mode & 61440) === 8192;
  1959. },isBlkdev:(mode) => {
  1960. return (mode & 61440) === 24576;
  1961. },isFIFO:(mode) => {
  1962. return (mode & 61440) === 4096;
  1963. },isSocket:(mode) => {
  1964. return (mode & 49152) === 49152;
  1965. },flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:(str) => {
  1966. var flags = FS.flagModes[str];
  1967. if (typeof flags == 'undefined') {
  1968. throw new Error('Unknown file open mode: ' + str);
  1969. }
  1970. return flags;
  1971. },flagsToPermissionString:(flag) => {
  1972. var perms = ['r', 'w', 'rw'][flag & 3];
  1973. if ((flag & 512)) {
  1974. perms += 'w';
  1975. }
  1976. return perms;
  1977. },nodePermissions:(node, perms) => {
  1978. if (FS.ignorePermissions) {
  1979. return 0;
  1980. }
  1981. // return 0 if any user, group or owner bits are set.
  1982. if (perms.includes('r') && !(node.mode & 292)) {
  1983. return 2;
  1984. } else if (perms.includes('w') && !(node.mode & 146)) {
  1985. return 2;
  1986. } else if (perms.includes('x') && !(node.mode & 73)) {
  1987. return 2;
  1988. }
  1989. return 0;
  1990. },mayLookup:(dir) => {
  1991. var errCode = FS.nodePermissions(dir, 'x');
  1992. if (errCode) return errCode;
  1993. if (!dir.node_ops.lookup) return 2;
  1994. return 0;
  1995. },mayCreate:(dir, name) => {
  1996. try {
  1997. var node = FS.lookupNode(dir, name);
  1998. return 20;
  1999. } catch (e) {
  2000. }
  2001. return FS.nodePermissions(dir, 'wx');
  2002. },mayDelete:(dir, name, isdir) => {
  2003. var node;
  2004. try {
  2005. node = FS.lookupNode(dir, name);
  2006. } catch (e) {
  2007. return e.errno;
  2008. }
  2009. var errCode = FS.nodePermissions(dir, 'wx');
  2010. if (errCode) {
  2011. return errCode;
  2012. }
  2013. if (isdir) {
  2014. if (!FS.isDir(node.mode)) {
  2015. return 54;
  2016. }
  2017. if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
  2018. return 10;
  2019. }
  2020. } else {
  2021. if (FS.isDir(node.mode)) {
  2022. return 31;
  2023. }
  2024. }
  2025. return 0;
  2026. },mayOpen:(node, flags) => {
  2027. if (!node) {
  2028. return 44;
  2029. }
  2030. if (FS.isLink(node.mode)) {
  2031. return 32;
  2032. } else if (FS.isDir(node.mode)) {
  2033. if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
  2034. (flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
  2035. return 31;
  2036. }
  2037. }
  2038. return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
  2039. },MAX_OPEN_FDS:4096,nextfd:(fd_start = 0, fd_end = FS.MAX_OPEN_FDS) => {
  2040. for (var fd = fd_start; fd <= fd_end; fd++) {
  2041. if (!FS.streams[fd]) {
  2042. return fd;
  2043. }
  2044. }
  2045. throw new FS.ErrnoError(33);
  2046. },getStream:(fd) => FS.streams[fd],createStream:(stream, fd_start, fd_end) => {
  2047. if (!FS.FSStream) {
  2048. FS.FSStream = /** @constructor */ function() {
  2049. this.shared = { };
  2050. };
  2051. FS.FSStream.prototype = {};
  2052. Object.defineProperties(FS.FSStream.prototype, {
  2053. object: {
  2054. /** @this {FS.FSStream} */
  2055. get: function() { return this.node; },
  2056. /** @this {FS.FSStream} */
  2057. set: function(val) { this.node = val; }
  2058. },
  2059. isRead: {
  2060. /** @this {FS.FSStream} */
  2061. get: function() { return (this.flags & 2097155) !== 1; }
  2062. },
  2063. isWrite: {
  2064. /** @this {FS.FSStream} */
  2065. get: function() { return (this.flags & 2097155) !== 0; }
  2066. },
  2067. isAppend: {
  2068. /** @this {FS.FSStream} */
  2069. get: function() { return (this.flags & 1024); }
  2070. },
  2071. flags: {
  2072. /** @this {FS.FSStream} */
  2073. get: function() { return this.shared.flags; },
  2074. /** @this {FS.FSStream} */
  2075. set: function(val) { this.shared.flags = val; },
  2076. },
  2077. position : {
  2078. /** @this {FS.FSStream} */
  2079. get: function() { return this.shared.position; },
  2080. /** @this {FS.FSStream} */
  2081. set: function(val) { this.shared.position = val; },
  2082. },
  2083. });
  2084. }
  2085. // clone it, so we can return an instance of FSStream
  2086. stream = Object.assign(new FS.FSStream(), stream);
  2087. var fd = FS.nextfd(fd_start, fd_end);
  2088. stream.fd = fd;
  2089. FS.streams[fd] = stream;
  2090. return stream;
  2091. },closeStream:(fd) => {
  2092. FS.streams[fd] = null;
  2093. },chrdev_stream_ops:{open:(stream) => {
  2094. var device = FS.getDevice(stream.node.rdev);
  2095. // override node's stream ops with the device's
  2096. stream.stream_ops = device.stream_ops;
  2097. // forward the open call
  2098. if (stream.stream_ops.open) {
  2099. stream.stream_ops.open(stream);
  2100. }
  2101. },llseek:() => {
  2102. throw new FS.ErrnoError(70);
  2103. }},major:(dev) => ((dev) >> 8),minor:(dev) => ((dev) & 0xff),makedev:(ma, mi) => ((ma) << 8 | (mi)),registerDevice:(dev, ops) => {
  2104. FS.devices[dev] = { stream_ops: ops };
  2105. },getDevice:(dev) => FS.devices[dev],getMounts:(mount) => {
  2106. var mounts = [];
  2107. var check = [mount];
  2108. while (check.length) {
  2109. var m = check.pop();
  2110. mounts.push(m);
  2111. check.push.apply(check, m.mounts);
  2112. }
  2113. return mounts;
  2114. },syncfs:(populate, callback) => {
  2115. if (typeof populate == 'function') {
  2116. callback = populate;
  2117. populate = false;
  2118. }
  2119. FS.syncFSRequests++;
  2120. if (FS.syncFSRequests > 1) {
  2121. err('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
  2122. }
  2123. var mounts = FS.getMounts(FS.root.mount);
  2124. var completed = 0;
  2125. function doCallback(errCode) {
  2126. assert(FS.syncFSRequests > 0);
  2127. FS.syncFSRequests--;
  2128. return callback(errCode);
  2129. }
  2130. function done(errCode) {
  2131. if (errCode) {
  2132. if (!done.errored) {
  2133. done.errored = true;
  2134. return doCallback(errCode);
  2135. }
  2136. return;
  2137. }
  2138. if (++completed >= mounts.length) {
  2139. doCallback(null);
  2140. }
  2141. };
  2142. // sync all mounts
  2143. mounts.forEach((mount) => {
  2144. if (!mount.type.syncfs) {
  2145. return done(null);
  2146. }
  2147. mount.type.syncfs(mount, populate, done);
  2148. });
  2149. },mount:(type, opts, mountpoint) => {
  2150. if (typeof type == 'string') {
  2151. // The filesystem was not included, and instead we have an error
  2152. // message stored in the variable.
  2153. throw type;
  2154. }
  2155. var root = mountpoint === '/';
  2156. var pseudo = !mountpoint;
  2157. var node;
  2158. if (root && FS.root) {
  2159. throw new FS.ErrnoError(10);
  2160. } else if (!root && !pseudo) {
  2161. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2162. mountpoint = lookup.path; // use the absolute path
  2163. node = lookup.node;
  2164. if (FS.isMountpoint(node)) {
  2165. throw new FS.ErrnoError(10);
  2166. }
  2167. if (!FS.isDir(node.mode)) {
  2168. throw new FS.ErrnoError(54);
  2169. }
  2170. }
  2171. var mount = {
  2172. type: type,
  2173. opts: opts,
  2174. mountpoint: mountpoint,
  2175. mounts: []
  2176. };
  2177. // create a root node for the fs
  2178. var mountRoot = type.mount(mount);
  2179. mountRoot.mount = mount;
  2180. mount.root = mountRoot;
  2181. if (root) {
  2182. FS.root = mountRoot;
  2183. } else if (node) {
  2184. // set as a mountpoint
  2185. node.mounted = mount;
  2186. // add the new mount to the current mount's children
  2187. if (node.mount) {
  2188. node.mount.mounts.push(mount);
  2189. }
  2190. }
  2191. return mountRoot;
  2192. },unmount:(mountpoint) => {
  2193. var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
  2194. if (!FS.isMountpoint(lookup.node)) {
  2195. throw new FS.ErrnoError(28);
  2196. }
  2197. // destroy the nodes for this mount, and all its child mounts
  2198. var node = lookup.node;
  2199. var mount = node.mounted;
  2200. var mounts = FS.getMounts(mount);
  2201. Object.keys(FS.nameTable).forEach((hash) => {
  2202. var current = FS.nameTable[hash];
  2203. while (current) {
  2204. var next = current.name_next;
  2205. if (mounts.includes(current.mount)) {
  2206. FS.destroyNode(current);
  2207. }
  2208. current = next;
  2209. }
  2210. });
  2211. // no longer a mountpoint
  2212. node.mounted = null;
  2213. // remove this mount from the child mounts
  2214. var idx = node.mount.mounts.indexOf(mount);
  2215. assert(idx !== -1);
  2216. node.mount.mounts.splice(idx, 1);
  2217. },lookup:(parent, name) => {
  2218. return parent.node_ops.lookup(parent, name);
  2219. },mknod:(path, mode, dev) => {
  2220. var lookup = FS.lookupPath(path, { parent: true });
  2221. var parent = lookup.node;
  2222. var name = PATH.basename(path);
  2223. if (!name || name === '.' || name === '..') {
  2224. throw new FS.ErrnoError(28);
  2225. }
  2226. var errCode = FS.mayCreate(parent, name);
  2227. if (errCode) {
  2228. throw new FS.ErrnoError(errCode);
  2229. }
  2230. if (!parent.node_ops.mknod) {
  2231. throw new FS.ErrnoError(63);
  2232. }
  2233. return parent.node_ops.mknod(parent, name, mode, dev);
  2234. },create:(path, mode) => {
  2235. mode = mode !== undefined ? mode : 438 /* 0666 */;
  2236. mode &= 4095;
  2237. mode |= 32768;
  2238. return FS.mknod(path, mode, 0);
  2239. },mkdir:(path, mode) => {
  2240. mode = mode !== undefined ? mode : 511 /* 0777 */;
  2241. mode &= 511 | 512;
  2242. mode |= 16384;
  2243. return FS.mknod(path, mode, 0);
  2244. },mkdirTree:(path, mode) => {
  2245. var dirs = path.split('/');
  2246. var d = '';
  2247. for (var i = 0; i < dirs.length; ++i) {
  2248. if (!dirs[i]) continue;
  2249. d += '/' + dirs[i];
  2250. try {
  2251. FS.mkdir(d, mode);
  2252. } catch(e) {
  2253. if (e.errno != 20) throw e;
  2254. }
  2255. }
  2256. },mkdev:(path, mode, dev) => {
  2257. if (typeof dev == 'undefined') {
  2258. dev = mode;
  2259. mode = 438 /* 0666 */;
  2260. }
  2261. mode |= 8192;
  2262. return FS.mknod(path, mode, dev);
  2263. },symlink:(oldpath, newpath) => {
  2264. if (!PATH_FS.resolve(oldpath)) {
  2265. throw new FS.ErrnoError(44);
  2266. }
  2267. var lookup = FS.lookupPath(newpath, { parent: true });
  2268. var parent = lookup.node;
  2269. if (!parent) {
  2270. throw new FS.ErrnoError(44);
  2271. }
  2272. var newname = PATH.basename(newpath);
  2273. var errCode = FS.mayCreate(parent, newname);
  2274. if (errCode) {
  2275. throw new FS.ErrnoError(errCode);
  2276. }
  2277. if (!parent.node_ops.symlink) {
  2278. throw new FS.ErrnoError(63);
  2279. }
  2280. return parent.node_ops.symlink(parent, newname, oldpath);
  2281. },rename:(old_path, new_path) => {
  2282. var old_dirname = PATH.dirname(old_path);
  2283. var new_dirname = PATH.dirname(new_path);
  2284. var old_name = PATH.basename(old_path);
  2285. var new_name = PATH.basename(new_path);
  2286. // parents must exist
  2287. var lookup, old_dir, new_dir;
  2288. // let the errors from non existant directories percolate up
  2289. lookup = FS.lookupPath(old_path, { parent: true });
  2290. old_dir = lookup.node;
  2291. lookup = FS.lookupPath(new_path, { parent: true });
  2292. new_dir = lookup.node;
  2293. if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
  2294. // need to be part of the same mount
  2295. if (old_dir.mount !== new_dir.mount) {
  2296. throw new FS.ErrnoError(75);
  2297. }
  2298. // source must exist
  2299. var old_node = FS.lookupNode(old_dir, old_name);
  2300. // old path should not be an ancestor of the new path
  2301. var relative = PATH_FS.relative(old_path, new_dirname);
  2302. if (relative.charAt(0) !== '.') {
  2303. throw new FS.ErrnoError(28);
  2304. }
  2305. // new path should not be an ancestor of the old path
  2306. relative = PATH_FS.relative(new_path, old_dirname);
  2307. if (relative.charAt(0) !== '.') {
  2308. throw new FS.ErrnoError(55);
  2309. }
  2310. // see if the new path already exists
  2311. var new_node;
  2312. try {
  2313. new_node = FS.lookupNode(new_dir, new_name);
  2314. } catch (e) {
  2315. // not fatal
  2316. }
  2317. // early out if nothing needs to change
  2318. if (old_node === new_node) {
  2319. return;
  2320. }
  2321. // we'll need to delete the old entry
  2322. var isdir = FS.isDir(old_node.mode);
  2323. var errCode = FS.mayDelete(old_dir, old_name, isdir);
  2324. if (errCode) {
  2325. throw new FS.ErrnoError(errCode);
  2326. }
  2327. // need delete permissions if we'll be overwriting.
  2328. // need create permissions if new doesn't already exist.
  2329. errCode = new_node ?
  2330. FS.mayDelete(new_dir, new_name, isdir) :
  2331. FS.mayCreate(new_dir, new_name);
  2332. if (errCode) {
  2333. throw new FS.ErrnoError(errCode);
  2334. }
  2335. if (!old_dir.node_ops.rename) {
  2336. throw new FS.ErrnoError(63);
  2337. }
  2338. if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
  2339. throw new FS.ErrnoError(10);
  2340. }
  2341. // if we are going to change the parent, check write permissions
  2342. if (new_dir !== old_dir) {
  2343. errCode = FS.nodePermissions(old_dir, 'w');
  2344. if (errCode) {
  2345. throw new FS.ErrnoError(errCode);
  2346. }
  2347. }
  2348. // remove the node from the lookup hash
  2349. FS.hashRemoveNode(old_node);
  2350. // do the underlying fs rename
  2351. try {
  2352. old_dir.node_ops.rename(old_node, new_dir, new_name);
  2353. } catch (e) {
  2354. throw e;
  2355. } finally {
  2356. // add the node back to the hash (in case node_ops.rename
  2357. // changed its name)
  2358. FS.hashAddNode(old_node);
  2359. }
  2360. },rmdir:(path) => {
  2361. var lookup = FS.lookupPath(path, { parent: true });
  2362. var parent = lookup.node;
  2363. var name = PATH.basename(path);
  2364. var node = FS.lookupNode(parent, name);
  2365. var errCode = FS.mayDelete(parent, name, true);
  2366. if (errCode) {
  2367. throw new FS.ErrnoError(errCode);
  2368. }
  2369. if (!parent.node_ops.rmdir) {
  2370. throw new FS.ErrnoError(63);
  2371. }
  2372. if (FS.isMountpoint(node)) {
  2373. throw new FS.ErrnoError(10);
  2374. }
  2375. parent.node_ops.rmdir(parent, name);
  2376. FS.destroyNode(node);
  2377. },readdir:(path) => {
  2378. var lookup = FS.lookupPath(path, { follow: true });
  2379. var node = lookup.node;
  2380. if (!node.node_ops.readdir) {
  2381. throw new FS.ErrnoError(54);
  2382. }
  2383. return node.node_ops.readdir(node);
  2384. },unlink:(path) => {
  2385. var lookup = FS.lookupPath(path, { parent: true });
  2386. var parent = lookup.node;
  2387. if (!parent) {
  2388. throw new FS.ErrnoError(44);
  2389. }
  2390. var name = PATH.basename(path);
  2391. var node = FS.lookupNode(parent, name);
  2392. var errCode = FS.mayDelete(parent, name, false);
  2393. if (errCode) {
  2394. // According to POSIX, we should map EISDIR to EPERM, but
  2395. // we instead do what Linux does (and we must, as we use
  2396. // the musl linux libc).
  2397. throw new FS.ErrnoError(errCode);
  2398. }
  2399. if (!parent.node_ops.unlink) {
  2400. throw new FS.ErrnoError(63);
  2401. }
  2402. if (FS.isMountpoint(node)) {
  2403. throw new FS.ErrnoError(10);
  2404. }
  2405. parent.node_ops.unlink(parent, name);
  2406. FS.destroyNode(node);
  2407. },readlink:(path) => {
  2408. var lookup = FS.lookupPath(path);
  2409. var link = lookup.node;
  2410. if (!link) {
  2411. throw new FS.ErrnoError(44);
  2412. }
  2413. if (!link.node_ops.readlink) {
  2414. throw new FS.ErrnoError(28);
  2415. }
  2416. return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
  2417. },stat:(path, dontFollow) => {
  2418. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2419. var node = lookup.node;
  2420. if (!node) {
  2421. throw new FS.ErrnoError(44);
  2422. }
  2423. if (!node.node_ops.getattr) {
  2424. throw new FS.ErrnoError(63);
  2425. }
  2426. return node.node_ops.getattr(node);
  2427. },lstat:(path) => {
  2428. return FS.stat(path, true);
  2429. },chmod:(path, mode, dontFollow) => {
  2430. var node;
  2431. if (typeof path == 'string') {
  2432. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2433. node = lookup.node;
  2434. } else {
  2435. node = path;
  2436. }
  2437. if (!node.node_ops.setattr) {
  2438. throw new FS.ErrnoError(63);
  2439. }
  2440. node.node_ops.setattr(node, {
  2441. mode: (mode & 4095) | (node.mode & ~4095),
  2442. timestamp: Date.now()
  2443. });
  2444. },lchmod:(path, mode) => {
  2445. FS.chmod(path, mode, true);
  2446. },fchmod:(fd, mode) => {
  2447. var stream = FS.getStream(fd);
  2448. if (!stream) {
  2449. throw new FS.ErrnoError(8);
  2450. }
  2451. FS.chmod(stream.node, mode);
  2452. },chown:(path, uid, gid, dontFollow) => {
  2453. var node;
  2454. if (typeof path == 'string') {
  2455. var lookup = FS.lookupPath(path, { follow: !dontFollow });
  2456. node = lookup.node;
  2457. } else {
  2458. node = path;
  2459. }
  2460. if (!node.node_ops.setattr) {
  2461. throw new FS.ErrnoError(63);
  2462. }
  2463. node.node_ops.setattr(node, {
  2464. timestamp: Date.now()
  2465. // we ignore the uid / gid for now
  2466. });
  2467. },lchown:(path, uid, gid) => {
  2468. FS.chown(path, uid, gid, true);
  2469. },fchown:(fd, uid, gid) => {
  2470. var stream = FS.getStream(fd);
  2471. if (!stream) {
  2472. throw new FS.ErrnoError(8);
  2473. }
  2474. FS.chown(stream.node, uid, gid);
  2475. },truncate:(path, len) => {
  2476. if (len < 0) {
  2477. throw new FS.ErrnoError(28);
  2478. }
  2479. var node;
  2480. if (typeof path == 'string') {
  2481. var lookup = FS.lookupPath(path, { follow: true });
  2482. node = lookup.node;
  2483. } else {
  2484. node = path;
  2485. }
  2486. if (!node.node_ops.setattr) {
  2487. throw new FS.ErrnoError(63);
  2488. }
  2489. if (FS.isDir(node.mode)) {
  2490. throw new FS.ErrnoError(31);
  2491. }
  2492. if (!FS.isFile(node.mode)) {
  2493. throw new FS.ErrnoError(28);
  2494. }
  2495. var errCode = FS.nodePermissions(node, 'w');
  2496. if (errCode) {
  2497. throw new FS.ErrnoError(errCode);
  2498. }
  2499. node.node_ops.setattr(node, {
  2500. size: len,
  2501. timestamp: Date.now()
  2502. });
  2503. },ftruncate:(fd, len) => {
  2504. var stream = FS.getStream(fd);
  2505. if (!stream) {
  2506. throw new FS.ErrnoError(8);
  2507. }
  2508. if ((stream.flags & 2097155) === 0) {
  2509. throw new FS.ErrnoError(28);
  2510. }
  2511. FS.truncate(stream.node, len);
  2512. },utime:(path, atime, mtime) => {
  2513. var lookup = FS.lookupPath(path, { follow: true });
  2514. var node = lookup.node;
  2515. node.node_ops.setattr(node, {
  2516. timestamp: Math.max(atime, mtime)
  2517. });
  2518. },open:(path, flags, mode) => {
  2519. if (path === "") {
  2520. throw new FS.ErrnoError(44);
  2521. }
  2522. flags = typeof flags == 'string' ? FS.modeStringToFlags(flags) : flags;
  2523. mode = typeof mode == 'undefined' ? 438 /* 0666 */ : mode;
  2524. if ((flags & 64)) {
  2525. mode = (mode & 4095) | 32768;
  2526. } else {
  2527. mode = 0;
  2528. }
  2529. var node;
  2530. if (typeof path == 'object') {
  2531. node = path;
  2532. } else {
  2533. path = PATH.normalize(path);
  2534. try {
  2535. var lookup = FS.lookupPath(path, {
  2536. follow: !(flags & 131072)
  2537. });
  2538. node = lookup.node;
  2539. } catch (e) {
  2540. // ignore
  2541. }
  2542. }
  2543. // perhaps we need to create the node
  2544. var created = false;
  2545. if ((flags & 64)) {
  2546. if (node) {
  2547. // if O_CREAT and O_EXCL are set, error out if the node already exists
  2548. if ((flags & 128)) {
  2549. throw new FS.ErrnoError(20);
  2550. }
  2551. } else {
  2552. // node doesn't exist, try to create it
  2553. node = FS.mknod(path, mode, 0);
  2554. created = true;
  2555. }
  2556. }
  2557. if (!node) {
  2558. throw new FS.ErrnoError(44);
  2559. }
  2560. // can't truncate a device
  2561. if (FS.isChrdev(node.mode)) {
  2562. flags &= ~512;
  2563. }
  2564. // if asked only for a directory, then this must be one
  2565. if ((flags & 65536) && !FS.isDir(node.mode)) {
  2566. throw new FS.ErrnoError(54);
  2567. }
  2568. // check permissions, if this is not a file we just created now (it is ok to
  2569. // create and write to a file with read-only permissions; it is read-only
  2570. // for later use)
  2571. if (!created) {
  2572. var errCode = FS.mayOpen(node, flags);
  2573. if (errCode) {
  2574. throw new FS.ErrnoError(errCode);
  2575. }
  2576. }
  2577. // do truncation if necessary
  2578. if ((flags & 512) && !created) {
  2579. FS.truncate(node, 0);
  2580. }
  2581. // we've already handled these, don't pass down to the underlying vfs
  2582. flags &= ~(128 | 512 | 131072);
  2583. // register the stream with the filesystem
  2584. var stream = FS.createStream({
  2585. node: node,
  2586. path: FS.getPath(node), // we want the absolute path to the node
  2587. flags: flags,
  2588. seekable: true,
  2589. position: 0,
  2590. stream_ops: node.stream_ops,
  2591. // used by the file family libc calls (fopen, fwrite, ferror, etc.)
  2592. ungotten: [],
  2593. error: false
  2594. });
  2595. // call the new stream's open function
  2596. if (stream.stream_ops.open) {
  2597. stream.stream_ops.open(stream);
  2598. }
  2599. if (Module['logReadFiles'] && !(flags & 1)) {
  2600. if (!FS.readFiles) FS.readFiles = {};
  2601. if (!(path in FS.readFiles)) {
  2602. FS.readFiles[path] = 1;
  2603. }
  2604. }
  2605. return stream;
  2606. },close:(stream) => {
  2607. if (FS.isClosed(stream)) {
  2608. throw new FS.ErrnoError(8);
  2609. }
  2610. if (stream.getdents) stream.getdents = null; // free readdir state
  2611. try {
  2612. if (stream.stream_ops.close) {
  2613. stream.stream_ops.close(stream);
  2614. }
  2615. } catch (e) {
  2616. throw e;
  2617. } finally {
  2618. FS.closeStream(stream.fd);
  2619. }
  2620. stream.fd = null;
  2621. },isClosed:(stream) => {
  2622. return stream.fd === null;
  2623. },llseek:(stream, offset, whence) => {
  2624. if (FS.isClosed(stream)) {
  2625. throw new FS.ErrnoError(8);
  2626. }
  2627. if (!stream.seekable || !stream.stream_ops.llseek) {
  2628. throw new FS.ErrnoError(70);
  2629. }
  2630. if (whence != 0 && whence != 1 && whence != 2) {
  2631. throw new FS.ErrnoError(28);
  2632. }
  2633. stream.position = stream.stream_ops.llseek(stream, offset, whence);
  2634. stream.ungotten = [];
  2635. return stream.position;
  2636. },read:(stream, buffer, offset, length, position) => {
  2637. if (length < 0 || position < 0) {
  2638. throw new FS.ErrnoError(28);
  2639. }
  2640. if (FS.isClosed(stream)) {
  2641. throw new FS.ErrnoError(8);
  2642. }
  2643. if ((stream.flags & 2097155) === 1) {
  2644. throw new FS.ErrnoError(8);
  2645. }
  2646. if (FS.isDir(stream.node.mode)) {
  2647. throw new FS.ErrnoError(31);
  2648. }
  2649. if (!stream.stream_ops.read) {
  2650. throw new FS.ErrnoError(28);
  2651. }
  2652. var seeking = typeof position != 'undefined';
  2653. if (!seeking) {
  2654. position = stream.position;
  2655. } else if (!stream.seekable) {
  2656. throw new FS.ErrnoError(70);
  2657. }
  2658. var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
  2659. if (!seeking) stream.position += bytesRead;
  2660. return bytesRead;
  2661. },write:(stream, buffer, offset, length, position, canOwn) => {
  2662. if (length < 0 || position < 0) {
  2663. throw new FS.ErrnoError(28);
  2664. }
  2665. if (FS.isClosed(stream)) {
  2666. throw new FS.ErrnoError(8);
  2667. }
  2668. if ((stream.flags & 2097155) === 0) {
  2669. throw new FS.ErrnoError(8);
  2670. }
  2671. if (FS.isDir(stream.node.mode)) {
  2672. throw new FS.ErrnoError(31);
  2673. }
  2674. if (!stream.stream_ops.write) {
  2675. throw new FS.ErrnoError(28);
  2676. }
  2677. if (stream.seekable && stream.flags & 1024) {
  2678. // seek to the end before writing in append mode
  2679. FS.llseek(stream, 0, 2);
  2680. }
  2681. var seeking = typeof position != 'undefined';
  2682. if (!seeking) {
  2683. position = stream.position;
  2684. } else if (!stream.seekable) {
  2685. throw new FS.ErrnoError(70);
  2686. }
  2687. var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
  2688. if (!seeking) stream.position += bytesWritten;
  2689. return bytesWritten;
  2690. },allocate:(stream, offset, length) => {
  2691. if (FS.isClosed(stream)) {
  2692. throw new FS.ErrnoError(8);
  2693. }
  2694. if (offset < 0 || length <= 0) {
  2695. throw new FS.ErrnoError(28);
  2696. }
  2697. if ((stream.flags & 2097155) === 0) {
  2698. throw new FS.ErrnoError(8);
  2699. }
  2700. if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
  2701. throw new FS.ErrnoError(43);
  2702. }
  2703. if (!stream.stream_ops.allocate) {
  2704. throw new FS.ErrnoError(138);
  2705. }
  2706. stream.stream_ops.allocate(stream, offset, length);
  2707. },mmap:(stream, length, position, prot, flags) => {
  2708. // User requests writing to file (prot & PROT_WRITE != 0).
  2709. // Checking if we have permissions to write to the file unless
  2710. // MAP_PRIVATE flag is set. According to POSIX spec it is possible
  2711. // to write to file opened in read-only mode with MAP_PRIVATE flag,
  2712. // as all modifications will be visible only in the memory of
  2713. // the current process.
  2714. if ((prot & 2) !== 0
  2715. && (flags & 2) === 0
  2716. && (stream.flags & 2097155) !== 2) {
  2717. throw new FS.ErrnoError(2);
  2718. }
  2719. if ((stream.flags & 2097155) === 1) {
  2720. throw new FS.ErrnoError(2);
  2721. }
  2722. if (!stream.stream_ops.mmap) {
  2723. throw new FS.ErrnoError(43);
  2724. }
  2725. return stream.stream_ops.mmap(stream, length, position, prot, flags);
  2726. },msync:(stream, buffer, offset, length, mmapFlags) => {
  2727. if (!stream.stream_ops.msync) {
  2728. return 0;
  2729. }
  2730. return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
  2731. },munmap:(stream) => 0,ioctl:(stream, cmd, arg) => {
  2732. if (!stream.stream_ops.ioctl) {
  2733. throw new FS.ErrnoError(59);
  2734. }
  2735. return stream.stream_ops.ioctl(stream, cmd, arg);
  2736. },readFile:(path, opts = {}) => {
  2737. opts.flags = opts.flags || 0;
  2738. opts.encoding = opts.encoding || 'binary';
  2739. if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
  2740. throw new Error('Invalid encoding type "' + opts.encoding + '"');
  2741. }
  2742. var ret;
  2743. var stream = FS.open(path, opts.flags);
  2744. var stat = FS.stat(path);
  2745. var length = stat.size;
  2746. var buf = new Uint8Array(length);
  2747. FS.read(stream, buf, 0, length, 0);
  2748. if (opts.encoding === 'utf8') {
  2749. ret = UTF8ArrayToString(buf, 0);
  2750. } else if (opts.encoding === 'binary') {
  2751. ret = buf;
  2752. }
  2753. FS.close(stream);
  2754. return ret;
  2755. },writeFile:(path, data, opts = {}) => {
  2756. opts.flags = opts.flags || 577;
  2757. var stream = FS.open(path, opts.flags, opts.mode);
  2758. if (typeof data == 'string') {
  2759. var buf = new Uint8Array(lengthBytesUTF8(data)+1);
  2760. var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
  2761. FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
  2762. } else if (ArrayBuffer.isView(data)) {
  2763. FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
  2764. } else {
  2765. throw new Error('Unsupported data type');
  2766. }
  2767. FS.close(stream);
  2768. },cwd:() => FS.currentPath,chdir:(path) => {
  2769. var lookup = FS.lookupPath(path, { follow: true });
  2770. if (lookup.node === null) {
  2771. throw new FS.ErrnoError(44);
  2772. }
  2773. if (!FS.isDir(lookup.node.mode)) {
  2774. throw new FS.ErrnoError(54);
  2775. }
  2776. var errCode = FS.nodePermissions(lookup.node, 'x');
  2777. if (errCode) {
  2778. throw new FS.ErrnoError(errCode);
  2779. }
  2780. FS.currentPath = lookup.path;
  2781. },createDefaultDirectories:() => {
  2782. FS.mkdir('/tmp');
  2783. FS.mkdir('/home');
  2784. FS.mkdir('/home/web_user');
  2785. },createDefaultDevices:() => {
  2786. // create /dev
  2787. FS.mkdir('/dev');
  2788. // setup /dev/null
  2789. FS.registerDevice(FS.makedev(1, 3), {
  2790. read: () => 0,
  2791. write: (stream, buffer, offset, length, pos) => length,
  2792. });
  2793. FS.mkdev('/dev/null', FS.makedev(1, 3));
  2794. // setup /dev/tty and /dev/tty1
  2795. // stderr needs to print output using err() rather than out()
  2796. // so we register a second tty just for it.
  2797. TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
  2798. TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
  2799. FS.mkdev('/dev/tty', FS.makedev(5, 0));
  2800. FS.mkdev('/dev/tty1', FS.makedev(6, 0));
  2801. // setup /dev/[u]random
  2802. var random_device = getRandomDevice();
  2803. FS.createDevice('/dev', 'random', random_device);
  2804. FS.createDevice('/dev', 'urandom', random_device);
  2805. // we're not going to emulate the actual shm device,
  2806. // just create the tmp dirs that reside in it commonly
  2807. FS.mkdir('/dev/shm');
  2808. FS.mkdir('/dev/shm/tmp');
  2809. },createSpecialDirectories:() => {
  2810. // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the
  2811. // name of the stream for fd 6 (see test_unistd_ttyname)
  2812. FS.mkdir('/proc');
  2813. var proc_self = FS.mkdir('/proc/self');
  2814. FS.mkdir('/proc/self/fd');
  2815. FS.mount({
  2816. mount: () => {
  2817. var node = FS.createNode(proc_self, 'fd', 16384 | 511 /* 0777 */, 73);
  2818. node.node_ops = {
  2819. lookup: (parent, name) => {
  2820. var fd = +name;
  2821. var stream = FS.getStream(fd);
  2822. if (!stream) throw new FS.ErrnoError(8);
  2823. var ret = {
  2824. parent: null,
  2825. mount: { mountpoint: 'fake' },
  2826. node_ops: { readlink: () => stream.path },
  2827. };
  2828. ret.parent = ret; // make it look like a simple root node
  2829. return ret;
  2830. }
  2831. };
  2832. return node;
  2833. }
  2834. }, {}, '/proc/self/fd');
  2835. },createStandardStreams:() => {
  2836. // TODO deprecate the old functionality of a single
  2837. // input / output callback and that utilizes FS.createDevice
  2838. // and instead require a unique set of stream ops
  2839. // by default, we symlink the standard streams to the
  2840. // default tty devices. however, if the standard streams
  2841. // have been overwritten we create a unique device for
  2842. // them instead.
  2843. if (Module['stdin']) {
  2844. FS.createDevice('/dev', 'stdin', Module['stdin']);
  2845. } else {
  2846. FS.symlink('/dev/tty', '/dev/stdin');
  2847. }
  2848. if (Module['stdout']) {
  2849. FS.createDevice('/dev', 'stdout', null, Module['stdout']);
  2850. } else {
  2851. FS.symlink('/dev/tty', '/dev/stdout');
  2852. }
  2853. if (Module['stderr']) {
  2854. FS.createDevice('/dev', 'stderr', null, Module['stderr']);
  2855. } else {
  2856. FS.symlink('/dev/tty1', '/dev/stderr');
  2857. }
  2858. // open default streams for the stdin, stdout and stderr devices
  2859. var stdin = FS.open('/dev/stdin', 0);
  2860. var stdout = FS.open('/dev/stdout', 1);
  2861. var stderr = FS.open('/dev/stderr', 1);
  2862. assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
  2863. assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
  2864. assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
  2865. },ensureErrnoError:() => {
  2866. if (FS.ErrnoError) return;
  2867. FS.ErrnoError = /** @this{Object} */ function ErrnoError(errno, node) {
  2868. this.node = node;
  2869. this.setErrno = /** @this{Object} */ function(errno) {
  2870. this.errno = errno;
  2871. for (var key in ERRNO_CODES) {
  2872. if (ERRNO_CODES[key] === errno) {
  2873. this.code = key;
  2874. break;
  2875. }
  2876. }
  2877. };
  2878. this.setErrno(errno);
  2879. this.message = ERRNO_MESSAGES[errno];
  2880. // Try to get a maximally helpful stack trace. On Node.js, getting Error.stack
  2881. // now ensures it shows what we want.
  2882. if (this.stack) {
  2883. // Define the stack property for Node.js 4, which otherwise errors on the next line.
  2884. Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true });
  2885. this.stack = demangleAll(this.stack);
  2886. }
  2887. };
  2888. FS.ErrnoError.prototype = new Error();
  2889. FS.ErrnoError.prototype.constructor = FS.ErrnoError;
  2890. // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
  2891. [44].forEach((code) => {
  2892. FS.genericErrors[code] = new FS.ErrnoError(code);
  2893. FS.genericErrors[code].stack = '<generic error, no stack>';
  2894. });
  2895. },staticInit:() => {
  2896. FS.ensureErrnoError();
  2897. FS.nameTable = new Array(4096);
  2898. FS.mount(MEMFS, {}, '/');
  2899. FS.createDefaultDirectories();
  2900. FS.createDefaultDevices();
  2901. FS.createSpecialDirectories();
  2902. FS.filesystems = {
  2903. 'MEMFS': MEMFS,
  2904. };
  2905. },init:(input, output, error) => {
  2906. 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)');
  2907. FS.init.initialized = true;
  2908. FS.ensureErrnoError();
  2909. // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
  2910. Module['stdin'] = input || Module['stdin'];
  2911. Module['stdout'] = output || Module['stdout'];
  2912. Module['stderr'] = error || Module['stderr'];
  2913. FS.createStandardStreams();
  2914. },quit:() => {
  2915. FS.init.initialized = false;
  2916. // force-flush all streams, so we get musl std streams printed out
  2917. _fflush(0);
  2918. // close all of our streams
  2919. for (var i = 0; i < FS.streams.length; i++) {
  2920. var stream = FS.streams[i];
  2921. if (!stream) {
  2922. continue;
  2923. }
  2924. FS.close(stream);
  2925. }
  2926. },getMode:(canRead, canWrite) => {
  2927. var mode = 0;
  2928. if (canRead) mode |= 292 | 73;
  2929. if (canWrite) mode |= 146;
  2930. return mode;
  2931. },findObject:(path, dontResolveLastLink) => {
  2932. var ret = FS.analyzePath(path, dontResolveLastLink);
  2933. if (!ret.exists) {
  2934. return null;
  2935. }
  2936. return ret.object;
  2937. },analyzePath:(path, dontResolveLastLink) => {
  2938. // operate from within the context of the symlink's target
  2939. try {
  2940. var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  2941. path = lookup.path;
  2942. } catch (e) {
  2943. }
  2944. var ret = {
  2945. isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
  2946. parentExists: false, parentPath: null, parentObject: null
  2947. };
  2948. try {
  2949. var lookup = FS.lookupPath(path, { parent: true });
  2950. ret.parentExists = true;
  2951. ret.parentPath = lookup.path;
  2952. ret.parentObject = lookup.node;
  2953. ret.name = PATH.basename(path);
  2954. lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
  2955. ret.exists = true;
  2956. ret.path = lookup.path;
  2957. ret.object = lookup.node;
  2958. ret.name = lookup.node.name;
  2959. ret.isRoot = lookup.path === '/';
  2960. } catch (e) {
  2961. ret.error = e.errno;
  2962. };
  2963. return ret;
  2964. },createPath:(parent, path, canRead, canWrite) => {
  2965. parent = typeof parent == 'string' ? parent : FS.getPath(parent);
  2966. var parts = path.split('/').reverse();
  2967. while (parts.length) {
  2968. var part = parts.pop();
  2969. if (!part) continue;
  2970. var current = PATH.join2(parent, part);
  2971. try {
  2972. FS.mkdir(current);
  2973. } catch (e) {
  2974. // ignore EEXIST
  2975. }
  2976. parent = current;
  2977. }
  2978. return current;
  2979. },createFile:(parent, name, properties, canRead, canWrite) => {
  2980. var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
  2981. var mode = FS.getMode(canRead, canWrite);
  2982. return FS.create(path, mode);
  2983. },createDataFile:(parent, name, data, canRead, canWrite, canOwn) => {
  2984. var path = name;
  2985. if (parent) {
  2986. parent = typeof parent == 'string' ? parent : FS.getPath(parent);
  2987. path = name ? PATH.join2(parent, name) : parent;
  2988. }
  2989. var mode = FS.getMode(canRead, canWrite);
  2990. var node = FS.create(path, mode);
  2991. if (data) {
  2992. if (typeof data == 'string') {
  2993. var arr = new Array(data.length);
  2994. for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
  2995. data = arr;
  2996. }
  2997. // make sure we can write to the file
  2998. FS.chmod(node, mode | 146);
  2999. var stream = FS.open(node, 577);
  3000. FS.write(stream, data, 0, data.length, 0, canOwn);
  3001. FS.close(stream);
  3002. FS.chmod(node, mode);
  3003. }
  3004. return node;
  3005. },createDevice:(parent, name, input, output) => {
  3006. var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
  3007. var mode = FS.getMode(!!input, !!output);
  3008. if (!FS.createDevice.major) FS.createDevice.major = 64;
  3009. var dev = FS.makedev(FS.createDevice.major++, 0);
  3010. // Create a fake device that a set of stream ops to emulate
  3011. // the old behavior.
  3012. FS.registerDevice(dev, {
  3013. open: (stream) => {
  3014. stream.seekable = false;
  3015. },
  3016. close: (stream) => {
  3017. // flush any pending line data
  3018. if (output && output.buffer && output.buffer.length) {
  3019. output(10);
  3020. }
  3021. },
  3022. read: (stream, buffer, offset, length, pos /* ignored */) => {
  3023. var bytesRead = 0;
  3024. for (var i = 0; i < length; i++) {
  3025. var result;
  3026. try {
  3027. result = input();
  3028. } catch (e) {
  3029. throw new FS.ErrnoError(29);
  3030. }
  3031. if (result === undefined && bytesRead === 0) {
  3032. throw new FS.ErrnoError(6);
  3033. }
  3034. if (result === null || result === undefined) break;
  3035. bytesRead++;
  3036. buffer[offset+i] = result;
  3037. }
  3038. if (bytesRead) {
  3039. stream.node.timestamp = Date.now();
  3040. }
  3041. return bytesRead;
  3042. },
  3043. write: (stream, buffer, offset, length, pos) => {
  3044. for (var i = 0; i < length; i++) {
  3045. try {
  3046. output(buffer[offset+i]);
  3047. } catch (e) {
  3048. throw new FS.ErrnoError(29);
  3049. }
  3050. }
  3051. if (length) {
  3052. stream.node.timestamp = Date.now();
  3053. }
  3054. return i;
  3055. }
  3056. });
  3057. return FS.mkdev(path, mode, dev);
  3058. },forceLoadFile:(obj) => {
  3059. if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
  3060. if (typeof XMLHttpRequest != 'undefined') {
  3061. 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.");
  3062. } else if (read_) {
  3063. // Command-line.
  3064. try {
  3065. // WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
  3066. // read() will try to parse UTF8.
  3067. obj.contents = intArrayFromString(read_(obj.url), true);
  3068. obj.usedBytes = obj.contents.length;
  3069. } catch (e) {
  3070. throw new FS.ErrnoError(29);
  3071. }
  3072. } else {
  3073. throw new Error('Cannot load without read() or XMLHttpRequest.');
  3074. }
  3075. },createLazyFile:(parent, name, url, canRead, canWrite) => {
  3076. // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
  3077. /** @constructor */
  3078. function LazyUint8Array() {
  3079. this.lengthKnown = false;
  3080. this.chunks = []; // Loaded chunks. Index is the chunk number
  3081. }
  3082. LazyUint8Array.prototype.get = /** @this{Object} */ function LazyUint8Array_get(idx) {
  3083. if (idx > this.length-1 || idx < 0) {
  3084. return undefined;
  3085. }
  3086. var chunkOffset = idx % this.chunkSize;
  3087. var chunkNum = (idx / this.chunkSize)|0;
  3088. return this.getter(chunkNum)[chunkOffset];
  3089. };
  3090. LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
  3091. this.getter = getter;
  3092. };
  3093. LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
  3094. // Find length
  3095. var xhr = new XMLHttpRequest();
  3096. xhr.open('HEAD', url, false);
  3097. xhr.send(null);
  3098. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3099. var datalength = Number(xhr.getResponseHeader("Content-length"));
  3100. var header;
  3101. var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
  3102. var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
  3103. var chunkSize = 1024*1024; // Chunk size in bytes
  3104. if (!hasByteServing) chunkSize = datalength;
  3105. // Function to get a range from the remote URL.
  3106. var doXHR = (from, to) => {
  3107. if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
  3108. if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
  3109. // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
  3110. var xhr = new XMLHttpRequest();
  3111. xhr.open('GET', url, false);
  3112. if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
  3113. // Some hints to the browser that we want binary data.
  3114. xhr.responseType = 'arraybuffer';
  3115. if (xhr.overrideMimeType) {
  3116. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  3117. }
  3118. xhr.send(null);
  3119. if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
  3120. if (xhr.response !== undefined) {
  3121. return new Uint8Array(/** @type{Array<number>} */(xhr.response || []));
  3122. }
  3123. return intArrayFromString(xhr.responseText || '', true);
  3124. };
  3125. var lazyArray = this;
  3126. lazyArray.setDataGetter((chunkNum) => {
  3127. var start = chunkNum * chunkSize;
  3128. var end = (chunkNum+1) * chunkSize - 1; // including this byte
  3129. end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
  3130. if (typeof lazyArray.chunks[chunkNum] == 'undefined') {
  3131. lazyArray.chunks[chunkNum] = doXHR(start, end);
  3132. }
  3133. if (typeof lazyArray.chunks[chunkNum] == 'undefined') throw new Error('doXHR failed!');
  3134. return lazyArray.chunks[chunkNum];
  3135. });
  3136. if (usesGzip || !datalength) {
  3137. // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
  3138. chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
  3139. datalength = this.getter(0).length;
  3140. chunkSize = datalength;
  3141. out("LazyFiles on gzip forces download of the whole file when length is accessed");
  3142. }
  3143. this._length = datalength;
  3144. this._chunkSize = chunkSize;
  3145. this.lengthKnown = true;
  3146. };
  3147. if (typeof XMLHttpRequest != 'undefined') {
  3148. if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
  3149. var lazyArray = new LazyUint8Array();
  3150. Object.defineProperties(lazyArray, {
  3151. length: {
  3152. get: /** @this{Object} */ function() {
  3153. if (!this.lengthKnown) {
  3154. this.cacheLength();
  3155. }
  3156. return this._length;
  3157. }
  3158. },
  3159. chunkSize: {
  3160. get: /** @this{Object} */ function() {
  3161. if (!this.lengthKnown) {
  3162. this.cacheLength();
  3163. }
  3164. return this._chunkSize;
  3165. }
  3166. }
  3167. });
  3168. var properties = { isDevice: false, contents: lazyArray };
  3169. } else {
  3170. var properties = { isDevice: false, url: url };
  3171. }
  3172. var node = FS.createFile(parent, name, properties, canRead, canWrite);
  3173. // This is a total hack, but I want to get this lazy file code out of the
  3174. // core of MEMFS. If we want to keep this lazy file concept I feel it should
  3175. // be its own thin LAZYFS proxying calls to MEMFS.
  3176. if (properties.contents) {
  3177. node.contents = properties.contents;
  3178. } else if (properties.url) {
  3179. node.contents = null;
  3180. node.url = properties.url;
  3181. }
  3182. // Add a function that defers querying the file size until it is asked the first time.
  3183. Object.defineProperties(node, {
  3184. usedBytes: {
  3185. get: /** @this {FSNode} */ function() { return this.contents.length; }
  3186. }
  3187. });
  3188. // override each stream op with one that tries to force load the lazy file first
  3189. var stream_ops = {};
  3190. var keys = Object.keys(node.stream_ops);
  3191. keys.forEach((key) => {
  3192. var fn = node.stream_ops[key];
  3193. stream_ops[key] = function forceLoadLazyFile() {
  3194. FS.forceLoadFile(node);
  3195. return fn.apply(null, arguments);
  3196. };
  3197. });
  3198. function writeChunks(stream, buffer, offset, length, position) {
  3199. var contents = stream.node.contents;
  3200. if (position >= contents.length)
  3201. return 0;
  3202. var size = Math.min(contents.length - position, length);
  3203. assert(size >= 0);
  3204. if (contents.slice) { // normal array
  3205. for (var i = 0; i < size; i++) {
  3206. buffer[offset + i] = contents[position + i];
  3207. }
  3208. } else {
  3209. for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
  3210. buffer[offset + i] = contents.get(position + i);
  3211. }
  3212. }
  3213. return size;
  3214. }
  3215. // use a custom read function
  3216. stream_ops.read = (stream, buffer, offset, length, position) => {
  3217. FS.forceLoadFile(node);
  3218. return writeChunks(stream, buffer, offset, length, position)
  3219. };
  3220. // use a custom mmap function
  3221. stream_ops.mmap = (stream, length, position, prot, flags) => {
  3222. FS.forceLoadFile(node);
  3223. var ptr = mmapAlloc(length);
  3224. if (!ptr) {
  3225. throw new FS.ErrnoError(48);
  3226. }
  3227. writeChunks(stream, HEAP8, ptr, length, position);
  3228. return { ptr: ptr, allocated: true };
  3229. };
  3230. node.stream_ops = stream_ops;
  3231. return node;
  3232. },createPreloadedFile:(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
  3233. // TODO we should allow people to just pass in a complete filename instead
  3234. // of parent and name being that we just join them anyways
  3235. var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
  3236. var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
  3237. function processData(byteArray) {
  3238. function finish(byteArray) {
  3239. if (preFinish) preFinish();
  3240. if (!dontCreateFile) {
  3241. FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
  3242. }
  3243. if (onload) onload();
  3244. removeRunDependency(dep);
  3245. }
  3246. if (Browser.handledByPreloadPlugin(byteArray, fullname, finish, () => {
  3247. if (onerror) onerror();
  3248. removeRunDependency(dep);
  3249. })) {
  3250. return;
  3251. }
  3252. finish(byteArray);
  3253. }
  3254. addRunDependency(dep);
  3255. if (typeof url == 'string') {
  3256. asyncLoad(url, (byteArray) => processData(byteArray), onerror);
  3257. } else {
  3258. processData(url);
  3259. }
  3260. },indexedDB:() => {
  3261. return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  3262. },DB_NAME:() => {
  3263. return 'EM_FS_' + window.location.pathname;
  3264. },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths, onload, onerror) => {
  3265. onload = onload || (() => {});
  3266. onerror = onerror || (() => {});
  3267. var indexedDB = FS.indexedDB();
  3268. try {
  3269. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3270. } catch (e) {
  3271. return onerror(e);
  3272. }
  3273. openRequest.onupgradeneeded = () => {
  3274. out('creating db');
  3275. var db = openRequest.result;
  3276. db.createObjectStore(FS.DB_STORE_NAME);
  3277. };
  3278. openRequest.onsuccess = () => {
  3279. var db = openRequest.result;
  3280. var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
  3281. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3282. var ok = 0, fail = 0, total = paths.length;
  3283. function finish() {
  3284. if (fail == 0) onload(); else onerror();
  3285. }
  3286. paths.forEach((path) => {
  3287. var putRequest = files.put(FS.analyzePath(path).object.contents, path);
  3288. putRequest.onsuccess = () => { ok++; if (ok + fail == total) finish() };
  3289. putRequest.onerror = () => { fail++; if (ok + fail == total) finish() };
  3290. });
  3291. transaction.onerror = onerror;
  3292. };
  3293. openRequest.onerror = onerror;
  3294. },loadFilesFromDB:(paths, onload, onerror) => {
  3295. onload = onload || (() => {});
  3296. onerror = onerror || (() => {});
  3297. var indexedDB = FS.indexedDB();
  3298. try {
  3299. var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
  3300. } catch (e) {
  3301. return onerror(e);
  3302. }
  3303. openRequest.onupgradeneeded = onerror; // no database to load from
  3304. openRequest.onsuccess = () => {
  3305. var db = openRequest.result;
  3306. try {
  3307. var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
  3308. } catch(e) {
  3309. onerror(e);
  3310. return;
  3311. }
  3312. var files = transaction.objectStore(FS.DB_STORE_NAME);
  3313. var ok = 0, fail = 0, total = paths.length;
  3314. function finish() {
  3315. if (fail == 0) onload(); else onerror();
  3316. }
  3317. paths.forEach((path) => {
  3318. var getRequest = files.get(path);
  3319. getRequest.onsuccess = () => {
  3320. if (FS.analyzePath(path).exists) {
  3321. FS.unlink(path);
  3322. }
  3323. FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
  3324. ok++;
  3325. if (ok + fail == total) finish();
  3326. };
  3327. getRequest.onerror = () => { fail++; if (ok + fail == total) finish() };
  3328. });
  3329. transaction.onerror = onerror;
  3330. };
  3331. openRequest.onerror = onerror;
  3332. },absolutePath:() => {
  3333. abort('FS.absolutePath has been removed; use PATH_FS.resolve instead');
  3334. },createFolder:() => {
  3335. abort('FS.createFolder has been removed; use FS.mkdir instead');
  3336. },createLink:() => {
  3337. abort('FS.createLink has been removed; use FS.symlink instead');
  3338. },joinPath:() => {
  3339. abort('FS.joinPath has been removed; use PATH.join instead');
  3340. },mmapAlloc:() => {
  3341. abort('FS.mmapAlloc has been replaced by the top level function mmapAlloc');
  3342. },standardizePath:() => {
  3343. abort('FS.standardizePath has been removed; use PATH.normalize instead');
  3344. }};
  3345. var SOCKFS = {mount:function(mount) {
  3346. // If Module['websocket'] has already been defined (e.g. for configuring
  3347. // the subprotocol/url) use that, if not initialise it to a new object.
  3348. Module['websocket'] = (Module['websocket'] &&
  3349. ('object' === typeof Module['websocket'])) ? Module['websocket'] : {};
  3350. // Add the Event registration mechanism to the exported websocket configuration
  3351. // object so we can register network callbacks from native JavaScript too.
  3352. // For more documentation see system/include/emscripten/emscripten.h
  3353. Module['websocket']._callbacks = {};
  3354. Module['websocket']['on'] = /** @this{Object} */ function(event, callback) {
  3355. if ('function' === typeof callback) {
  3356. this._callbacks[event] = callback;
  3357. }
  3358. return this;
  3359. };
  3360. Module['websocket'].emit = /** @this{Object} */ function(event, param) {
  3361. if ('function' === typeof this._callbacks[event]) {
  3362. this._callbacks[event].call(this, param);
  3363. }
  3364. };
  3365. // If debug is enabled register simple default logging callbacks for each Event.
  3366. return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
  3367. },createSocket:function(family, type, protocol) {
  3368. type &= ~526336; // Some applications may pass it; it makes no sense for a single process.
  3369. var streaming = type == 1;
  3370. if (streaming && protocol && protocol != 6) {
  3371. throw new FS.ErrnoError(66); // if SOCK_STREAM, must be tcp or 0.
  3372. }
  3373. // create our internal socket structure
  3374. var sock = {
  3375. family: family,
  3376. type: type,
  3377. protocol: protocol,
  3378. server: null,
  3379. error: null, // Used in getsockopt for SOL_SOCKET/SO_ERROR test
  3380. peers: {},
  3381. pending: [],
  3382. recv_queue: [],
  3383. sock_ops: SOCKFS.websocket_sock_ops
  3384. };
  3385. // create the filesystem node to store the socket structure
  3386. var name = SOCKFS.nextname();
  3387. var node = FS.createNode(SOCKFS.root, name, 49152, 0);
  3388. node.sock = sock;
  3389. // and the wrapping stream that enables library functions such
  3390. // as read and write to indirectly interact with the socket
  3391. var stream = FS.createStream({
  3392. path: name,
  3393. node: node,
  3394. flags: 2,
  3395. seekable: false,
  3396. stream_ops: SOCKFS.stream_ops
  3397. });
  3398. // map the new stream to the socket structure (sockets have a 1:1
  3399. // relationship with a stream)
  3400. sock.stream = stream;
  3401. return sock;
  3402. },getSocket:function(fd) {
  3403. var stream = FS.getStream(fd);
  3404. if (!stream || !FS.isSocket(stream.node.mode)) {
  3405. return null;
  3406. }
  3407. return stream.node.sock;
  3408. },stream_ops:{poll:function(stream) {
  3409. var sock = stream.node.sock;
  3410. return sock.sock_ops.poll(sock);
  3411. },ioctl:function(stream, request, varargs) {
  3412. var sock = stream.node.sock;
  3413. return sock.sock_ops.ioctl(sock, request, varargs);
  3414. },read:function(stream, buffer, offset, length, position /* ignored */) {
  3415. var sock = stream.node.sock;
  3416. var msg = sock.sock_ops.recvmsg(sock, length);
  3417. if (!msg) {
  3418. // socket is closed
  3419. return 0;
  3420. }
  3421. buffer.set(msg.buffer, offset);
  3422. return msg.buffer.length;
  3423. },write:function(stream, buffer, offset, length, position /* ignored */) {
  3424. var sock = stream.node.sock;
  3425. return sock.sock_ops.sendmsg(sock, buffer, offset, length);
  3426. },close:function(stream) {
  3427. var sock = stream.node.sock;
  3428. sock.sock_ops.close(sock);
  3429. }},nextname:function() {
  3430. if (!SOCKFS.nextname.current) {
  3431. SOCKFS.nextname.current = 0;
  3432. }
  3433. return 'socket[' + (SOCKFS.nextname.current++) + ']';
  3434. },websocket_sock_ops:{createPeer:function(sock, addr, port) {
  3435. var ws;
  3436. if (typeof addr == 'object') {
  3437. ws = addr;
  3438. addr = null;
  3439. port = null;
  3440. }
  3441. if (ws) {
  3442. // for sockets that've already connected (e.g. we're the server)
  3443. // we can inspect the _socket property for the address
  3444. if (ws._socket) {
  3445. addr = ws._socket.remoteAddress;
  3446. port = ws._socket.remotePort;
  3447. }
  3448. // if we're just now initializing a connection to the remote,
  3449. // inspect the url property
  3450. else {
  3451. var result = /ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);
  3452. if (!result) {
  3453. throw new Error('WebSocket URL must be in the format ws(s)://address:port');
  3454. }
  3455. addr = result[1];
  3456. port = parseInt(result[2], 10);
  3457. }
  3458. } else {
  3459. // create the actual websocket object and connect
  3460. try {
  3461. // runtimeConfig gets set to true if WebSocket runtime configuration is available.
  3462. var runtimeConfig = (Module['websocket'] && ('object' === typeof Module['websocket']));
  3463. // The default value is 'ws://' the replace is needed because the compiler replaces '//' comments with '#'
  3464. // comments without checking context, so we'd end up with ws:#, the replace swaps the '#' for '//' again.
  3465. var url = 'ws:#'.replace('#', '//');
  3466. if (runtimeConfig) {
  3467. if ('string' === typeof Module['websocket']['url']) {
  3468. url = Module['websocket']['url']; // Fetch runtime WebSocket URL config.
  3469. }
  3470. }
  3471. if (url === 'ws://' || url === 'wss://') { // Is the supplied URL config just a prefix, if so complete it.
  3472. var parts = addr.split('/');
  3473. url = url + parts[0] + ":" + port + "/" + parts.slice(1).join('/');
  3474. }
  3475. // Make the WebSocket subprotocol (Sec-WebSocket-Protocol) default to binary if no configuration is set.
  3476. var subProtocols = 'binary'; // The default value is 'binary'
  3477. if (runtimeConfig) {
  3478. if ('string' === typeof Module['websocket']['subprotocol']) {
  3479. subProtocols = Module['websocket']['subprotocol']; // Fetch runtime WebSocket subprotocol config.
  3480. }
  3481. }
  3482. // The default WebSocket options
  3483. var opts = undefined;
  3484. if (subProtocols !== 'null') {
  3485. // The regex trims the string (removes spaces at the beginning and end, then splits the string by
  3486. // <any space>,<any space> into an Array. Whitespace removal is important for Websockify and ws.
  3487. subProtocols = subProtocols.replace(/^ +| +$/g,"").split(/ *, */);
  3488. opts = subProtocols;
  3489. }
  3490. // some webservers (azure) does not support subprotocol header
  3491. if (runtimeConfig && null === Module['websocket']['subprotocol']) {
  3492. subProtocols = 'null';
  3493. opts = undefined;
  3494. }
  3495. // If node we use the ws library.
  3496. var WebSocketConstructor;
  3497. if (ENVIRONMENT_IS_NODE) {
  3498. WebSocketConstructor = /** @type{(typeof WebSocket)} */(require('ws'));
  3499. } else
  3500. {
  3501. WebSocketConstructor = WebSocket;
  3502. }
  3503. ws = new WebSocketConstructor(url, opts);
  3504. ws.binaryType = 'arraybuffer';
  3505. } catch (e) {
  3506. throw new FS.ErrnoError(23);
  3507. }
  3508. }
  3509. var peer = {
  3510. addr: addr,
  3511. port: port,
  3512. socket: ws,
  3513. dgram_send_queue: []
  3514. };
  3515. SOCKFS.websocket_sock_ops.addPeer(sock, peer);
  3516. SOCKFS.websocket_sock_ops.handlePeerEvents(sock, peer);
  3517. // if this is a bound dgram socket, send the port number first to allow
  3518. // us to override the ephemeral port reported to us by remotePort on the
  3519. // remote end.
  3520. if (sock.type === 2 && typeof sock.sport != 'undefined') {
  3521. peer.dgram_send_queue.push(new Uint8Array([
  3522. 255, 255, 255, 255,
  3523. 'p'.charCodeAt(0), 'o'.charCodeAt(0), 'r'.charCodeAt(0), 't'.charCodeAt(0),
  3524. ((sock.sport & 0xff00) >> 8) , (sock.sport & 0xff)
  3525. ]));
  3526. }
  3527. return peer;
  3528. },getPeer:function(sock, addr, port) {
  3529. return sock.peers[addr + ':' + port];
  3530. },addPeer:function(sock, peer) {
  3531. sock.peers[peer.addr + ':' + peer.port] = peer;
  3532. },removePeer:function(sock, peer) {
  3533. delete sock.peers[peer.addr + ':' + peer.port];
  3534. },handlePeerEvents:function(sock, peer) {
  3535. var first = true;
  3536. var handleOpen = function () {
  3537. Module['websocket'].emit('open', sock.stream.fd);
  3538. try {
  3539. var queued = peer.dgram_send_queue.shift();
  3540. while (queued) {
  3541. peer.socket.send(queued);
  3542. queued = peer.dgram_send_queue.shift();
  3543. }
  3544. } catch (e) {
  3545. // not much we can do here in the way of proper error handling as we've already
  3546. // lied and said this data was sent. shut it down.
  3547. peer.socket.close();
  3548. }
  3549. };
  3550. function handleMessage(data) {
  3551. if (typeof data == 'string') {
  3552. var encoder = new TextEncoder(); // should be utf-8
  3553. data = encoder.encode(data); // make a typed array from the string
  3554. } else {
  3555. assert(data.byteLength !== undefined); // must receive an ArrayBuffer
  3556. if (data.byteLength == 0) {
  3557. // An empty ArrayBuffer will emit a pseudo disconnect event
  3558. // as recv/recvmsg will return zero which indicates that a socket
  3559. // has performed a shutdown although the connection has not been disconnected yet.
  3560. return;
  3561. }
  3562. data = new Uint8Array(data); // make a typed array view on the array buffer
  3563. }
  3564. // if this is the port message, override the peer's port with it
  3565. var wasfirst = first;
  3566. first = false;
  3567. if (wasfirst &&
  3568. data.length === 10 &&
  3569. data[0] === 255 && data[1] === 255 && data[2] === 255 && data[3] === 255 &&
  3570. data[4] === 'p'.charCodeAt(0) && data[5] === 'o'.charCodeAt(0) && data[6] === 'r'.charCodeAt(0) && data[7] === 't'.charCodeAt(0)) {
  3571. // update the peer's port and it's key in the peer map
  3572. var newport = ((data[8] << 8) | data[9]);
  3573. SOCKFS.websocket_sock_ops.removePeer(sock, peer);
  3574. peer.port = newport;
  3575. SOCKFS.websocket_sock_ops.addPeer(sock, peer);
  3576. return;
  3577. }
  3578. sock.recv_queue.push({ addr: peer.addr, port: peer.port, data: data });
  3579. Module['websocket'].emit('message', sock.stream.fd);
  3580. };
  3581. if (ENVIRONMENT_IS_NODE) {
  3582. peer.socket.on('open', handleOpen);
  3583. peer.socket.on('message', function(data, isBinary) {
  3584. if (!isBinary) {
  3585. return;
  3586. }
  3587. handleMessage((new Uint8Array(data)).buffer); // copy from node Buffer -> ArrayBuffer
  3588. });
  3589. peer.socket.on('close', function() {
  3590. Module['websocket'].emit('close', sock.stream.fd);
  3591. });
  3592. peer.socket.on('error', function(error) {
  3593. // Although the ws library may pass errors that may be more descriptive than
  3594. // ECONNREFUSED they are not necessarily the expected error code e.g.
  3595. // ENOTFOUND on getaddrinfo seems to be node.js specific, so using ECONNREFUSED
  3596. // is still probably the most useful thing to do.
  3597. sock.error = 14; // Used in getsockopt for SOL_SOCKET/SO_ERROR test.
  3598. Module['websocket'].emit('error', [sock.stream.fd, sock.error, 'ECONNREFUSED: Connection refused']);
  3599. // don't throw
  3600. });
  3601. } else {
  3602. peer.socket.onopen = handleOpen;
  3603. peer.socket.onclose = function() {
  3604. Module['websocket'].emit('close', sock.stream.fd);
  3605. };
  3606. peer.socket.onmessage = function peer_socket_onmessage(event) {
  3607. handleMessage(event.data);
  3608. };
  3609. peer.socket.onerror = function(error) {
  3610. // The WebSocket spec only allows a 'simple event' to be thrown on error,
  3611. // so we only really know as much as ECONNREFUSED.
  3612. sock.error = 14; // Used in getsockopt for SOL_SOCKET/SO_ERROR test.
  3613. Module['websocket'].emit('error', [sock.stream.fd, sock.error, 'ECONNREFUSED: Connection refused']);
  3614. };
  3615. }
  3616. },poll:function(sock) {
  3617. if (sock.type === 1 && sock.server) {
  3618. // listen sockets should only say they're available for reading
  3619. // if there are pending clients.
  3620. return sock.pending.length ? (64 | 1) : 0;
  3621. }
  3622. var mask = 0;
  3623. var dest = sock.type === 1 ? // we only care about the socket state for connection-based sockets
  3624. SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport) :
  3625. null;
  3626. if (sock.recv_queue.length ||
  3627. !dest || // connection-less sockets are always ready to read
  3628. (dest && dest.socket.readyState === dest.socket.CLOSING) ||
  3629. (dest && dest.socket.readyState === dest.socket.CLOSED)) { // let recv return 0 once closed
  3630. mask |= (64 | 1);
  3631. }
  3632. if (!dest || // connection-less sockets are always ready to write
  3633. (dest && dest.socket.readyState === dest.socket.OPEN)) {
  3634. mask |= 4;
  3635. }
  3636. if ((dest && dest.socket.readyState === dest.socket.CLOSING) ||
  3637. (dest && dest.socket.readyState === dest.socket.CLOSED)) {
  3638. mask |= 16;
  3639. }
  3640. return mask;
  3641. },ioctl:function(sock, request, arg) {
  3642. switch (request) {
  3643. case 21531:
  3644. var bytes = 0;
  3645. if (sock.recv_queue.length) {
  3646. bytes = sock.recv_queue[0].data.length;
  3647. }
  3648. HEAP32[((arg)>>2)] = bytes;
  3649. return 0;
  3650. default:
  3651. return 28;
  3652. }
  3653. },close:function(sock) {
  3654. // if we've spawned a listen server, close it
  3655. if (sock.server) {
  3656. try {
  3657. sock.server.close();
  3658. } catch (e) {
  3659. }
  3660. sock.server = null;
  3661. }
  3662. // close any peer connections
  3663. var peers = Object.keys(sock.peers);
  3664. for (var i = 0; i < peers.length; i++) {
  3665. var peer = sock.peers[peers[i]];
  3666. try {
  3667. peer.socket.close();
  3668. } catch (e) {
  3669. }
  3670. SOCKFS.websocket_sock_ops.removePeer(sock, peer);
  3671. }
  3672. return 0;
  3673. },bind:function(sock, addr, port) {
  3674. if (typeof sock.saddr != 'undefined' || typeof sock.sport != 'undefined') {
  3675. throw new FS.ErrnoError(28); // already bound
  3676. }
  3677. sock.saddr = addr;
  3678. sock.sport = port;
  3679. // in order to emulate dgram sockets, we need to launch a listen server when
  3680. // binding on a connection-less socket
  3681. // note: this is only required on the server side
  3682. if (sock.type === 2) {
  3683. // close the existing server if it exists
  3684. if (sock.server) {
  3685. sock.server.close();
  3686. sock.server = null;
  3687. }
  3688. // swallow error operation not supported error that occurs when binding in the
  3689. // browser where this isn't supported
  3690. try {
  3691. sock.sock_ops.listen(sock, 0);
  3692. } catch (e) {
  3693. if (!(e instanceof FS.ErrnoError)) throw e;
  3694. if (e.errno !== 138) throw e;
  3695. }
  3696. }
  3697. },connect:function(sock, addr, port) {
  3698. if (sock.server) {
  3699. throw new FS.ErrnoError(138);
  3700. }
  3701. // TODO autobind
  3702. // if (!sock.addr && sock.type == 2) {
  3703. // }
  3704. // early out if we're already connected / in the middle of connecting
  3705. if (typeof sock.daddr != 'undefined' && typeof sock.dport != 'undefined') {
  3706. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
  3707. if (dest) {
  3708. if (dest.socket.readyState === dest.socket.CONNECTING) {
  3709. throw new FS.ErrnoError(7);
  3710. } else {
  3711. throw new FS.ErrnoError(30);
  3712. }
  3713. }
  3714. }
  3715. // add the socket to our peer list and set our
  3716. // destination address / port to match
  3717. var peer = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
  3718. sock.daddr = peer.addr;
  3719. sock.dport = peer.port;
  3720. // always "fail" in non-blocking mode
  3721. throw new FS.ErrnoError(26);
  3722. },listen:function(sock, backlog) {
  3723. if (!ENVIRONMENT_IS_NODE) {
  3724. throw new FS.ErrnoError(138);
  3725. }
  3726. if (sock.server) {
  3727. throw new FS.ErrnoError(28); // already listening
  3728. }
  3729. var WebSocketServer = require('ws').Server;
  3730. var host = sock.saddr;
  3731. sock.server = new WebSocketServer({
  3732. host: host,
  3733. port: sock.sport
  3734. // TODO support backlog
  3735. });
  3736. Module['websocket'].emit('listen', sock.stream.fd); // Send Event with listen fd.
  3737. sock.server.on('connection', function(ws) {
  3738. if (sock.type === 1) {
  3739. var newsock = SOCKFS.createSocket(sock.family, sock.type, sock.protocol);
  3740. // create a peer on the new socket
  3741. var peer = SOCKFS.websocket_sock_ops.createPeer(newsock, ws);
  3742. newsock.daddr = peer.addr;
  3743. newsock.dport = peer.port;
  3744. // push to queue for accept to pick up
  3745. sock.pending.push(newsock);
  3746. Module['websocket'].emit('connection', newsock.stream.fd);
  3747. } else {
  3748. // create a peer on the listen socket so calling sendto
  3749. // with the listen socket and an address will resolve
  3750. // to the correct client
  3751. SOCKFS.websocket_sock_ops.createPeer(sock, ws);
  3752. Module['websocket'].emit('connection', sock.stream.fd);
  3753. }
  3754. });
  3755. sock.server.on('close', function() {
  3756. Module['websocket'].emit('close', sock.stream.fd);
  3757. sock.server = null;
  3758. });
  3759. sock.server.on('error', function(error) {
  3760. // Although the ws library may pass errors that may be more descriptive than
  3761. // ECONNREFUSED they are not necessarily the expected error code e.g.
  3762. // ENOTFOUND on getaddrinfo seems to be node.js specific, so using EHOSTUNREACH
  3763. // is still probably the most useful thing to do. This error shouldn't
  3764. // occur in a well written app as errors should get trapped in the compiled
  3765. // app's own getaddrinfo call.
  3766. sock.error = 23; // Used in getsockopt for SOL_SOCKET/SO_ERROR test.
  3767. Module['websocket'].emit('error', [sock.stream.fd, sock.error, 'EHOSTUNREACH: Host is unreachable']);
  3768. // don't throw
  3769. });
  3770. },accept:function(listensock) {
  3771. if (!listensock.server || !listensock.pending.length) {
  3772. throw new FS.ErrnoError(28);
  3773. }
  3774. var newsock = listensock.pending.shift();
  3775. newsock.stream.flags = listensock.stream.flags;
  3776. return newsock;
  3777. },getname:function(sock, peer) {
  3778. var addr, port;
  3779. if (peer) {
  3780. if (sock.daddr === undefined || sock.dport === undefined) {
  3781. throw new FS.ErrnoError(53);
  3782. }
  3783. addr = sock.daddr;
  3784. port = sock.dport;
  3785. } else {
  3786. // TODO saddr and sport will be set for bind()'d UDP sockets, but what
  3787. // should we be returning for TCP sockets that've been connect()'d?
  3788. addr = sock.saddr || 0;
  3789. port = sock.sport || 0;
  3790. }
  3791. return { addr: addr, port: port };
  3792. },sendmsg:function(sock, buffer, offset, length, addr, port) {
  3793. if (sock.type === 2) {
  3794. // connection-less sockets will honor the message address,
  3795. // and otherwise fall back to the bound destination address
  3796. if (addr === undefined || port === undefined) {
  3797. addr = sock.daddr;
  3798. port = sock.dport;
  3799. }
  3800. // if there was no address to fall back to, error out
  3801. if (addr === undefined || port === undefined) {
  3802. throw new FS.ErrnoError(17);
  3803. }
  3804. } else {
  3805. // connection-based sockets will only use the bound
  3806. addr = sock.daddr;
  3807. port = sock.dport;
  3808. }
  3809. // find the peer for the destination address
  3810. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, addr, port);
  3811. // early out if not connected with a connection-based socket
  3812. if (sock.type === 1) {
  3813. if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  3814. throw new FS.ErrnoError(53);
  3815. } else if (dest.socket.readyState === dest.socket.CONNECTING) {
  3816. throw new FS.ErrnoError(6);
  3817. }
  3818. }
  3819. // create a copy of the incoming data to send, as the WebSocket API
  3820. // doesn't work entirely with an ArrayBufferView, it'll just send
  3821. // the entire underlying buffer
  3822. if (ArrayBuffer.isView(buffer)) {
  3823. offset += buffer.byteOffset;
  3824. buffer = buffer.buffer;
  3825. }
  3826. var data;
  3827. data = buffer.slice(offset, offset + length);
  3828. // if we're emulating a connection-less dgram socket and don't have
  3829. // a cached connection, queue the buffer to send upon connect and
  3830. // lie, saying the data was sent now.
  3831. if (sock.type === 2) {
  3832. if (!dest || dest.socket.readyState !== dest.socket.OPEN) {
  3833. // if we're not connected, open a new connection
  3834. if (!dest || dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  3835. dest = SOCKFS.websocket_sock_ops.createPeer(sock, addr, port);
  3836. }
  3837. dest.dgram_send_queue.push(data);
  3838. return length;
  3839. }
  3840. }
  3841. try {
  3842. // send the actual data
  3843. dest.socket.send(data);
  3844. return length;
  3845. } catch (e) {
  3846. throw new FS.ErrnoError(28);
  3847. }
  3848. },recvmsg:function(sock, length) {
  3849. // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html
  3850. if (sock.type === 1 && sock.server) {
  3851. // tcp servers should not be recv()'ing on the listen socket
  3852. throw new FS.ErrnoError(53);
  3853. }
  3854. var queued = sock.recv_queue.shift();
  3855. if (!queued) {
  3856. if (sock.type === 1) {
  3857. var dest = SOCKFS.websocket_sock_ops.getPeer(sock, sock.daddr, sock.dport);
  3858. if (!dest) {
  3859. // if we have a destination address but are not connected, error out
  3860. throw new FS.ErrnoError(53);
  3861. }
  3862. if (dest.socket.readyState === dest.socket.CLOSING || dest.socket.readyState === dest.socket.CLOSED) {
  3863. // return null if the socket has closed
  3864. return null;
  3865. }
  3866. // else, our socket is in a valid state but truly has nothing available
  3867. throw new FS.ErrnoError(6);
  3868. }
  3869. throw new FS.ErrnoError(6);
  3870. }
  3871. // queued.data will be an ArrayBuffer if it's unadulterated, but if it's
  3872. // requeued TCP data it'll be an ArrayBufferView
  3873. var queuedLength = queued.data.byteLength || queued.data.length;
  3874. var queuedOffset = queued.data.byteOffset || 0;
  3875. var queuedBuffer = queued.data.buffer || queued.data;
  3876. var bytesRead = Math.min(length, queuedLength);
  3877. var res = {
  3878. buffer: new Uint8Array(queuedBuffer, queuedOffset, bytesRead),
  3879. addr: queued.addr,
  3880. port: queued.port
  3881. };
  3882. // push back any unread data for TCP connections
  3883. if (sock.type === 1 && bytesRead < queuedLength) {
  3884. var bytesRemaining = queuedLength - bytesRead;
  3885. queued.data = new Uint8Array(queuedBuffer, queuedOffset + bytesRead, bytesRemaining);
  3886. sock.recv_queue.unshift(queued);
  3887. }
  3888. return res;
  3889. }}};
  3890. function getSocketFromFD(fd) {
  3891. var socket = SOCKFS.getSocket(fd);
  3892. if (!socket) throw new FS.ErrnoError(8);
  3893. return socket;
  3894. }
  3895. function setErrNo(value) {
  3896. HEAP32[((___errno_location())>>2)] = value;
  3897. return value;
  3898. }
  3899. var Sockets = {BUFFER_SIZE:10240,MAX_BUFFER_SIZE:10485760,nextFd:1,fds:{},nextport:1,maxport:65535,peer:null,connections:{},portmap:{},localAddr:4261412874,addrPool:[33554442,50331658,67108874,83886090,100663306,117440522,134217738,150994954,167772170,184549386,201326602,218103818,234881034]};
  3900. function inetNtop4(addr) {
  3901. return (addr & 0xff) + '.' + ((addr >> 8) & 0xff) + '.' + ((addr >> 16) & 0xff) + '.' + ((addr >> 24) & 0xff)
  3902. }
  3903. function inetNtop6(ints) {
  3904. // ref: http://www.ietf.org/rfc/rfc2373.txt - section 2.5.4
  3905. // Format for IPv4 compatible and mapped 128-bit IPv6 Addresses
  3906. // 128-bits are split into eight 16-bit words
  3907. // stored in network byte order (big-endian)
  3908. // | 80 bits | 16 | 32 bits |
  3909. // +-----------------------------------------------------------------+
  3910. // | 10 bytes | 2 | 4 bytes |
  3911. // +--------------------------------------+--------------------------+
  3912. // + 5 words | 1 | 2 words |
  3913. // +--------------------------------------+--------------------------+
  3914. // |0000..............................0000|0000| IPv4 ADDRESS | (compatible)
  3915. // +--------------------------------------+----+---------------------+
  3916. // |0000..............................0000|FFFF| IPv4 ADDRESS | (mapped)
  3917. // +--------------------------------------+----+---------------------+
  3918. var str = "";
  3919. var word = 0;
  3920. var longest = 0;
  3921. var lastzero = 0;
  3922. var zstart = 0;
  3923. var len = 0;
  3924. var i = 0;
  3925. var parts = [
  3926. ints[0] & 0xffff,
  3927. (ints[0] >> 16),
  3928. ints[1] & 0xffff,
  3929. (ints[1] >> 16),
  3930. ints[2] & 0xffff,
  3931. (ints[2] >> 16),
  3932. ints[3] & 0xffff,
  3933. (ints[3] >> 16)
  3934. ];
  3935. // Handle IPv4-compatible, IPv4-mapped, loopback and any/unspecified addresses
  3936. var hasipv4 = true;
  3937. var v4part = "";
  3938. // check if the 10 high-order bytes are all zeros (first 5 words)
  3939. for (i = 0; i < 5; i++) {
  3940. if (parts[i] !== 0) { hasipv4 = false; break; }
  3941. }
  3942. if (hasipv4) {
  3943. // low-order 32-bits store an IPv4 address (bytes 13 to 16) (last 2 words)
  3944. v4part = inetNtop4(parts[6] | (parts[7] << 16));
  3945. // IPv4-mapped IPv6 address if 16-bit value (bytes 11 and 12) == 0xFFFF (6th word)
  3946. if (parts[5] === -1) {
  3947. str = "::ffff:";
  3948. str += v4part;
  3949. return str;
  3950. }
  3951. // IPv4-compatible IPv6 address if 16-bit value (bytes 11 and 12) == 0x0000 (6th word)
  3952. if (parts[5] === 0) {
  3953. str = "::";
  3954. //special case IPv6 addresses
  3955. if (v4part === "0.0.0.0") v4part = ""; // any/unspecified address
  3956. if (v4part === "0.0.0.1") v4part = "1";// loopback address
  3957. str += v4part;
  3958. return str;
  3959. }
  3960. }
  3961. // Handle all other IPv6 addresses
  3962. // first run to find the longest contiguous zero words
  3963. for (word = 0; word < 8; word++) {
  3964. if (parts[word] === 0) {
  3965. if (word - lastzero > 1) {
  3966. len = 0;
  3967. }
  3968. lastzero = word;
  3969. len++;
  3970. }
  3971. if (len > longest) {
  3972. longest = len;
  3973. zstart = word - longest + 1;
  3974. }
  3975. }
  3976. for (word = 0; word < 8; word++) {
  3977. if (longest > 1) {
  3978. // compress contiguous zeros - to produce "::"
  3979. if (parts[word] === 0 && word >= zstart && word < (zstart + longest) ) {
  3980. if (word === zstart) {
  3981. str += ":";
  3982. if (zstart === 0) str += ":"; //leading zeros case
  3983. }
  3984. continue;
  3985. }
  3986. }
  3987. // converts 16-bit words from big-endian to little-endian before converting to hex string
  3988. str += Number(_ntohs(parts[word] & 0xffff)).toString(16);
  3989. str += word < 7 ? ":" : "";
  3990. }
  3991. return str;
  3992. }
  3993. function readSockaddr(sa, salen) {
  3994. // family / port offsets are common to both sockaddr_in and sockaddr_in6
  3995. var family = HEAP16[((sa)>>1)];
  3996. var port = _ntohs(HEAPU16[(((sa)+(2))>>1)]);
  3997. var addr;
  3998. switch (family) {
  3999. case 2:
  4000. if (salen !== 16) {
  4001. return { errno: 28 };
  4002. }
  4003. addr = HEAP32[(((sa)+(4))>>2)];
  4004. addr = inetNtop4(addr);
  4005. break;
  4006. case 10:
  4007. if (salen !== 28) {
  4008. return { errno: 28 };
  4009. }
  4010. addr = [
  4011. HEAP32[(((sa)+(8))>>2)],
  4012. HEAP32[(((sa)+(12))>>2)],
  4013. HEAP32[(((sa)+(16))>>2)],
  4014. HEAP32[(((sa)+(20))>>2)]
  4015. ];
  4016. addr = inetNtop6(addr);
  4017. break;
  4018. default:
  4019. return { errno: 5 };
  4020. }
  4021. return { family: family, addr: addr, port: port };
  4022. }
  4023. function inetPton4(str) {
  4024. var b = str.split('.');
  4025. for (var i = 0; i < 4; i++) {
  4026. var tmp = Number(b[i]);
  4027. if (isNaN(tmp)) return null;
  4028. b[i] = tmp;
  4029. }
  4030. return (b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0;
  4031. }
  4032. /** @suppress {checkTypes} */
  4033. function jstoi_q(str) {
  4034. return parseInt(str);
  4035. }
  4036. function inetPton6(str) {
  4037. var words;
  4038. var w, offset, z, i;
  4039. /* http://home.deds.nl/~aeron/regex/ */
  4040. var valid6regx = /^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i
  4041. var parts = [];
  4042. if (!valid6regx.test(str)) {
  4043. return null;
  4044. }
  4045. if (str === "::") {
  4046. return [0, 0, 0, 0, 0, 0, 0, 0];
  4047. }
  4048. // Z placeholder to keep track of zeros when splitting the string on ":"
  4049. if (str.startsWith("::")) {
  4050. str = str.replace("::", "Z:"); // leading zeros case
  4051. } else {
  4052. str = str.replace("::", ":Z:");
  4053. }
  4054. if (str.indexOf(".") > 0) {
  4055. // parse IPv4 embedded stress
  4056. str = str.replace(new RegExp('[.]', 'g'), ":");
  4057. words = str.split(":");
  4058. words[words.length-4] = jstoi_q(words[words.length-4]) + jstoi_q(words[words.length-3])*256;
  4059. words[words.length-3] = jstoi_q(words[words.length-2]) + jstoi_q(words[words.length-1])*256;
  4060. words = words.slice(0, words.length-2);
  4061. } else {
  4062. words = str.split(":");
  4063. }
  4064. offset = 0; z = 0;
  4065. for (w=0; w < words.length; w++) {
  4066. if (typeof words[w] == 'string') {
  4067. if (words[w] === 'Z') {
  4068. // compressed zeros - write appropriate number of zero words
  4069. for (z = 0; z < (8 - words.length+1); z++) {
  4070. parts[w+z] = 0;
  4071. }
  4072. offset = z-1;
  4073. } else {
  4074. // parse hex to field to 16-bit value and write it in network byte-order
  4075. parts[w+offset] = _htons(parseInt(words[w],16));
  4076. }
  4077. } else {
  4078. // parsed IPv4 words
  4079. parts[w+offset] = words[w];
  4080. }
  4081. }
  4082. return [
  4083. (parts[1] << 16) | parts[0],
  4084. (parts[3] << 16) | parts[2],
  4085. (parts[5] << 16) | parts[4],
  4086. (parts[7] << 16) | parts[6]
  4087. ];
  4088. }
  4089. var DNS = {address_map:{id:1,addrs:{},names:{}},lookup_name:function (name) {
  4090. // If the name is already a valid ipv4 / ipv6 address, don't generate a fake one.
  4091. var res = inetPton4(name);
  4092. if (res !== null) {
  4093. return name;
  4094. }
  4095. res = inetPton6(name);
  4096. if (res !== null) {
  4097. return name;
  4098. }
  4099. // See if this name is already mapped.
  4100. var addr;
  4101. if (DNS.address_map.addrs[name]) {
  4102. addr = DNS.address_map.addrs[name];
  4103. } else {
  4104. var id = DNS.address_map.id++;
  4105. assert(id < 65535, 'exceeded max address mappings of 65535');
  4106. addr = '172.29.' + (id & 0xff) + '.' + (id & 0xff00);
  4107. DNS.address_map.names[addr] = name;
  4108. DNS.address_map.addrs[name] = addr;
  4109. }
  4110. return addr;
  4111. },lookup_addr:function (addr) {
  4112. if (DNS.address_map.names[addr]) {
  4113. return DNS.address_map.names[addr];
  4114. }
  4115. return null;
  4116. }};
  4117. /** @param {boolean=} allowNull */
  4118. function getSocketAddress(addrp, addrlen, allowNull) {
  4119. if (allowNull && addrp === 0) return null;
  4120. var info = readSockaddr(addrp, addrlen);
  4121. if (info.errno) throw new FS.ErrnoError(info.errno);
  4122. info.addr = DNS.lookup_addr(info.addr) || info.addr;
  4123. return info;
  4124. }
  4125. var SYSCALLS = {DEFAULT_POLLMASK:5,calculateAt:function(dirfd, path, allowEmpty) {
  4126. if (PATH.isAbs(path)) {
  4127. return path;
  4128. }
  4129. // relative path
  4130. var dir;
  4131. if (dirfd === -100) {
  4132. dir = FS.cwd();
  4133. } else {
  4134. var dirstream = SYSCALLS.getStreamFromFD(dirfd);
  4135. dir = dirstream.path;
  4136. }
  4137. if (path.length == 0) {
  4138. if (!allowEmpty) {
  4139. throw new FS.ErrnoError(44);;
  4140. }
  4141. return dir;
  4142. }
  4143. return PATH.join2(dir, path);
  4144. },doStat:function(func, path, buf) {
  4145. try {
  4146. var stat = func(path);
  4147. } catch (e) {
  4148. if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
  4149. // an error occurred while trying to look up the path; we should just report ENOTDIR
  4150. return -54;
  4151. }
  4152. throw e;
  4153. }
  4154. HEAP32[((buf)>>2)] = stat.dev;
  4155. HEAP32[(((buf)+(8))>>2)] = stat.ino;
  4156. HEAP32[(((buf)+(12))>>2)] = stat.mode;
  4157. HEAPU32[(((buf)+(16))>>2)] = stat.nlink;
  4158. HEAP32[(((buf)+(20))>>2)] = stat.uid;
  4159. HEAP32[(((buf)+(24))>>2)] = stat.gid;
  4160. HEAP32[(((buf)+(28))>>2)] = stat.rdev;
  4161. (tempI64 = [stat.size>>>0,(tempDouble=stat.size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(40))>>2)] = tempI64[0],HEAP32[(((buf)+(44))>>2)] = tempI64[1]);
  4162. HEAP32[(((buf)+(48))>>2)] = 4096;
  4163. HEAP32[(((buf)+(52))>>2)] = stat.blocks;
  4164. var atime = stat.atime.getTime();
  4165. var mtime = stat.mtime.getTime();
  4166. var ctime = stat.ctime.getTime();
  4167. (tempI64 = [Math.floor(atime / 1000)>>>0,(tempDouble=Math.floor(atime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(56))>>2)] = tempI64[0],HEAP32[(((buf)+(60))>>2)] = tempI64[1]);
  4168. HEAPU32[(((buf)+(64))>>2)] = (atime % 1000) * 1000;
  4169. (tempI64 = [Math.floor(mtime / 1000)>>>0,(tempDouble=Math.floor(mtime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(72))>>2)] = tempI64[0],HEAP32[(((buf)+(76))>>2)] = tempI64[1]);
  4170. HEAPU32[(((buf)+(80))>>2)] = (mtime % 1000) * 1000;
  4171. (tempI64 = [Math.floor(ctime / 1000)>>>0,(tempDouble=Math.floor(ctime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(88))>>2)] = tempI64[0],HEAP32[(((buf)+(92))>>2)] = tempI64[1]);
  4172. HEAPU32[(((buf)+(96))>>2)] = (ctime % 1000) * 1000;
  4173. (tempI64 = [stat.ino>>>0,(tempDouble=stat.ino,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(104))>>2)] = tempI64[0],HEAP32[(((buf)+(108))>>2)] = tempI64[1]);
  4174. return 0;
  4175. },doMsync:function(addr, stream, len, flags, offset) {
  4176. if (!FS.isFile(stream.node.mode)) {
  4177. throw new FS.ErrnoError(43);
  4178. }
  4179. if (flags & 2) {
  4180. // MAP_PRIVATE calls need not to be synced back to underlying fs
  4181. return 0;
  4182. }
  4183. var buffer = HEAPU8.slice(addr, addr + len);
  4184. FS.msync(stream, buffer, offset, len, flags);
  4185. },varargs:undefined,get:function() {
  4186. assert(SYSCALLS.varargs != undefined);
  4187. SYSCALLS.varargs += 4;
  4188. var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
  4189. return ret;
  4190. },getStr:function(ptr) {
  4191. var ret = UTF8ToString(ptr);
  4192. return ret;
  4193. },getStreamFromFD:function(fd) {
  4194. var stream = FS.getStream(fd);
  4195. if (!stream) throw new FS.ErrnoError(8);
  4196. return stream;
  4197. }};
  4198. function ___syscall_connect(fd, addr, addrlen) {
  4199. try {
  4200. var sock = getSocketFromFD(fd);
  4201. var info = getSocketAddress(addr, addrlen);
  4202. sock.sock_ops.connect(sock, info.addr, info.port);
  4203. return 0;
  4204. } catch (e) {
  4205. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4206. return -e.errno;
  4207. }
  4208. }
  4209. function ___syscall_faccessat(dirfd, path, amode, flags) {
  4210. try {
  4211. path = SYSCALLS.getStr(path);
  4212. assert(flags === 0);
  4213. path = SYSCALLS.calculateAt(dirfd, path);
  4214. if (amode & ~7) {
  4215. // need a valid mode
  4216. return -28;
  4217. }
  4218. var lookup = FS.lookupPath(path, { follow: true });
  4219. var node = lookup.node;
  4220. if (!node) {
  4221. return -44;
  4222. }
  4223. var perms = '';
  4224. if (amode & 4) perms += 'r';
  4225. if (amode & 2) perms += 'w';
  4226. if (amode & 1) perms += 'x';
  4227. if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
  4228. return -2;
  4229. }
  4230. return 0;
  4231. } catch (e) {
  4232. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4233. return -e.errno;
  4234. }
  4235. }
  4236. function ___syscall_fcntl64(fd, cmd, varargs) {
  4237. SYSCALLS.varargs = varargs;
  4238. try {
  4239. var stream = SYSCALLS.getStreamFromFD(fd);
  4240. switch (cmd) {
  4241. case 0: {
  4242. var arg = SYSCALLS.get();
  4243. if (arg < 0) {
  4244. return -28;
  4245. }
  4246. var newStream;
  4247. newStream = FS.createStream(stream, arg);
  4248. return newStream.fd;
  4249. }
  4250. case 1:
  4251. case 2:
  4252. return 0; // FD_CLOEXEC makes no sense for a single process.
  4253. case 3:
  4254. return stream.flags;
  4255. case 4: {
  4256. var arg = SYSCALLS.get();
  4257. stream.flags |= arg;
  4258. return 0;
  4259. }
  4260. case 5:
  4261. /* case 5: Currently in musl F_GETLK64 has same value as F_GETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */ {
  4262. var arg = SYSCALLS.get();
  4263. var offset = 0;
  4264. // We're always unlocked.
  4265. HEAP16[(((arg)+(offset))>>1)] = 2;
  4266. return 0;
  4267. }
  4268. case 6:
  4269. case 7:
  4270. /* case 6: Currently in musl F_SETLK64 has same value as F_SETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */
  4271. /* case 7: Currently in musl F_SETLKW64 has same value as F_SETLKW, so omitted to avoid duplicate case blocks. If that changes, uncomment this */
  4272. return 0; // Pretend that the locking is successful.
  4273. case 16:
  4274. case 8:
  4275. return -28; // These are for sockets. We don't have them fully implemented yet.
  4276. case 9:
  4277. // musl trusts getown return values, due to a bug where they must be, as they overlap with errors. just return -1 here, so fcntl() returns that, and we set errno ourselves.
  4278. setErrNo(28);
  4279. return -1;
  4280. default: {
  4281. return -28;
  4282. }
  4283. }
  4284. } catch (e) {
  4285. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4286. return -e.errno;
  4287. }
  4288. }
  4289. function ___syscall_fstat64(fd, buf) {
  4290. try {
  4291. var stream = SYSCALLS.getStreamFromFD(fd);
  4292. return SYSCALLS.doStat(FS.stat, stream.path, buf);
  4293. } catch (e) {
  4294. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4295. return -e.errno;
  4296. }
  4297. }
  4298. function convertI32PairToI53Checked(lo, hi) {
  4299. assert(lo == (lo >>> 0) || lo == (lo|0)); // lo should either be a i32 or a u32
  4300. assert(hi === (hi|0)); // hi should be a i32
  4301. return ((hi + 0x200000) >>> 0 < 0x400001 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;
  4302. }
  4303. function ___syscall_ftruncate64(fd, length_low, length_high) {
  4304. try {
  4305. var length = convertI32PairToI53Checked(length_low, length_high); if (isNaN(length)) return -61;
  4306. FS.ftruncate(fd, length);
  4307. return 0;
  4308. } catch (e) {
  4309. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4310. return -e.errno;
  4311. }
  4312. }
  4313. function ___syscall_ioctl(fd, op, varargs) {
  4314. SYSCALLS.varargs = varargs;
  4315. try {
  4316. var stream = SYSCALLS.getStreamFromFD(fd);
  4317. switch (op) {
  4318. case 21509:
  4319. case 21505: {
  4320. if (!stream.tty) return -59;
  4321. return 0;
  4322. }
  4323. case 21510:
  4324. case 21511:
  4325. case 21512:
  4326. case 21506:
  4327. case 21507:
  4328. case 21508: {
  4329. if (!stream.tty) return -59;
  4330. return 0; // no-op, not actually adjusting terminal settings
  4331. }
  4332. case 21519: {
  4333. if (!stream.tty) return -59;
  4334. var argp = SYSCALLS.get();
  4335. HEAP32[((argp)>>2)] = 0;
  4336. return 0;
  4337. }
  4338. case 21520: {
  4339. if (!stream.tty) return -59;
  4340. return -28; // not supported
  4341. }
  4342. case 21531: {
  4343. var argp = SYSCALLS.get();
  4344. return FS.ioctl(stream, op, argp);
  4345. }
  4346. case 21523: {
  4347. // TODO: in theory we should write to the winsize struct that gets
  4348. // passed in, but for now musl doesn't read anything on it
  4349. if (!stream.tty) return -59;
  4350. return 0;
  4351. }
  4352. case 21524: {
  4353. // TODO: technically, this ioctl call should change the window size.
  4354. // but, since emscripten doesn't have any concept of a terminal window
  4355. // yet, we'll just silently throw it away as we do TIOCGWINSZ
  4356. if (!stream.tty) return -59;
  4357. return 0;
  4358. }
  4359. default: return -28; // not supported
  4360. }
  4361. } catch (e) {
  4362. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4363. return -e.errno;
  4364. }
  4365. }
  4366. function ___syscall_lstat64(path, buf) {
  4367. try {
  4368. path = SYSCALLS.getStr(path);
  4369. return SYSCALLS.doStat(FS.lstat, path, buf);
  4370. } catch (e) {
  4371. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4372. return -e.errno;
  4373. }
  4374. }
  4375. function ___syscall_newfstatat(dirfd, path, buf, flags) {
  4376. try {
  4377. path = SYSCALLS.getStr(path);
  4378. var nofollow = flags & 256;
  4379. var allowEmpty = flags & 4096;
  4380. flags = flags & (~6400);
  4381. assert(!flags, 'unknown flags in __syscall_newfstatat: ' + flags);
  4382. path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
  4383. return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf);
  4384. } catch (e) {
  4385. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4386. return -e.errno;
  4387. }
  4388. }
  4389. function ___syscall_openat(dirfd, path, flags, varargs) {
  4390. SYSCALLS.varargs = varargs;
  4391. try {
  4392. path = SYSCALLS.getStr(path);
  4393. path = SYSCALLS.calculateAt(dirfd, path);
  4394. var mode = varargs ? SYSCALLS.get() : 0;
  4395. return FS.open(path, flags, mode).fd;
  4396. } catch (e) {
  4397. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4398. return -e.errno;
  4399. }
  4400. }
  4401. function ___syscall_socket(domain, type, protocol) {
  4402. try {
  4403. var sock = SOCKFS.createSocket(domain, type, protocol);
  4404. assert(sock.stream.fd < 64); // XXX ? select() assumes socket fd values are in 0..63
  4405. return sock.stream.fd;
  4406. } catch (e) {
  4407. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4408. return -e.errno;
  4409. }
  4410. }
  4411. function ___syscall_stat64(path, buf) {
  4412. try {
  4413. path = SYSCALLS.getStr(path);
  4414. return SYSCALLS.doStat(FS.stat, path, buf);
  4415. } catch (e) {
  4416. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  4417. return -e.errno;
  4418. }
  4419. }
  4420. var tupleRegistrations = {};
  4421. function runDestructors(destructors) {
  4422. while (destructors.length) {
  4423. var ptr = destructors.pop();
  4424. var del = destructors.pop();
  4425. del(ptr);
  4426. }
  4427. }
  4428. function simpleReadValueFromPointer(pointer) {
  4429. return this['fromWireType'](HEAP32[((pointer)>>2)]);
  4430. }
  4431. var awaitingDependencies = {};
  4432. var registeredTypes = {};
  4433. var typeDependencies = {};
  4434. var char_0 = 48;
  4435. var char_9 = 57;
  4436. function makeLegalFunctionName(name) {
  4437. if (undefined === name) {
  4438. return '_unknown';
  4439. }
  4440. name = name.replace(/[^a-zA-Z0-9_]/g, '$');
  4441. var f = name.charCodeAt(0);
  4442. if (f >= char_0 && f <= char_9) {
  4443. return '_' + name;
  4444. }
  4445. return name;
  4446. }
  4447. function createNamedFunction(name, body) {
  4448. name = makeLegalFunctionName(name);
  4449. /*jshint evil:true*/
  4450. return new Function(
  4451. "body",
  4452. "return function " + name + "() {\n" +
  4453. " \"use strict\";" +
  4454. " return body.apply(this, arguments);\n" +
  4455. "};\n"
  4456. )(body);
  4457. }
  4458. function extendError(baseErrorType, errorName) {
  4459. var errorClass = createNamedFunction(errorName, function(message) {
  4460. this.name = errorName;
  4461. this.message = message;
  4462. var stack = (new Error(message)).stack;
  4463. if (stack !== undefined) {
  4464. this.stack = this.toString() + '\n' +
  4465. stack.replace(/^Error(:[^\n]*)?\n/, '');
  4466. }
  4467. });
  4468. errorClass.prototype = Object.create(baseErrorType.prototype);
  4469. errorClass.prototype.constructor = errorClass;
  4470. errorClass.prototype.toString = function() {
  4471. if (this.message === undefined) {
  4472. return this.name;
  4473. } else {
  4474. return this.name + ': ' + this.message;
  4475. }
  4476. };
  4477. return errorClass;
  4478. }
  4479. var InternalError = undefined;
  4480. function throwInternalError(message) {
  4481. throw new InternalError(message);
  4482. }
  4483. function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) {
  4484. myTypes.forEach(function(type) {
  4485. typeDependencies[type] = dependentTypes;
  4486. });
  4487. function onComplete(typeConverters) {
  4488. var myTypeConverters = getTypeConverters(typeConverters);
  4489. if (myTypeConverters.length !== myTypes.length) {
  4490. throwInternalError('Mismatched type converter count');
  4491. }
  4492. for (var i = 0; i < myTypes.length; ++i) {
  4493. registerType(myTypes[i], myTypeConverters[i]);
  4494. }
  4495. }
  4496. var typeConverters = new Array(dependentTypes.length);
  4497. var unregisteredTypes = [];
  4498. var registered = 0;
  4499. dependentTypes.forEach((dt, i) => {
  4500. if (registeredTypes.hasOwnProperty(dt)) {
  4501. typeConverters[i] = registeredTypes[dt];
  4502. } else {
  4503. unregisteredTypes.push(dt);
  4504. if (!awaitingDependencies.hasOwnProperty(dt)) {
  4505. awaitingDependencies[dt] = [];
  4506. }
  4507. awaitingDependencies[dt].push(() => {
  4508. typeConverters[i] = registeredTypes[dt];
  4509. ++registered;
  4510. if (registered === unregisteredTypes.length) {
  4511. onComplete(typeConverters);
  4512. }
  4513. });
  4514. }
  4515. });
  4516. if (0 === unregisteredTypes.length) {
  4517. onComplete(typeConverters);
  4518. }
  4519. }
  4520. function __embind_finalize_value_array(rawTupleType) {
  4521. var reg = tupleRegistrations[rawTupleType];
  4522. delete tupleRegistrations[rawTupleType];
  4523. var elements = reg.elements;
  4524. var elementsLength = elements.length;
  4525. var elementTypes = elements.map(function(elt) { return elt.getterReturnType; }).
  4526. concat(elements.map(function(elt) { return elt.setterArgumentType; }));
  4527. var rawConstructor = reg.rawConstructor;
  4528. var rawDestructor = reg.rawDestructor;
  4529. whenDependentTypesAreResolved([rawTupleType], elementTypes, function(elementTypes) {
  4530. elements.forEach((elt, i) => {
  4531. var getterReturnType = elementTypes[i];
  4532. var getter = elt.getter;
  4533. var getterContext = elt.getterContext;
  4534. var setterArgumentType = elementTypes[i + elementsLength];
  4535. var setter = elt.setter;
  4536. var setterContext = elt.setterContext;
  4537. elt.read = (ptr) => {
  4538. return getterReturnType['fromWireType'](getter(getterContext, ptr));
  4539. };
  4540. elt.write = (ptr, o) => {
  4541. var destructors = [];
  4542. setter(setterContext, ptr, setterArgumentType['toWireType'](destructors, o));
  4543. runDestructors(destructors);
  4544. };
  4545. });
  4546. return [{
  4547. name: reg.name,
  4548. 'fromWireType': function(ptr) {
  4549. var rv = new Array(elementsLength);
  4550. for (var i = 0; i < elementsLength; ++i) {
  4551. rv[i] = elements[i].read(ptr);
  4552. }
  4553. rawDestructor(ptr);
  4554. return rv;
  4555. },
  4556. 'toWireType': function(destructors, o) {
  4557. if (elementsLength !== o.length) {
  4558. throw new TypeError("Incorrect number of tuple elements for " + reg.name + ": expected=" + elementsLength + ", actual=" + o.length);
  4559. }
  4560. var ptr = rawConstructor();
  4561. for (var i = 0; i < elementsLength; ++i) {
  4562. elements[i].write(ptr, o[i]);
  4563. }
  4564. if (destructors !== null) {
  4565. destructors.push(rawDestructor, ptr);
  4566. }
  4567. return ptr;
  4568. },
  4569. 'argPackAdvance': 8,
  4570. 'readValueFromPointer': simpleReadValueFromPointer,
  4571. destructorFunction: rawDestructor,
  4572. }];
  4573. });
  4574. }
  4575. var structRegistrations = {};
  4576. function __embind_finalize_value_object(structType) {
  4577. var reg = structRegistrations[structType];
  4578. delete structRegistrations[structType];
  4579. var rawConstructor = reg.rawConstructor;
  4580. var rawDestructor = reg.rawDestructor;
  4581. var fieldRecords = reg.fields;
  4582. var fieldTypes = fieldRecords.map((field) => field.getterReturnType).
  4583. concat(fieldRecords.map((field) => field.setterArgumentType));
  4584. whenDependentTypesAreResolved([structType], fieldTypes, (fieldTypes) => {
  4585. var fields = {};
  4586. fieldRecords.forEach((field, i) => {
  4587. var fieldName = field.fieldName;
  4588. var getterReturnType = fieldTypes[i];
  4589. var getter = field.getter;
  4590. var getterContext = field.getterContext;
  4591. var setterArgumentType = fieldTypes[i + fieldRecords.length];
  4592. var setter = field.setter;
  4593. var setterContext = field.setterContext;
  4594. fields[fieldName] = {
  4595. read: (ptr) => {
  4596. return getterReturnType['fromWireType'](
  4597. getter(getterContext, ptr));
  4598. },
  4599. write: (ptr, o) => {
  4600. var destructors = [];
  4601. setter(setterContext, ptr, setterArgumentType['toWireType'](destructors, o));
  4602. runDestructors(destructors);
  4603. }
  4604. };
  4605. });
  4606. return [{
  4607. name: reg.name,
  4608. 'fromWireType': function(ptr) {
  4609. var rv = {};
  4610. for (var i in fields) {
  4611. rv[i] = fields[i].read(ptr);
  4612. }
  4613. rawDestructor(ptr);
  4614. return rv;
  4615. },
  4616. 'toWireType': function(destructors, o) {
  4617. // todo: Here we have an opportunity for -O3 level "unsafe" optimizations:
  4618. // assume all fields are present without checking.
  4619. for (var fieldName in fields) {
  4620. if (!(fieldName in o)) {
  4621. throw new TypeError('Missing field: "' + fieldName + '"');
  4622. }
  4623. }
  4624. var ptr = rawConstructor();
  4625. for (fieldName in fields) {
  4626. fields[fieldName].write(ptr, o[fieldName]);
  4627. }
  4628. if (destructors !== null) {
  4629. destructors.push(rawDestructor, ptr);
  4630. }
  4631. return ptr;
  4632. },
  4633. 'argPackAdvance': 8,
  4634. 'readValueFromPointer': simpleReadValueFromPointer,
  4635. destructorFunction: rawDestructor,
  4636. }];
  4637. });
  4638. }
  4639. function __embind_register_bigint(primitiveType, name, size, minRange, maxRange) {}
  4640. function getShiftFromSize(size) {
  4641. switch (size) {
  4642. case 1: return 0;
  4643. case 2: return 1;
  4644. case 4: return 2;
  4645. case 8: return 3;
  4646. default:
  4647. throw new TypeError('Unknown type size: ' + size);
  4648. }
  4649. }
  4650. function embind_init_charCodes() {
  4651. var codes = new Array(256);
  4652. for (var i = 0; i < 256; ++i) {
  4653. codes[i] = String.fromCharCode(i);
  4654. }
  4655. embind_charCodes = codes;
  4656. }
  4657. var embind_charCodes = undefined;
  4658. function readLatin1String(ptr) {
  4659. var ret = "";
  4660. var c = ptr;
  4661. while (HEAPU8[c]) {
  4662. ret += embind_charCodes[HEAPU8[c++]];
  4663. }
  4664. return ret;
  4665. }
  4666. var BindingError = undefined;
  4667. function throwBindingError(message) {
  4668. throw new BindingError(message);
  4669. }
  4670. /** @param {Object=} options */
  4671. function registerType(rawType, registeredInstance, options = {}) {
  4672. if (!('argPackAdvance' in registeredInstance)) {
  4673. throw new TypeError('registerType registeredInstance requires argPackAdvance');
  4674. }
  4675. var name = registeredInstance.name;
  4676. if (!rawType) {
  4677. throwBindingError('type "' + name + '" must have a positive integer typeid pointer');
  4678. }
  4679. if (registeredTypes.hasOwnProperty(rawType)) {
  4680. if (options.ignoreDuplicateRegistrations) {
  4681. return;
  4682. } else {
  4683. throwBindingError("Cannot register type '" + name + "' twice");
  4684. }
  4685. }
  4686. registeredTypes[rawType] = registeredInstance;
  4687. delete typeDependencies[rawType];
  4688. if (awaitingDependencies.hasOwnProperty(rawType)) {
  4689. var callbacks = awaitingDependencies[rawType];
  4690. delete awaitingDependencies[rawType];
  4691. callbacks.forEach((cb) => cb());
  4692. }
  4693. }
  4694. function __embind_register_bool(rawType, name, size, trueValue, falseValue) {
  4695. var shift = getShiftFromSize(size);
  4696. name = readLatin1String(name);
  4697. registerType(rawType, {
  4698. name: name,
  4699. 'fromWireType': function(wt) {
  4700. // ambiguous emscripten ABI: sometimes return values are
  4701. // true or false, and sometimes integers (0 or 1)
  4702. return !!wt;
  4703. },
  4704. 'toWireType': function(destructors, o) {
  4705. return o ? trueValue : falseValue;
  4706. },
  4707. 'argPackAdvance': 8,
  4708. 'readValueFromPointer': function(pointer) {
  4709. // TODO: if heap is fixed (like in asm.js) this could be executed outside
  4710. var heap;
  4711. if (size === 1) {
  4712. heap = HEAP8;
  4713. } else if (size === 2) {
  4714. heap = HEAP16;
  4715. } else if (size === 4) {
  4716. heap = HEAP32;
  4717. } else {
  4718. throw new TypeError("Unknown boolean type size: " + name);
  4719. }
  4720. return this['fromWireType'](heap[pointer >> shift]);
  4721. },
  4722. destructorFunction: null, // This type does not need a destructor
  4723. });
  4724. }
  4725. function ClassHandle_isAliasOf(other) {
  4726. if (!(this instanceof ClassHandle)) {
  4727. return false;
  4728. }
  4729. if (!(other instanceof ClassHandle)) {
  4730. return false;
  4731. }
  4732. var leftClass = this.$$.ptrType.registeredClass;
  4733. var left = this.$$.ptr;
  4734. var rightClass = other.$$.ptrType.registeredClass;
  4735. var right = other.$$.ptr;
  4736. while (leftClass.baseClass) {
  4737. left = leftClass.upcast(left);
  4738. leftClass = leftClass.baseClass;
  4739. }
  4740. while (rightClass.baseClass) {
  4741. right = rightClass.upcast(right);
  4742. rightClass = rightClass.baseClass;
  4743. }
  4744. return leftClass === rightClass && left === right;
  4745. }
  4746. function shallowCopyInternalPointer(o) {
  4747. return {
  4748. count: o.count,
  4749. deleteScheduled: o.deleteScheduled,
  4750. preservePointerOnDelete: o.preservePointerOnDelete,
  4751. ptr: o.ptr,
  4752. ptrType: o.ptrType,
  4753. smartPtr: o.smartPtr,
  4754. smartPtrType: o.smartPtrType,
  4755. };
  4756. }
  4757. function throwInstanceAlreadyDeleted(obj) {
  4758. function getInstanceTypeName(handle) {
  4759. return handle.$$.ptrType.registeredClass.name;
  4760. }
  4761. throwBindingError(getInstanceTypeName(obj) + ' instance already deleted');
  4762. }
  4763. var finalizationRegistry = false;
  4764. function detachFinalizer(handle) {}
  4765. function runDestructor($$) {
  4766. if ($$.smartPtr) {
  4767. $$.smartPtrType.rawDestructor($$.smartPtr);
  4768. } else {
  4769. $$.ptrType.registeredClass.rawDestructor($$.ptr);
  4770. }
  4771. }
  4772. function releaseClassHandle($$) {
  4773. $$.count.value -= 1;
  4774. var toDelete = 0 === $$.count.value;
  4775. if (toDelete) {
  4776. runDestructor($$);
  4777. }
  4778. }
  4779. function downcastPointer(ptr, ptrClass, desiredClass) {
  4780. if (ptrClass === desiredClass) {
  4781. return ptr;
  4782. }
  4783. if (undefined === desiredClass.baseClass) {
  4784. return null; // no conversion
  4785. }
  4786. var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass);
  4787. if (rv === null) {
  4788. return null;
  4789. }
  4790. return desiredClass.downcast(rv);
  4791. }
  4792. var registeredPointers = {};
  4793. function getInheritedInstanceCount() {
  4794. return Object.keys(registeredInstances).length;
  4795. }
  4796. function getLiveInheritedInstances() {
  4797. var rv = [];
  4798. for (var k in registeredInstances) {
  4799. if (registeredInstances.hasOwnProperty(k)) {
  4800. rv.push(registeredInstances[k]);
  4801. }
  4802. }
  4803. return rv;
  4804. }
  4805. var deletionQueue = [];
  4806. function flushPendingDeletes() {
  4807. while (deletionQueue.length) {
  4808. var obj = deletionQueue.pop();
  4809. obj.$$.deleteScheduled = false;
  4810. obj['delete']();
  4811. }
  4812. }
  4813. var delayFunction = undefined;
  4814. function setDelayFunction(fn) {
  4815. delayFunction = fn;
  4816. if (deletionQueue.length && delayFunction) {
  4817. delayFunction(flushPendingDeletes);
  4818. }
  4819. }
  4820. function init_embind() {
  4821. Module['getInheritedInstanceCount'] = getInheritedInstanceCount;
  4822. Module['getLiveInheritedInstances'] = getLiveInheritedInstances;
  4823. Module['flushPendingDeletes'] = flushPendingDeletes;
  4824. Module['setDelayFunction'] = setDelayFunction;
  4825. }
  4826. var registeredInstances = {};
  4827. function getBasestPointer(class_, ptr) {
  4828. if (ptr === undefined) {
  4829. throwBindingError('ptr should not be undefined');
  4830. }
  4831. while (class_.baseClass) {
  4832. ptr = class_.upcast(ptr);
  4833. class_ = class_.baseClass;
  4834. }
  4835. return ptr;
  4836. }
  4837. function getInheritedInstance(class_, ptr) {
  4838. ptr = getBasestPointer(class_, ptr);
  4839. return registeredInstances[ptr];
  4840. }
  4841. function makeClassHandle(prototype, record) {
  4842. if (!record.ptrType || !record.ptr) {
  4843. throwInternalError('makeClassHandle requires ptr and ptrType');
  4844. }
  4845. var hasSmartPtrType = !!record.smartPtrType;
  4846. var hasSmartPtr = !!record.smartPtr;
  4847. if (hasSmartPtrType !== hasSmartPtr) {
  4848. throwInternalError('Both smartPtrType and smartPtr must be specified');
  4849. }
  4850. record.count = { value: 1 };
  4851. return attachFinalizer(Object.create(prototype, {
  4852. $$: {
  4853. value: record,
  4854. },
  4855. }));
  4856. }
  4857. function RegisteredPointer_fromWireType(ptr) {
  4858. // ptr is a raw pointer (or a raw smartpointer)
  4859. // rawPointer is a maybe-null raw pointer
  4860. var rawPointer = this.getPointee(ptr);
  4861. if (!rawPointer) {
  4862. this.destructor(ptr);
  4863. return null;
  4864. }
  4865. var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer);
  4866. if (undefined !== registeredInstance) {
  4867. // JS object has been neutered, time to repopulate it
  4868. if (0 === registeredInstance.$$.count.value) {
  4869. registeredInstance.$$.ptr = rawPointer;
  4870. registeredInstance.$$.smartPtr = ptr;
  4871. return registeredInstance['clone']();
  4872. } else {
  4873. // else, just increment reference count on existing object
  4874. // it already has a reference to the smart pointer
  4875. var rv = registeredInstance['clone']();
  4876. this.destructor(ptr);
  4877. return rv;
  4878. }
  4879. }
  4880. function makeDefaultHandle() {
  4881. if (this.isSmartPointer) {
  4882. return makeClassHandle(this.registeredClass.instancePrototype, {
  4883. ptrType: this.pointeeType,
  4884. ptr: rawPointer,
  4885. smartPtrType: this,
  4886. smartPtr: ptr,
  4887. });
  4888. } else {
  4889. return makeClassHandle(this.registeredClass.instancePrototype, {
  4890. ptrType: this,
  4891. ptr: ptr,
  4892. });
  4893. }
  4894. }
  4895. var actualType = this.registeredClass.getActualType(rawPointer);
  4896. var registeredPointerRecord = registeredPointers[actualType];
  4897. if (!registeredPointerRecord) {
  4898. return makeDefaultHandle.call(this);
  4899. }
  4900. var toType;
  4901. if (this.isConst) {
  4902. toType = registeredPointerRecord.constPointerType;
  4903. } else {
  4904. toType = registeredPointerRecord.pointerType;
  4905. }
  4906. var dp = downcastPointer(
  4907. rawPointer,
  4908. this.registeredClass,
  4909. toType.registeredClass);
  4910. if (dp === null) {
  4911. return makeDefaultHandle.call(this);
  4912. }
  4913. if (this.isSmartPointer) {
  4914. return makeClassHandle(toType.registeredClass.instancePrototype, {
  4915. ptrType: toType,
  4916. ptr: dp,
  4917. smartPtrType: this,
  4918. smartPtr: ptr,
  4919. });
  4920. } else {
  4921. return makeClassHandle(toType.registeredClass.instancePrototype, {
  4922. ptrType: toType,
  4923. ptr: dp,
  4924. });
  4925. }
  4926. }
  4927. function attachFinalizer(handle) {
  4928. if ('undefined' === typeof FinalizationRegistry) {
  4929. attachFinalizer = (handle) => handle;
  4930. return handle;
  4931. }
  4932. // If the running environment has a FinalizationRegistry (see
  4933. // https://github.com/tc39/proposal-weakrefs), then attach finalizers
  4934. // for class handles. We check for the presence of FinalizationRegistry
  4935. // at run-time, not build-time.
  4936. finalizationRegistry = new FinalizationRegistry((info) => {
  4937. console.warn(info.leakWarning.stack.replace(/^Error: /, ''));
  4938. releaseClassHandle(info.$$);
  4939. });
  4940. attachFinalizer = (handle) => {
  4941. var $$ = handle.$$;
  4942. var hasSmartPtr = !!$$.smartPtr;
  4943. if (hasSmartPtr) {
  4944. // We should not call the destructor on raw pointers in case other code expects the pointee to live
  4945. var info = { $$: $$ };
  4946. // Create a warning as an Error instance in advance so that we can store
  4947. // the current stacktrace and point to it when / if a leak is detected.
  4948. // This is more useful than the empty stacktrace of `FinalizationRegistry`
  4949. // callback.
  4950. var cls = $$.ptrType.registeredClass;
  4951. info.leakWarning = new Error("Embind found a leaked C++ instance " + cls.name + " <" + ptrToString($$.ptr) + ">.\n" +
  4952. "We'll free it automatically in this case, but this functionality is not reliable across various environments.\n" +
  4953. "Make sure to invoke .delete() manually once you're done with the instance instead.\n" +
  4954. "Originally allocated"); // `.stack` will add "at ..." after this sentence
  4955. if ('captureStackTrace' in Error) {
  4956. Error.captureStackTrace(info.leakWarning, RegisteredPointer_fromWireType);
  4957. }
  4958. finalizationRegistry.register(handle, info, handle);
  4959. }
  4960. return handle;
  4961. };
  4962. detachFinalizer = (handle) => finalizationRegistry.unregister(handle);
  4963. return attachFinalizer(handle);
  4964. }
  4965. function ClassHandle_clone() {
  4966. if (!this.$$.ptr) {
  4967. throwInstanceAlreadyDeleted(this);
  4968. }
  4969. if (this.$$.preservePointerOnDelete) {
  4970. this.$$.count.value += 1;
  4971. return this;
  4972. } else {
  4973. var clone = attachFinalizer(Object.create(Object.getPrototypeOf(this), {
  4974. $$: {
  4975. value: shallowCopyInternalPointer(this.$$),
  4976. }
  4977. }));
  4978. clone.$$.count.value += 1;
  4979. clone.$$.deleteScheduled = false;
  4980. return clone;
  4981. }
  4982. }
  4983. function ClassHandle_delete() {
  4984. if (!this.$$.ptr) {
  4985. throwInstanceAlreadyDeleted(this);
  4986. }
  4987. if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
  4988. throwBindingError('Object already scheduled for deletion');
  4989. }
  4990. detachFinalizer(this);
  4991. releaseClassHandle(this.$$);
  4992. if (!this.$$.preservePointerOnDelete) {
  4993. this.$$.smartPtr = undefined;
  4994. this.$$.ptr = undefined;
  4995. }
  4996. }
  4997. function ClassHandle_isDeleted() {
  4998. return !this.$$.ptr;
  4999. }
  5000. function ClassHandle_deleteLater() {
  5001. if (!this.$$.ptr) {
  5002. throwInstanceAlreadyDeleted(this);
  5003. }
  5004. if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
  5005. throwBindingError('Object already scheduled for deletion');
  5006. }
  5007. deletionQueue.push(this);
  5008. if (deletionQueue.length === 1 && delayFunction) {
  5009. delayFunction(flushPendingDeletes);
  5010. }
  5011. this.$$.deleteScheduled = true;
  5012. return this;
  5013. }
  5014. function init_ClassHandle() {
  5015. ClassHandle.prototype['isAliasOf'] = ClassHandle_isAliasOf;
  5016. ClassHandle.prototype['clone'] = ClassHandle_clone;
  5017. ClassHandle.prototype['delete'] = ClassHandle_delete;
  5018. ClassHandle.prototype['isDeleted'] = ClassHandle_isDeleted;
  5019. ClassHandle.prototype['deleteLater'] = ClassHandle_deleteLater;
  5020. }
  5021. function ClassHandle() {
  5022. }
  5023. function ensureOverloadTable(proto, methodName, humanName) {
  5024. if (undefined === proto[methodName].overloadTable) {
  5025. var prevFunc = proto[methodName];
  5026. // Inject an overload resolver function that routes to the appropriate overload based on the number of arguments.
  5027. proto[methodName] = function() {
  5028. // TODO This check can be removed in -O3 level "unsafe" optimizations.
  5029. if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) {
  5030. throwBindingError("Function '" + humanName + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + proto[methodName].overloadTable + ")!");
  5031. }
  5032. return proto[methodName].overloadTable[arguments.length].apply(this, arguments);
  5033. };
  5034. // Move the previous function into the overload table.
  5035. proto[methodName].overloadTable = [];
  5036. proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
  5037. }
  5038. }
  5039. /** @param {number=} numArguments */
  5040. function exposePublicSymbol(name, value, numArguments) {
  5041. if (Module.hasOwnProperty(name)) {
  5042. if (undefined === numArguments || (undefined !== Module[name].overloadTable && undefined !== Module[name].overloadTable[numArguments])) {
  5043. throwBindingError("Cannot register public name '" + name + "' twice");
  5044. }
  5045. // We are exposing a function with the same name as an existing function. Create an overload table and a function selector
  5046. // that routes between the two.
  5047. ensureOverloadTable(Module, name, name);
  5048. if (Module.hasOwnProperty(numArguments)) {
  5049. throwBindingError("Cannot register multiple overloads of a function with the same number of arguments (" + numArguments + ")!");
  5050. }
  5051. // Add the new function into the overload table.
  5052. Module[name].overloadTable[numArguments] = value;
  5053. }
  5054. else {
  5055. Module[name] = value;
  5056. if (undefined !== numArguments) {
  5057. Module[name].numArguments = numArguments;
  5058. }
  5059. }
  5060. }
  5061. /** @constructor */
  5062. function RegisteredClass(name,
  5063. constructor,
  5064. instancePrototype,
  5065. rawDestructor,
  5066. baseClass,
  5067. getActualType,
  5068. upcast,
  5069. downcast) {
  5070. this.name = name;
  5071. this.constructor = constructor;
  5072. this.instancePrototype = instancePrototype;
  5073. this.rawDestructor = rawDestructor;
  5074. this.baseClass = baseClass;
  5075. this.getActualType = getActualType;
  5076. this.upcast = upcast;
  5077. this.downcast = downcast;
  5078. this.pureVirtualFunctions = [];
  5079. }
  5080. function upcastPointer(ptr, ptrClass, desiredClass) {
  5081. while (ptrClass !== desiredClass) {
  5082. if (!ptrClass.upcast) {
  5083. throwBindingError("Expected null or instance of " + desiredClass.name + ", got an instance of " + ptrClass.name);
  5084. }
  5085. ptr = ptrClass.upcast(ptr);
  5086. ptrClass = ptrClass.baseClass;
  5087. }
  5088. return ptr;
  5089. }
  5090. function constNoSmartPtrRawPointerToWireType(destructors, handle) {
  5091. if (handle === null) {
  5092. if (this.isReference) {
  5093. throwBindingError('null is not a valid ' + this.name);
  5094. }
  5095. return 0;
  5096. }
  5097. if (!handle.$$) {
  5098. throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
  5099. }
  5100. if (!handle.$$.ptr) {
  5101. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  5102. }
  5103. var handleClass = handle.$$.ptrType.registeredClass;
  5104. var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  5105. return ptr;
  5106. }
  5107. function genericPointerToWireType(destructors, handle) {
  5108. var ptr;
  5109. if (handle === null) {
  5110. if (this.isReference) {
  5111. throwBindingError('null is not a valid ' + this.name);
  5112. }
  5113. if (this.isSmartPointer) {
  5114. ptr = this.rawConstructor();
  5115. if (destructors !== null) {
  5116. destructors.push(this.rawDestructor, ptr);
  5117. }
  5118. return ptr;
  5119. } else {
  5120. return 0;
  5121. }
  5122. }
  5123. if (!handle.$$) {
  5124. throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
  5125. }
  5126. if (!handle.$$.ptr) {
  5127. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  5128. }
  5129. if (!this.isConst && handle.$$.ptrType.isConst) {
  5130. throwBindingError('Cannot convert argument of type ' + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + ' to parameter type ' + this.name);
  5131. }
  5132. var handleClass = handle.$$.ptrType.registeredClass;
  5133. ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  5134. if (this.isSmartPointer) {
  5135. // TODO: this is not strictly true
  5136. // We could support BY_EMVAL conversions from raw pointers to smart pointers
  5137. // because the smart pointer can hold a reference to the handle
  5138. if (undefined === handle.$$.smartPtr) {
  5139. throwBindingError('Passing raw pointer to smart pointer is illegal');
  5140. }
  5141. switch (this.sharingPolicy) {
  5142. case 0: // NONE
  5143. // no upcasting
  5144. if (handle.$$.smartPtrType === this) {
  5145. ptr = handle.$$.smartPtr;
  5146. } else {
  5147. throwBindingError('Cannot convert argument of type ' + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + ' to parameter type ' + this.name);
  5148. }
  5149. break;
  5150. case 1: // INTRUSIVE
  5151. ptr = handle.$$.smartPtr;
  5152. break;
  5153. case 2: // BY_EMVAL
  5154. if (handle.$$.smartPtrType === this) {
  5155. ptr = handle.$$.smartPtr;
  5156. } else {
  5157. var clonedHandle = handle['clone']();
  5158. ptr = this.rawShare(
  5159. ptr,
  5160. Emval.toHandle(function() {
  5161. clonedHandle['delete']();
  5162. })
  5163. );
  5164. if (destructors !== null) {
  5165. destructors.push(this.rawDestructor, ptr);
  5166. }
  5167. }
  5168. break;
  5169. default:
  5170. throwBindingError('Unsupporting sharing policy');
  5171. }
  5172. }
  5173. return ptr;
  5174. }
  5175. function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) {
  5176. if (handle === null) {
  5177. if (this.isReference) {
  5178. throwBindingError('null is not a valid ' + this.name);
  5179. }
  5180. return 0;
  5181. }
  5182. if (!handle.$$) {
  5183. throwBindingError('Cannot pass "' + embindRepr(handle) + '" as a ' + this.name);
  5184. }
  5185. if (!handle.$$.ptr) {
  5186. throwBindingError('Cannot pass deleted object as a pointer of type ' + this.name);
  5187. }
  5188. if (handle.$$.ptrType.isConst) {
  5189. throwBindingError('Cannot convert argument of type ' + handle.$$.ptrType.name + ' to parameter type ' + this.name);
  5190. }
  5191. var handleClass = handle.$$.ptrType.registeredClass;
  5192. var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
  5193. return ptr;
  5194. }
  5195. function RegisteredPointer_getPointee(ptr) {
  5196. if (this.rawGetPointee) {
  5197. ptr = this.rawGetPointee(ptr);
  5198. }
  5199. return ptr;
  5200. }
  5201. function RegisteredPointer_destructor(ptr) {
  5202. if (this.rawDestructor) {
  5203. this.rawDestructor(ptr);
  5204. }
  5205. }
  5206. function RegisteredPointer_deleteObject(handle) {
  5207. if (handle !== null) {
  5208. handle['delete']();
  5209. }
  5210. }
  5211. function init_RegisteredPointer() {
  5212. RegisteredPointer.prototype.getPointee = RegisteredPointer_getPointee;
  5213. RegisteredPointer.prototype.destructor = RegisteredPointer_destructor;
  5214. RegisteredPointer.prototype['argPackAdvance'] = 8;
  5215. RegisteredPointer.prototype['readValueFromPointer'] = simpleReadValueFromPointer;
  5216. RegisteredPointer.prototype['deleteObject'] = RegisteredPointer_deleteObject;
  5217. RegisteredPointer.prototype['fromWireType'] = RegisteredPointer_fromWireType;
  5218. }
  5219. /** @constructor
  5220. @param {*=} pointeeType,
  5221. @param {*=} sharingPolicy,
  5222. @param {*=} rawGetPointee,
  5223. @param {*=} rawConstructor,
  5224. @param {*=} rawShare,
  5225. @param {*=} rawDestructor,
  5226. */
  5227. function RegisteredPointer(
  5228. name,
  5229. registeredClass,
  5230. isReference,
  5231. isConst,
  5232. // smart pointer properties
  5233. isSmartPointer,
  5234. pointeeType,
  5235. sharingPolicy,
  5236. rawGetPointee,
  5237. rawConstructor,
  5238. rawShare,
  5239. rawDestructor
  5240. ) {
  5241. this.name = name;
  5242. this.registeredClass = registeredClass;
  5243. this.isReference = isReference;
  5244. this.isConst = isConst;
  5245. // smart pointer properties
  5246. this.isSmartPointer = isSmartPointer;
  5247. this.pointeeType = pointeeType;
  5248. this.sharingPolicy = sharingPolicy;
  5249. this.rawGetPointee = rawGetPointee;
  5250. this.rawConstructor = rawConstructor;
  5251. this.rawShare = rawShare;
  5252. this.rawDestructor = rawDestructor;
  5253. if (!isSmartPointer && registeredClass.baseClass === undefined) {
  5254. if (isConst) {
  5255. this['toWireType'] = constNoSmartPtrRawPointerToWireType;
  5256. this.destructorFunction = null;
  5257. } else {
  5258. this['toWireType'] = nonConstNoSmartPtrRawPointerToWireType;
  5259. this.destructorFunction = null;
  5260. }
  5261. } else {
  5262. this['toWireType'] = genericPointerToWireType;
  5263. // Here we must leave this.destructorFunction undefined, since whether genericPointerToWireType returns
  5264. // a pointer that needs to be freed up is runtime-dependent, and cannot be evaluated at registration time.
  5265. // TODO: Create an alternative mechanism that allows removing the use of var destructors = []; array in
  5266. // craftInvokerFunction altogether.
  5267. }
  5268. }
  5269. /** @param {number=} numArguments */
  5270. function replacePublicSymbol(name, value, numArguments) {
  5271. if (!Module.hasOwnProperty(name)) {
  5272. throwInternalError('Replacing nonexistant public symbol');
  5273. }
  5274. // If there's an overload table for this symbol, replace the symbol in the overload table instead.
  5275. if (undefined !== Module[name].overloadTable && undefined !== numArguments) {
  5276. Module[name].overloadTable[numArguments] = value;
  5277. }
  5278. else {
  5279. Module[name] = value;
  5280. Module[name].argCount = numArguments;
  5281. }
  5282. }
  5283. function dynCallLegacy(sig, ptr, args) {
  5284. assert(('dynCall_' + sig) in Module, 'bad function pointer type - dynCall function not found for sig \'' + sig + '\'');
  5285. if (args && args.length) {
  5286. // j (64-bit integer) must be passed in as two numbers [low 32, high 32].
  5287. assert(args.length === sig.substring(1).replace(/j/g, '--').length);
  5288. } else {
  5289. assert(sig.length == 1);
  5290. }
  5291. var f = Module['dynCall_' + sig];
  5292. return args && args.length ? f.apply(null, [ptr].concat(args)) : f.call(null, ptr);
  5293. }
  5294. var wasmTableMirror = [];
  5295. function getWasmTableEntry(funcPtr) {
  5296. var func = wasmTableMirror[funcPtr];
  5297. if (!func) {
  5298. if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
  5299. wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
  5300. }
  5301. assert(wasmTable.get(funcPtr) == func, "JavaScript-side Wasm function table mirror is out of date!");
  5302. return func;
  5303. }
  5304. /** @param {Object=} args */
  5305. function dynCall(sig, ptr, args) {
  5306. // Without WASM_BIGINT support we cannot directly call function with i64 as
  5307. // part of thier signature, so we rely the dynCall functions generated by
  5308. // wasm-emscripten-finalize
  5309. if (sig.includes('j')) {
  5310. return dynCallLegacy(sig, ptr, args);
  5311. }
  5312. assert(getWasmTableEntry(ptr), 'missing table entry in dynCall: ' + ptr);
  5313. var rtn = getWasmTableEntry(ptr).apply(null, args);
  5314. return rtn;
  5315. }
  5316. function getDynCaller(sig, ptr) {
  5317. assert(sig.includes('j') || sig.includes('p'), 'getDynCaller should only be called with i64 sigs')
  5318. var argCache = [];
  5319. return function() {
  5320. argCache.length = 0;
  5321. Object.assign(argCache, arguments);
  5322. return dynCall(sig, ptr, argCache);
  5323. };
  5324. }
  5325. function embind__requireFunction(signature, rawFunction) {
  5326. signature = readLatin1String(signature);
  5327. function makeDynCaller() {
  5328. if (signature.includes('j')) {
  5329. return getDynCaller(signature, rawFunction);
  5330. }
  5331. return getWasmTableEntry(rawFunction);
  5332. }
  5333. var fp = makeDynCaller();
  5334. if (typeof fp != "function") {
  5335. throwBindingError("unknown function pointer with signature " + signature + ": " + rawFunction);
  5336. }
  5337. return fp;
  5338. }
  5339. var UnboundTypeError = undefined;
  5340. function getTypeName(type) {
  5341. var ptr = ___getTypeName(type);
  5342. var rv = readLatin1String(ptr);
  5343. _free(ptr);
  5344. return rv;
  5345. }
  5346. function throwUnboundTypeError(message, types) {
  5347. var unboundTypes = [];
  5348. var seen = {};
  5349. function visit(type) {
  5350. if (seen[type]) {
  5351. return;
  5352. }
  5353. if (registeredTypes[type]) {
  5354. return;
  5355. }
  5356. if (typeDependencies[type]) {
  5357. typeDependencies[type].forEach(visit);
  5358. return;
  5359. }
  5360. unboundTypes.push(type);
  5361. seen[type] = true;
  5362. }
  5363. types.forEach(visit);
  5364. throw new UnboundTypeError(message + ': ' + unboundTypes.map(getTypeName).join([', ']));
  5365. }
  5366. function __embind_register_class(rawType,
  5367. rawPointerType,
  5368. rawConstPointerType,
  5369. baseClassRawType,
  5370. getActualTypeSignature,
  5371. getActualType,
  5372. upcastSignature,
  5373. upcast,
  5374. downcastSignature,
  5375. downcast,
  5376. name,
  5377. destructorSignature,
  5378. rawDestructor) {
  5379. name = readLatin1String(name);
  5380. getActualType = embind__requireFunction(getActualTypeSignature, getActualType);
  5381. if (upcast) {
  5382. upcast = embind__requireFunction(upcastSignature, upcast);
  5383. }
  5384. if (downcast) {
  5385. downcast = embind__requireFunction(downcastSignature, downcast);
  5386. }
  5387. rawDestructor = embind__requireFunction(destructorSignature, rawDestructor);
  5388. var legalFunctionName = makeLegalFunctionName(name);
  5389. exposePublicSymbol(legalFunctionName, function() {
  5390. // this code cannot run if baseClassRawType is zero
  5391. throwUnboundTypeError('Cannot construct ' + name + ' due to unbound types', [baseClassRawType]);
  5392. });
  5393. whenDependentTypesAreResolved(
  5394. [rawType, rawPointerType, rawConstPointerType],
  5395. baseClassRawType ? [baseClassRawType] : [],
  5396. function(base) {
  5397. base = base[0];
  5398. var baseClass;
  5399. var basePrototype;
  5400. if (baseClassRawType) {
  5401. baseClass = base.registeredClass;
  5402. basePrototype = baseClass.instancePrototype;
  5403. } else {
  5404. basePrototype = ClassHandle.prototype;
  5405. }
  5406. var constructor = createNamedFunction(legalFunctionName, function() {
  5407. if (Object.getPrototypeOf(this) !== instancePrototype) {
  5408. throw new BindingError("Use 'new' to construct " + name);
  5409. }
  5410. if (undefined === registeredClass.constructor_body) {
  5411. throw new BindingError(name + " has no accessible constructor");
  5412. }
  5413. var body = registeredClass.constructor_body[arguments.length];
  5414. if (undefined === body) {
  5415. throw new BindingError("Tried to invoke ctor of " + name + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(registeredClass.constructor_body).toString() + ") parameters instead!");
  5416. }
  5417. return body.apply(this, arguments);
  5418. });
  5419. var instancePrototype = Object.create(basePrototype, {
  5420. constructor: { value: constructor },
  5421. });
  5422. constructor.prototype = instancePrototype;
  5423. var registeredClass = new RegisteredClass(name,
  5424. constructor,
  5425. instancePrototype,
  5426. rawDestructor,
  5427. baseClass,
  5428. getActualType,
  5429. upcast,
  5430. downcast);
  5431. var referenceConverter = new RegisteredPointer(name,
  5432. registeredClass,
  5433. true,
  5434. false,
  5435. false);
  5436. var pointerConverter = new RegisteredPointer(name + '*',
  5437. registeredClass,
  5438. false,
  5439. false,
  5440. false);
  5441. var constPointerConverter = new RegisteredPointer(name + ' const*',
  5442. registeredClass,
  5443. false,
  5444. true,
  5445. false);
  5446. registeredPointers[rawType] = {
  5447. pointerType: pointerConverter,
  5448. constPointerType: constPointerConverter
  5449. };
  5450. replacePublicSymbol(legalFunctionName, constructor);
  5451. return [referenceConverter, pointerConverter, constPointerConverter];
  5452. }
  5453. );
  5454. }
  5455. function new_(constructor, argumentList) {
  5456. if (!(constructor instanceof Function)) {
  5457. throw new TypeError('new_ called with constructor type ' + typeof(constructor) + " which is not a function");
  5458. }
  5459. /*
  5460. * Previously, the following line was just:
  5461. * function dummy() {};
  5462. * Unfortunately, Chrome was preserving 'dummy' as the object's name, even
  5463. * though at creation, the 'dummy' has the correct constructor name. Thus,
  5464. * objects created with IMVU.new would show up in the debugger as 'dummy',
  5465. * which isn't very helpful. Using IMVU.createNamedFunction addresses the
  5466. * issue. Doublely-unfortunately, there's no way to write a test for this
  5467. * behavior. -NRD 2013.02.22
  5468. */
  5469. var dummy = createNamedFunction(constructor.name || 'unknownFunctionName', function(){});
  5470. dummy.prototype = constructor.prototype;
  5471. var obj = new dummy;
  5472. var r = constructor.apply(obj, argumentList);
  5473. return (r instanceof Object) ? r : obj;
  5474. }
  5475. function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) {
  5476. // humanName: a human-readable string name for the function to be generated.
  5477. // argTypes: An array that contains the embind type objects for all types in the function signature.
  5478. // argTypes[0] is the type object for the function return value.
  5479. // argTypes[1] is the type object for function this object/class type, or null if not crafting an invoker for a class method.
  5480. // argTypes[2...] are the actual function parameters.
  5481. // classType: The embind type object for the class to be bound, or null if this is not a method of a class.
  5482. // cppInvokerFunc: JS Function object to the C++-side function that interops into C++ code.
  5483. // cppTargetFunc: Function pointer (an integer to FUNCTION_TABLE) to the target C++ function the cppInvokerFunc will end up calling.
  5484. var argCount = argTypes.length;
  5485. if (argCount < 2) {
  5486. throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
  5487. }
  5488. var isClassMethodFunc = (argTypes[1] !== null && classType !== null);
  5489. // Free functions with signature "void function()" do not need an invoker that marshalls between wire types.
  5490. // TODO: This omits argument count check - enable only at -O3 or similar.
  5491. // if (ENABLE_UNSAFE_OPTS && argCount == 2 && argTypes[0].name == "void" && !isClassMethodFunc) {
  5492. // return FUNCTION_TABLE[fn];
  5493. // }
  5494. // Determine if we need to use a dynamic stack to store the destructors for the function parameters.
  5495. // TODO: Remove this completely once all function invokers are being dynamically generated.
  5496. var needsDestructorStack = false;
  5497. for (var i = 1; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here.
  5498. if (argTypes[i] !== null && argTypes[i].destructorFunction === undefined) { // The type does not define a destructor function - must use dynamic stack
  5499. needsDestructorStack = true;
  5500. break;
  5501. }
  5502. }
  5503. var returns = (argTypes[0].name !== "void");
  5504. var argsList = "";
  5505. var argsListWired = "";
  5506. for (var i = 0; i < argCount - 2; ++i) {
  5507. argsList += (i!==0?", ":"")+"arg"+i;
  5508. argsListWired += (i!==0?", ":"")+"arg"+i+"Wired";
  5509. }
  5510. var invokerFnBody =
  5511. "return function "+makeLegalFunctionName(humanName)+"("+argsList+") {\n" +
  5512. "if (arguments.length !== "+(argCount - 2)+") {\n" +
  5513. "throwBindingError('function "+humanName+" called with ' + arguments.length + ' arguments, expected "+(argCount - 2)+" args!');\n" +
  5514. "}\n";
  5515. if (needsDestructorStack) {
  5516. invokerFnBody += "var destructors = [];\n";
  5517. }
  5518. var dtorStack = needsDestructorStack ? "destructors" : "null";
  5519. var args1 = ["throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"];
  5520. var args2 = [throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]];
  5521. if (isClassMethodFunc) {
  5522. invokerFnBody += "var thisWired = classParam.toWireType("+dtorStack+", this);\n";
  5523. }
  5524. for (var i = 0; i < argCount - 2; ++i) {
  5525. invokerFnBody += "var arg"+i+"Wired = argType"+i+".toWireType("+dtorStack+", arg"+i+"); // "+argTypes[i+2].name+"\n";
  5526. args1.push("argType"+i);
  5527. args2.push(argTypes[i+2]);
  5528. }
  5529. if (isClassMethodFunc) {
  5530. argsListWired = "thisWired" + (argsListWired.length > 0 ? ", " : "") + argsListWired;
  5531. }
  5532. invokerFnBody +=
  5533. (returns?"var rv = ":"") + "invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";
  5534. if (needsDestructorStack) {
  5535. invokerFnBody += "runDestructors(destructors);\n";
  5536. } else {
  5537. for (var i = isClassMethodFunc?1:2; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here. Also skip class type if not a method.
  5538. var paramName = (i === 1 ? "thisWired" : ("arg"+(i - 2)+"Wired"));
  5539. if (argTypes[i].destructorFunction !== null) {
  5540. invokerFnBody += paramName+"_dtor("+paramName+"); // "+argTypes[i].name+"\n";
  5541. args1.push(paramName+"_dtor");
  5542. args2.push(argTypes[i].destructorFunction);
  5543. }
  5544. }
  5545. }
  5546. if (returns) {
  5547. invokerFnBody += "var ret = retType.fromWireType(rv);\n" +
  5548. "return ret;\n";
  5549. } else {
  5550. }
  5551. invokerFnBody += "}\n";
  5552. args1.push(invokerFnBody);
  5553. var invokerFunction = new_(Function, args1).apply(null, args2);
  5554. return invokerFunction;
  5555. }
  5556. function heap32VectorToArray(count, firstElement) {
  5557. var array = [];
  5558. for (var i = 0; i < count; i++) {
  5559. // TODO(https://github.com/emscripten-core/emscripten/issues/17310):
  5560. // Find a way to hoist the `>> 2` or `>> 3` out of this loop.
  5561. array.push(HEAPU32[(((firstElement)+(i * 4))>>2)]);
  5562. }
  5563. return array;
  5564. }
  5565. function __embind_register_class_class_function(rawClassType,
  5566. methodName,
  5567. argCount,
  5568. rawArgTypesAddr,
  5569. invokerSignature,
  5570. rawInvoker,
  5571. fn) {
  5572. var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  5573. methodName = readLatin1String(methodName);
  5574. rawInvoker = embind__requireFunction(invokerSignature, rawInvoker);
  5575. whenDependentTypesAreResolved([], [rawClassType], function(classType) {
  5576. classType = classType[0];
  5577. var humanName = classType.name + '.' + methodName;
  5578. function unboundTypesHandler() {
  5579. throwUnboundTypeError('Cannot call ' + humanName + ' due to unbound types', rawArgTypes);
  5580. }
  5581. if (methodName.startsWith("@@")) {
  5582. methodName = Symbol[methodName.substring(2)];
  5583. }
  5584. var proto = classType.registeredClass.constructor;
  5585. if (undefined === proto[methodName]) {
  5586. // This is the first function to be registered with this name.
  5587. unboundTypesHandler.argCount = argCount-1;
  5588. proto[methodName] = unboundTypesHandler;
  5589. } else {
  5590. // There was an existing function with the same name registered. Set up
  5591. // a function overload routing table.
  5592. ensureOverloadTable(proto, methodName, humanName);
  5593. proto[methodName].overloadTable[argCount-1] = unboundTypesHandler;
  5594. }
  5595. whenDependentTypesAreResolved([], rawArgTypes, function(argTypes) {
  5596. // Replace the initial unbound-types-handler stub with the proper
  5597. // function. If multiple overloads are registered, the function handlers
  5598. // go into an overload table.
  5599. var invokerArgsArray = [argTypes[0] /* return value */, null /* no class 'this'*/].concat(argTypes.slice(1) /* actual params */);
  5600. var func = craftInvokerFunction(humanName, invokerArgsArray, null /* no class 'this'*/, rawInvoker, fn);
  5601. if (undefined === proto[methodName].overloadTable) {
  5602. func.argCount = argCount-1;
  5603. proto[methodName] = func;
  5604. } else {
  5605. proto[methodName].overloadTable[argCount-1] = func;
  5606. }
  5607. return [];
  5608. });
  5609. return [];
  5610. });
  5611. }
  5612. function __embind_register_class_constructor(
  5613. rawClassType,
  5614. argCount,
  5615. rawArgTypesAddr,
  5616. invokerSignature,
  5617. invoker,
  5618. rawConstructor
  5619. ) {
  5620. assert(argCount > 0);
  5621. var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  5622. invoker = embind__requireFunction(invokerSignature, invoker);
  5623. var args = [rawConstructor];
  5624. var destructors = [];
  5625. whenDependentTypesAreResolved([], [rawClassType], function(classType) {
  5626. classType = classType[0];
  5627. var humanName = 'constructor ' + classType.name;
  5628. if (undefined === classType.registeredClass.constructor_body) {
  5629. classType.registeredClass.constructor_body = [];
  5630. }
  5631. if (undefined !== classType.registeredClass.constructor_body[argCount - 1]) {
  5632. throw new BindingError("Cannot register multiple constructors with identical number of parameters (" + (argCount-1) + ") for class '" + classType.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
  5633. }
  5634. classType.registeredClass.constructor_body[argCount - 1] = () => {
  5635. throwUnboundTypeError('Cannot construct ' + classType.name + ' due to unbound types', rawArgTypes);
  5636. };
  5637. whenDependentTypesAreResolved([], rawArgTypes, function(argTypes) {
  5638. // Insert empty slot for context type (argTypes[1]).
  5639. argTypes.splice(1, 0, null);
  5640. classType.registeredClass.constructor_body[argCount - 1] = craftInvokerFunction(humanName, argTypes, null, invoker, rawConstructor);
  5641. return [];
  5642. });
  5643. return [];
  5644. });
  5645. }
  5646. function __embind_register_class_function(rawClassType,
  5647. methodName,
  5648. argCount,
  5649. rawArgTypesAddr, // [ReturnType, ThisType, Args...]
  5650. invokerSignature,
  5651. rawInvoker,
  5652. context,
  5653. isPureVirtual) {
  5654. var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  5655. methodName = readLatin1String(methodName);
  5656. rawInvoker = embind__requireFunction(invokerSignature, rawInvoker);
  5657. whenDependentTypesAreResolved([], [rawClassType], function(classType) {
  5658. classType = classType[0];
  5659. var humanName = classType.name + '.' + methodName;
  5660. if (methodName.startsWith("@@")) {
  5661. methodName = Symbol[methodName.substring(2)];
  5662. }
  5663. if (isPureVirtual) {
  5664. classType.registeredClass.pureVirtualFunctions.push(methodName);
  5665. }
  5666. function unboundTypesHandler() {
  5667. throwUnboundTypeError('Cannot call ' + humanName + ' due to unbound types', rawArgTypes);
  5668. }
  5669. var proto = classType.registeredClass.instancePrototype;
  5670. var method = proto[methodName];
  5671. if (undefined === method || (undefined === method.overloadTable && method.className !== classType.name && method.argCount === argCount - 2)) {
  5672. // This is the first overload to be registered, OR we are replacing a
  5673. // function in the base class with a function in the derived class.
  5674. unboundTypesHandler.argCount = argCount - 2;
  5675. unboundTypesHandler.className = classType.name;
  5676. proto[methodName] = unboundTypesHandler;
  5677. } else {
  5678. // There was an existing function with the same name registered. Set up
  5679. // a function overload routing table.
  5680. ensureOverloadTable(proto, methodName, humanName);
  5681. proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler;
  5682. }
  5683. whenDependentTypesAreResolved([], rawArgTypes, function(argTypes) {
  5684. var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context);
  5685. // Replace the initial unbound-handler-stub function with the appropriate member function, now that all types
  5686. // are resolved. If multiple overloads are registered for this function, the function goes into an overload table.
  5687. if (undefined === proto[methodName].overloadTable) {
  5688. // Set argCount in case an overload is registered later
  5689. memberFunction.argCount = argCount - 2;
  5690. proto[methodName] = memberFunction;
  5691. } else {
  5692. proto[methodName].overloadTable[argCount - 2] = memberFunction;
  5693. }
  5694. return [];
  5695. });
  5696. return [];
  5697. });
  5698. }
  5699. function validateThis(this_, classType, humanName) {
  5700. if (!(this_ instanceof Object)) {
  5701. throwBindingError(humanName + ' with invalid "this": ' + this_);
  5702. }
  5703. if (!(this_ instanceof classType.registeredClass.constructor)) {
  5704. throwBindingError(humanName + ' incompatible with "this" of type ' + this_.constructor.name);
  5705. }
  5706. if (!this_.$$.ptr) {
  5707. throwBindingError('cannot call emscripten binding method ' + humanName + ' on deleted object');
  5708. }
  5709. // todo: kill this
  5710. return upcastPointer(this_.$$.ptr,
  5711. this_.$$.ptrType.registeredClass,
  5712. classType.registeredClass);
  5713. }
  5714. function __embind_register_class_property(classType,
  5715. fieldName,
  5716. getterReturnType,
  5717. getterSignature,
  5718. getter,
  5719. getterContext,
  5720. setterArgumentType,
  5721. setterSignature,
  5722. setter,
  5723. setterContext) {
  5724. fieldName = readLatin1String(fieldName);
  5725. getter = embind__requireFunction(getterSignature, getter);
  5726. whenDependentTypesAreResolved([], [classType], function(classType) {
  5727. classType = classType[0];
  5728. var humanName = classType.name + '.' + fieldName;
  5729. var desc = {
  5730. get: function() {
  5731. throwUnboundTypeError('Cannot access ' + humanName + ' due to unbound types', [getterReturnType, setterArgumentType]);
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. };
  5736. if (setter) {
  5737. desc.set = () => {
  5738. throwUnboundTypeError('Cannot access ' + humanName + ' due to unbound types', [getterReturnType, setterArgumentType]);
  5739. };
  5740. } else {
  5741. desc.set = (v) => {
  5742. throwBindingError(humanName + ' is a read-only property');
  5743. };
  5744. }
  5745. Object.defineProperty(classType.registeredClass.instancePrototype, fieldName, desc);
  5746. whenDependentTypesAreResolved(
  5747. [],
  5748. (setter ? [getterReturnType, setterArgumentType] : [getterReturnType]),
  5749. function(types) {
  5750. var getterReturnType = types[0];
  5751. var desc = {
  5752. get: function() {
  5753. var ptr = validateThis(this, classType, humanName + ' getter');
  5754. return getterReturnType['fromWireType'](getter(getterContext, ptr));
  5755. },
  5756. enumerable: true
  5757. };
  5758. if (setter) {
  5759. setter = embind__requireFunction(setterSignature, setter);
  5760. var setterArgumentType = types[1];
  5761. desc.set = function(v) {
  5762. var ptr = validateThis(this, classType, humanName + ' setter');
  5763. var destructors = [];
  5764. setter(setterContext, ptr, setterArgumentType['toWireType'](destructors, v));
  5765. runDestructors(destructors);
  5766. };
  5767. }
  5768. Object.defineProperty(classType.registeredClass.instancePrototype, fieldName, desc);
  5769. return [];
  5770. });
  5771. return [];
  5772. });
  5773. }
  5774. var emval_free_list = [];
  5775. var emval_handle_array = [{},{value:undefined},{value:null},{value:true},{value:false}];
  5776. function __emval_decref(handle) {
  5777. if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
  5778. emval_handle_array[handle] = undefined;
  5779. emval_free_list.push(handle);
  5780. }
  5781. }
  5782. function count_emval_handles() {
  5783. var count = 0;
  5784. for (var i = 5; i < emval_handle_array.length; ++i) {
  5785. if (emval_handle_array[i] !== undefined) {
  5786. ++count;
  5787. }
  5788. }
  5789. return count;
  5790. }
  5791. function get_first_emval() {
  5792. for (var i = 5; i < emval_handle_array.length; ++i) {
  5793. if (emval_handle_array[i] !== undefined) {
  5794. return emval_handle_array[i];
  5795. }
  5796. }
  5797. return null;
  5798. }
  5799. function init_emval() {
  5800. Module['count_emval_handles'] = count_emval_handles;
  5801. Module['get_first_emval'] = get_first_emval;
  5802. }
  5803. var Emval = {toValue:(handle) => {
  5804. if (!handle) {
  5805. throwBindingError('Cannot use deleted val. handle = ' + handle);
  5806. }
  5807. return emval_handle_array[handle].value;
  5808. },toHandle:(value) => {
  5809. switch (value) {
  5810. case undefined: return 1;
  5811. case null: return 2;
  5812. case true: return 3;
  5813. case false: return 4;
  5814. default:{
  5815. var handle = emval_free_list.length ?
  5816. emval_free_list.pop() :
  5817. emval_handle_array.length;
  5818. emval_handle_array[handle] = {refcount: 1, value: value};
  5819. return handle;
  5820. }
  5821. }
  5822. }};
  5823. function __embind_register_emval(rawType, name) {
  5824. name = readLatin1String(name);
  5825. registerType(rawType, {
  5826. name: name,
  5827. 'fromWireType': function(handle) {
  5828. var rv = Emval.toValue(handle);
  5829. __emval_decref(handle);
  5830. return rv;
  5831. },
  5832. 'toWireType': function(destructors, value) {
  5833. return Emval.toHandle(value);
  5834. },
  5835. 'argPackAdvance': 8,
  5836. 'readValueFromPointer': simpleReadValueFromPointer,
  5837. destructorFunction: null, // This type does not need a destructor
  5838. // TODO: do we need a deleteObject here? write a test where
  5839. // emval is passed into JS via an interface
  5840. });
  5841. }
  5842. function enumReadValueFromPointer(name, shift, signed) {
  5843. switch (shift) {
  5844. case 0: return function(pointer) {
  5845. var heap = signed ? HEAP8 : HEAPU8;
  5846. return this['fromWireType'](heap[pointer]);
  5847. };
  5848. case 1: return function(pointer) {
  5849. var heap = signed ? HEAP16 : HEAPU16;
  5850. return this['fromWireType'](heap[pointer >> 1]);
  5851. };
  5852. case 2: return function(pointer) {
  5853. var heap = signed ? HEAP32 : HEAPU32;
  5854. return this['fromWireType'](heap[pointer >> 2]);
  5855. };
  5856. default:
  5857. throw new TypeError("Unknown integer type: " + name);
  5858. }
  5859. }
  5860. function __embind_register_enum(rawType, name, size, isSigned) {
  5861. var shift = getShiftFromSize(size);
  5862. name = readLatin1String(name);
  5863. function ctor() {}
  5864. ctor.values = {};
  5865. registerType(rawType, {
  5866. name: name,
  5867. constructor: ctor,
  5868. 'fromWireType': function(c) {
  5869. return this.constructor.values[c];
  5870. },
  5871. 'toWireType': function(destructors, c) {
  5872. return c.value;
  5873. },
  5874. 'argPackAdvance': 8,
  5875. 'readValueFromPointer': enumReadValueFromPointer(name, shift, isSigned),
  5876. destructorFunction: null,
  5877. });
  5878. exposePublicSymbol(name, ctor);
  5879. }
  5880. function requireRegisteredType(rawType, humanName) {
  5881. var impl = registeredTypes[rawType];
  5882. if (undefined === impl) {
  5883. throwBindingError(humanName + " has unknown type " + getTypeName(rawType));
  5884. }
  5885. return impl;
  5886. }
  5887. function __embind_register_enum_value(rawEnumType, name, enumValue) {
  5888. var enumType = requireRegisteredType(rawEnumType, 'enum');
  5889. name = readLatin1String(name);
  5890. var Enum = enumType.constructor;
  5891. var Value = Object.create(enumType.constructor.prototype, {
  5892. value: {value: enumValue},
  5893. constructor: {value: createNamedFunction(enumType.name + '_' + name, function() {})},
  5894. });
  5895. Enum.values[enumValue] = Value;
  5896. Enum[name] = Value;
  5897. }
  5898. function embindRepr(v) {
  5899. if (v === null) {
  5900. return 'null';
  5901. }
  5902. var t = typeof v;
  5903. if (t === 'object' || t === 'array' || t === 'function') {
  5904. return v.toString();
  5905. } else {
  5906. return '' + v;
  5907. }
  5908. }
  5909. function floatReadValueFromPointer(name, shift) {
  5910. switch (shift) {
  5911. case 2: return function(pointer) {
  5912. return this['fromWireType'](HEAPF32[pointer >> 2]);
  5913. };
  5914. case 3: return function(pointer) {
  5915. return this['fromWireType'](HEAPF64[pointer >> 3]);
  5916. };
  5917. default:
  5918. throw new TypeError("Unknown float type: " + name);
  5919. }
  5920. }
  5921. function __embind_register_float(rawType, name, size) {
  5922. var shift = getShiftFromSize(size);
  5923. name = readLatin1String(name);
  5924. registerType(rawType, {
  5925. name: name,
  5926. 'fromWireType': function(value) {
  5927. return value;
  5928. },
  5929. 'toWireType': function(destructors, value) {
  5930. if (typeof value != "number" && typeof value != "boolean") {
  5931. throw new TypeError('Cannot convert "' + embindRepr(value) + '" to ' + this.name);
  5932. }
  5933. // The VM will perform JS to Wasm value conversion, according to the spec:
  5934. // https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
  5935. return value;
  5936. },
  5937. 'argPackAdvance': 8,
  5938. 'readValueFromPointer': floatReadValueFromPointer(name, shift),
  5939. destructorFunction: null, // This type does not need a destructor
  5940. });
  5941. }
  5942. function integerReadValueFromPointer(name, shift, signed) {
  5943. // integers are quite common, so generate very specialized functions
  5944. switch (shift) {
  5945. case 0: return signed ?
  5946. function readS8FromPointer(pointer) { return HEAP8[pointer]; } :
  5947. function readU8FromPointer(pointer) { return HEAPU8[pointer]; };
  5948. case 1: return signed ?
  5949. function readS16FromPointer(pointer) { return HEAP16[pointer >> 1]; } :
  5950. function readU16FromPointer(pointer) { return HEAPU16[pointer >> 1]; };
  5951. case 2: return signed ?
  5952. function readS32FromPointer(pointer) { return HEAP32[pointer >> 2]; } :
  5953. function readU32FromPointer(pointer) { return HEAPU32[pointer >> 2]; };
  5954. default:
  5955. throw new TypeError("Unknown integer type: " + name);
  5956. }
  5957. }
  5958. function __embind_register_integer(primitiveType, name, size, minRange, maxRange) {
  5959. name = readLatin1String(name);
  5960. // LLVM doesn't have signed and unsigned 32-bit types, so u32 literals come
  5961. // out as 'i32 -1'. Always treat those as max u32.
  5962. if (maxRange === -1) {
  5963. maxRange = 4294967295;
  5964. }
  5965. var shift = getShiftFromSize(size);
  5966. var fromWireType = (value) => value;
  5967. if (minRange === 0) {
  5968. var bitshift = 32 - 8*size;
  5969. fromWireType = (value) => (value << bitshift) >>> bitshift;
  5970. }
  5971. var isUnsignedType = (name.includes('unsigned'));
  5972. var checkAssertions = (value, toTypeName) => {
  5973. if (typeof value != "number" && typeof value != "boolean") {
  5974. throw new TypeError('Cannot convert "' + embindRepr(value) + '" to ' + toTypeName);
  5975. }
  5976. if (value < minRange || value > maxRange) {
  5977. throw new TypeError('Passing a number "' + embindRepr(value) + '" from JS side to C/C++ side to an argument of type "' + name + '", which is outside the valid range [' + minRange + ', ' + maxRange + ']!');
  5978. }
  5979. }
  5980. var toWireType;
  5981. if (isUnsignedType) {
  5982. toWireType = function(destructors, value) {
  5983. checkAssertions(value, this.name);
  5984. return value >>> 0;
  5985. }
  5986. } else {
  5987. toWireType = function(destructors, value) {
  5988. checkAssertions(value, this.name);
  5989. // The VM will perform JS to Wasm value conversion, according to the spec:
  5990. // https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
  5991. return value;
  5992. }
  5993. }
  5994. registerType(primitiveType, {
  5995. name: name,
  5996. 'fromWireType': fromWireType,
  5997. 'toWireType': toWireType,
  5998. 'argPackAdvance': 8,
  5999. 'readValueFromPointer': integerReadValueFromPointer(name, shift, minRange !== 0),
  6000. destructorFunction: null, // This type does not need a destructor
  6001. });
  6002. }
  6003. function __embind_register_memory_view(rawType, dataTypeIndex, name) {
  6004. var typeMapping = [
  6005. Int8Array,
  6006. Uint8Array,
  6007. Int16Array,
  6008. Uint16Array,
  6009. Int32Array,
  6010. Uint32Array,
  6011. Float32Array,
  6012. Float64Array,
  6013. ];
  6014. var TA = typeMapping[dataTypeIndex];
  6015. function decodeMemoryView(handle) {
  6016. handle = handle >> 2;
  6017. var heap = HEAPU32;
  6018. var size = heap[handle]; // in elements
  6019. var data = heap[handle + 1]; // byte offset into emscripten heap
  6020. return new TA(heap.buffer, data, size);
  6021. }
  6022. name = readLatin1String(name);
  6023. registerType(rawType, {
  6024. name: name,
  6025. 'fromWireType': decodeMemoryView,
  6026. 'argPackAdvance': 8,
  6027. 'readValueFromPointer': decodeMemoryView,
  6028. }, {
  6029. ignoreDuplicateRegistrations: true,
  6030. });
  6031. }
  6032. function __embind_register_std_string(rawType, name) {
  6033. name = readLatin1String(name);
  6034. var stdStringIsUTF8
  6035. //process only std::string bindings with UTF8 support, in contrast to e.g. std::basic_string<unsigned char>
  6036. = (name === "std::string");
  6037. registerType(rawType, {
  6038. name: name,
  6039. 'fromWireType': function(value) {
  6040. var length = HEAPU32[((value)>>2)];
  6041. var payload = value + 4;
  6042. var str;
  6043. if (stdStringIsUTF8) {
  6044. var decodeStartPtr = payload;
  6045. // Looping here to support possible embedded '0' bytes
  6046. for (var i = 0; i <= length; ++i) {
  6047. var currentBytePtr = payload + i;
  6048. if (i == length || HEAPU8[currentBytePtr] == 0) {
  6049. var maxRead = currentBytePtr - decodeStartPtr;
  6050. var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
  6051. if (str === undefined) {
  6052. str = stringSegment;
  6053. } else {
  6054. str += String.fromCharCode(0);
  6055. str += stringSegment;
  6056. }
  6057. decodeStartPtr = currentBytePtr + 1;
  6058. }
  6059. }
  6060. } else {
  6061. var a = new Array(length);
  6062. for (var i = 0; i < length; ++i) {
  6063. a[i] = String.fromCharCode(HEAPU8[payload + i]);
  6064. }
  6065. str = a.join('');
  6066. }
  6067. _free(value);
  6068. return str;
  6069. },
  6070. 'toWireType': function(destructors, value) {
  6071. if (value instanceof ArrayBuffer) {
  6072. value = new Uint8Array(value);
  6073. }
  6074. var length;
  6075. var valueIsOfTypeString = (typeof value == 'string');
  6076. if (!(valueIsOfTypeString || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int8Array)) {
  6077. throwBindingError('Cannot pass non-string to std::string');
  6078. }
  6079. if (stdStringIsUTF8 && valueIsOfTypeString) {
  6080. length = lengthBytesUTF8(value);
  6081. } else {
  6082. length = value.length;
  6083. }
  6084. // assumes 4-byte alignment
  6085. var base = _malloc(4 + length + 1);
  6086. var ptr = base + 4;
  6087. HEAPU32[((base)>>2)] = length;
  6088. if (stdStringIsUTF8 && valueIsOfTypeString) {
  6089. stringToUTF8(value, ptr, length + 1);
  6090. } else {
  6091. if (valueIsOfTypeString) {
  6092. for (var i = 0; i < length; ++i) {
  6093. var charCode = value.charCodeAt(i);
  6094. if (charCode > 255) {
  6095. _free(ptr);
  6096. throwBindingError('String has UTF-16 code units that do not fit in 8 bits');
  6097. }
  6098. HEAPU8[ptr + i] = charCode;
  6099. }
  6100. } else {
  6101. for (var i = 0; i < length; ++i) {
  6102. HEAPU8[ptr + i] = value[i];
  6103. }
  6104. }
  6105. }
  6106. if (destructors !== null) {
  6107. destructors.push(_free, base);
  6108. }
  6109. return base;
  6110. },
  6111. 'argPackAdvance': 8,
  6112. 'readValueFromPointer': simpleReadValueFromPointer,
  6113. destructorFunction: function(ptr) { _free(ptr); },
  6114. });
  6115. }
  6116. var UTF16Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf-16le') : undefined;;
  6117. function UTF16ToString(ptr, maxBytesToRead) {
  6118. assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
  6119. var endPtr = ptr;
  6120. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  6121. // null terminator by itself.
  6122. // Also, use the length info to avoid running tiny strings through
  6123. // TextDecoder, since .subarray() allocates garbage.
  6124. var idx = endPtr >> 1;
  6125. var maxIdx = idx + maxBytesToRead / 2;
  6126. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  6127. // will always evaluate to true. This saves on code size.
  6128. while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
  6129. endPtr = idx << 1;
  6130. if (endPtr - ptr > 32 && UTF16Decoder)
  6131. return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
  6132. // Fallback: decode without UTF16Decoder
  6133. var str = '';
  6134. // If maxBytesToRead is not passed explicitly, it will be undefined, and the
  6135. // for-loop's condition will always evaluate to true. The loop is then
  6136. // terminated on the first null char.
  6137. for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
  6138. var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
  6139. if (codeUnit == 0) break;
  6140. // fromCharCode constructs a character from a UTF-16 code unit, so we can
  6141. // pass the UTF16 string right through.
  6142. str += String.fromCharCode(codeUnit);
  6143. }
  6144. return str;
  6145. }
  6146. function stringToUTF16(str, outPtr, maxBytesToWrite) {
  6147. assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
  6148. assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  6149. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  6150. if (maxBytesToWrite === undefined) {
  6151. maxBytesToWrite = 0x7FFFFFFF;
  6152. }
  6153. if (maxBytesToWrite < 2) return 0;
  6154. maxBytesToWrite -= 2; // Null terminator.
  6155. var startPtr = outPtr;
  6156. var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
  6157. for (var i = 0; i < numCharsToWrite; ++i) {
  6158. // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
  6159. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  6160. HEAP16[((outPtr)>>1)] = codeUnit;
  6161. outPtr += 2;
  6162. }
  6163. // Null-terminate the pointer to the HEAP.
  6164. HEAP16[((outPtr)>>1)] = 0;
  6165. return outPtr - startPtr;
  6166. }
  6167. function lengthBytesUTF16(str) {
  6168. return str.length*2;
  6169. }
  6170. function UTF32ToString(ptr, maxBytesToRead) {
  6171. assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
  6172. var i = 0;
  6173. var str = '';
  6174. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  6175. // will always evaluate to true. This saves on code size.
  6176. while (!(i >= maxBytesToRead / 4)) {
  6177. var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
  6178. if (utf32 == 0) break;
  6179. ++i;
  6180. // 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.
  6181. // See http://unicode.org/faq/utf_bom.html#utf16-3
  6182. if (utf32 >= 0x10000) {
  6183. var ch = utf32 - 0x10000;
  6184. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  6185. } else {
  6186. str += String.fromCharCode(utf32);
  6187. }
  6188. }
  6189. return str;
  6190. }
  6191. function stringToUTF32(str, outPtr, maxBytesToWrite) {
  6192. assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
  6193. assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  6194. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  6195. if (maxBytesToWrite === undefined) {
  6196. maxBytesToWrite = 0x7FFFFFFF;
  6197. }
  6198. if (maxBytesToWrite < 4) return 0;
  6199. var startPtr = outPtr;
  6200. var endPtr = startPtr + maxBytesToWrite - 4;
  6201. for (var i = 0; i < str.length; ++i) {
  6202. // 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.
  6203. // See http://unicode.org/faq/utf_bom.html#utf16-3
  6204. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  6205. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
  6206. var trailSurrogate = str.charCodeAt(++i);
  6207. codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
  6208. }
  6209. HEAP32[((outPtr)>>2)] = codeUnit;
  6210. outPtr += 4;
  6211. if (outPtr + 4 > endPtr) break;
  6212. }
  6213. // Null-terminate the pointer to the HEAP.
  6214. HEAP32[((outPtr)>>2)] = 0;
  6215. return outPtr - startPtr;
  6216. }
  6217. function lengthBytesUTF32(str) {
  6218. var len = 0;
  6219. for (var i = 0; i < str.length; ++i) {
  6220. // 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.
  6221. // See http://unicode.org/faq/utf_bom.html#utf16-3
  6222. var codeUnit = str.charCodeAt(i);
  6223. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
  6224. len += 4;
  6225. }
  6226. return len;
  6227. }
  6228. function __embind_register_std_wstring(rawType, charSize, name) {
  6229. name = readLatin1String(name);
  6230. var decodeString, encodeString, getHeap, lengthBytesUTF, shift;
  6231. if (charSize === 2) {
  6232. decodeString = UTF16ToString;
  6233. encodeString = stringToUTF16;
  6234. lengthBytesUTF = lengthBytesUTF16;
  6235. getHeap = () => HEAPU16;
  6236. shift = 1;
  6237. } else if (charSize === 4) {
  6238. decodeString = UTF32ToString;
  6239. encodeString = stringToUTF32;
  6240. lengthBytesUTF = lengthBytesUTF32;
  6241. getHeap = () => HEAPU32;
  6242. shift = 2;
  6243. }
  6244. registerType(rawType, {
  6245. name: name,
  6246. 'fromWireType': function(value) {
  6247. // Code mostly taken from _embind_register_std_string fromWireType
  6248. var length = HEAPU32[value >> 2];
  6249. var HEAP = getHeap();
  6250. var str;
  6251. var decodeStartPtr = value + 4;
  6252. // Looping here to support possible embedded '0' bytes
  6253. for (var i = 0; i <= length; ++i) {
  6254. var currentBytePtr = value + 4 + i * charSize;
  6255. if (i == length || HEAP[currentBytePtr >> shift] == 0) {
  6256. var maxReadBytes = currentBytePtr - decodeStartPtr;
  6257. var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
  6258. if (str === undefined) {
  6259. str = stringSegment;
  6260. } else {
  6261. str += String.fromCharCode(0);
  6262. str += stringSegment;
  6263. }
  6264. decodeStartPtr = currentBytePtr + charSize;
  6265. }
  6266. }
  6267. _free(value);
  6268. return str;
  6269. },
  6270. 'toWireType': function(destructors, value) {
  6271. if (!(typeof value == 'string')) {
  6272. throwBindingError('Cannot pass non-string to C++ string type ' + name);
  6273. }
  6274. // assumes 4-byte alignment
  6275. var length = lengthBytesUTF(value);
  6276. var ptr = _malloc(4 + length + charSize);
  6277. HEAPU32[ptr >> 2] = length >> shift;
  6278. encodeString(value, ptr + 4, length + charSize);
  6279. if (destructors !== null) {
  6280. destructors.push(_free, ptr);
  6281. }
  6282. return ptr;
  6283. },
  6284. 'argPackAdvance': 8,
  6285. 'readValueFromPointer': simpleReadValueFromPointer,
  6286. destructorFunction: function(ptr) { _free(ptr); },
  6287. });
  6288. }
  6289. function __embind_register_value_array(
  6290. rawType,
  6291. name,
  6292. constructorSignature,
  6293. rawConstructor,
  6294. destructorSignature,
  6295. rawDestructor
  6296. ) {
  6297. tupleRegistrations[rawType] = {
  6298. name: readLatin1String(name),
  6299. rawConstructor: embind__requireFunction(constructorSignature, rawConstructor),
  6300. rawDestructor: embind__requireFunction(destructorSignature, rawDestructor),
  6301. elements: [],
  6302. };
  6303. }
  6304. function __embind_register_value_array_element(
  6305. rawTupleType,
  6306. getterReturnType,
  6307. getterSignature,
  6308. getter,
  6309. getterContext,
  6310. setterArgumentType,
  6311. setterSignature,
  6312. setter,
  6313. setterContext
  6314. ) {
  6315. tupleRegistrations[rawTupleType].elements.push({
  6316. getterReturnType: getterReturnType,
  6317. getter: embind__requireFunction(getterSignature, getter),
  6318. getterContext: getterContext,
  6319. setterArgumentType: setterArgumentType,
  6320. setter: embind__requireFunction(setterSignature, setter),
  6321. setterContext: setterContext,
  6322. });
  6323. }
  6324. function __embind_register_value_object(
  6325. rawType,
  6326. name,
  6327. constructorSignature,
  6328. rawConstructor,
  6329. destructorSignature,
  6330. rawDestructor
  6331. ) {
  6332. structRegistrations[rawType] = {
  6333. name: readLatin1String(name),
  6334. rawConstructor: embind__requireFunction(constructorSignature, rawConstructor),
  6335. rawDestructor: embind__requireFunction(destructorSignature, rawDestructor),
  6336. fields: [],
  6337. };
  6338. }
  6339. function __embind_register_value_object_field(
  6340. structType,
  6341. fieldName,
  6342. getterReturnType,
  6343. getterSignature,
  6344. getter,
  6345. getterContext,
  6346. setterArgumentType,
  6347. setterSignature,
  6348. setter,
  6349. setterContext
  6350. ) {
  6351. structRegistrations[structType].fields.push({
  6352. fieldName: readLatin1String(fieldName),
  6353. getterReturnType: getterReturnType,
  6354. getter: embind__requireFunction(getterSignature, getter),
  6355. getterContext: getterContext,
  6356. setterArgumentType: setterArgumentType,
  6357. setter: embind__requireFunction(setterSignature, setter),
  6358. setterContext: setterContext,
  6359. });
  6360. }
  6361. function __embind_register_void(rawType, name) {
  6362. name = readLatin1String(name);
  6363. registerType(rawType, {
  6364. isVoid: true, // void return values can be optimized out sometimes
  6365. name: name,
  6366. 'argPackAdvance': 0,
  6367. 'fromWireType': function() {
  6368. return undefined;
  6369. },
  6370. 'toWireType': function(destructors, o) {
  6371. // TODO: assert if anything else is given?
  6372. return undefined;
  6373. },
  6374. });
  6375. }
  6376. var nowIsMonotonic = true;;
  6377. function __emscripten_get_now_is_monotonic() {
  6378. return nowIsMonotonic;
  6379. }
  6380. function __emval_as(handle, returnType, destructorsRef) {
  6381. handle = Emval.toValue(handle);
  6382. returnType = requireRegisteredType(returnType, 'emval::as');
  6383. var destructors = [];
  6384. var rd = Emval.toHandle(destructors);
  6385. HEAPU32[((destructorsRef)>>2)] = rd;
  6386. return returnType['toWireType'](destructors, handle);
  6387. }
  6388. function emval_allocateDestructors(destructorsRef) {
  6389. var destructors = [];
  6390. HEAPU32[((destructorsRef)>>2)] = Emval.toHandle(destructors);
  6391. return destructors;
  6392. }
  6393. var emval_symbols = {};
  6394. function getStringOrSymbol(address) {
  6395. var symbol = emval_symbols[address];
  6396. if (symbol === undefined) {
  6397. return readLatin1String(address);
  6398. }
  6399. return symbol;
  6400. }
  6401. var emval_methodCallers = [];
  6402. function __emval_call_method(caller, handle, methodName, destructorsRef, args) {
  6403. caller = emval_methodCallers[caller];
  6404. handle = Emval.toValue(handle);
  6405. methodName = getStringOrSymbol(methodName);
  6406. return caller(handle, methodName, emval_allocateDestructors(destructorsRef), args);
  6407. }
  6408. function __emval_call_void_method(caller, handle, methodName, args) {
  6409. caller = emval_methodCallers[caller];
  6410. handle = Emval.toValue(handle);
  6411. methodName = getStringOrSymbol(methodName);
  6412. caller(handle, methodName, null, args);
  6413. }
  6414. function __emval_equals(first, second) {
  6415. first = Emval.toValue(first);
  6416. second = Emval.toValue(second);
  6417. return first == second;
  6418. }
  6419. function emval_get_global() {
  6420. if (typeof globalThis == 'object') {
  6421. return globalThis;
  6422. }
  6423. return (function(){
  6424. return Function;
  6425. })()('return this')();
  6426. }
  6427. function __emval_get_global(name) {
  6428. if (name===0) {
  6429. return Emval.toHandle(emval_get_global());
  6430. } else {
  6431. name = getStringOrSymbol(name);
  6432. return Emval.toHandle(emval_get_global()[name]);
  6433. }
  6434. }
  6435. function emval_addMethodCaller(caller) {
  6436. var id = emval_methodCallers.length;
  6437. emval_methodCallers.push(caller);
  6438. return id;
  6439. }
  6440. function emval_lookupTypes(argCount, argTypes) {
  6441. var a = new Array(argCount);
  6442. for (var i = 0; i < argCount; ++i) {
  6443. a[i] = requireRegisteredType(HEAPU32[(((argTypes)+(i * POINTER_SIZE))>>2)],
  6444. "parameter " + i);
  6445. }
  6446. return a;
  6447. }
  6448. var emval_registeredMethods = [];
  6449. function __emval_get_method_caller(argCount, argTypes) {
  6450. var types = emval_lookupTypes(argCount, argTypes);
  6451. var retType = types[0];
  6452. var signatureName = retType.name + "_$" + types.slice(1).map(function (t) { return t.name; }).join("_") + "$";
  6453. var returnId = emval_registeredMethods[signatureName];
  6454. if (returnId !== undefined) {
  6455. return returnId;
  6456. }
  6457. var params = ["retType"];
  6458. var args = [retType];
  6459. var argsList = ""; // 'arg0, arg1, arg2, ... , argN'
  6460. for (var i = 0; i < argCount - 1; ++i) {
  6461. argsList += (i !== 0 ? ", " : "") + "arg" + i;
  6462. params.push("argType" + i);
  6463. args.push(types[1 + i]);
  6464. }
  6465. var functionName = makeLegalFunctionName("methodCaller_" + signatureName);
  6466. var functionBody =
  6467. "return function " + functionName + "(handle, name, destructors, args) {\n";
  6468. var offset = 0;
  6469. for (var i = 0; i < argCount - 1; ++i) {
  6470. functionBody +=
  6471. " var arg" + i + " = argType" + i + ".readValueFromPointer(args" + (offset ? ("+"+offset) : "") + ");\n";
  6472. offset += types[i + 1]['argPackAdvance'];
  6473. }
  6474. functionBody +=
  6475. " var rv = handle[name](" + argsList + ");\n";
  6476. for (var i = 0; i < argCount - 1; ++i) {
  6477. if (types[i + 1]['deleteObject']) {
  6478. functionBody +=
  6479. " argType" + i + ".deleteObject(arg" + i + ");\n";
  6480. }
  6481. }
  6482. if (!retType.isVoid) {
  6483. functionBody +=
  6484. " return retType.toWireType(destructors, rv);\n";
  6485. }
  6486. functionBody +=
  6487. "};\n";
  6488. params.push(functionBody);
  6489. var invokerFunction = new_(Function, params).apply(null, args);
  6490. returnId = emval_addMethodCaller(invokerFunction);
  6491. emval_registeredMethods[signatureName] = returnId;
  6492. return returnId;
  6493. }
  6494. function __emval_get_module_property(name) {
  6495. name = getStringOrSymbol(name);
  6496. return Emval.toHandle(Module[name]);
  6497. }
  6498. function __emval_get_property(handle, key) {
  6499. handle = Emval.toValue(handle);
  6500. key = Emval.toValue(key);
  6501. return Emval.toHandle(handle[key]);
  6502. }
  6503. function __emval_incref(handle) {
  6504. if (handle > 4) {
  6505. emval_handle_array[handle].refcount += 1;
  6506. }
  6507. }
  6508. function __emval_instanceof(object, constructor) {
  6509. object = Emval.toValue(object);
  6510. constructor = Emval.toValue(constructor);
  6511. return object instanceof constructor;
  6512. }
  6513. function __emval_is_number(handle) {
  6514. handle = Emval.toValue(handle);
  6515. return typeof handle == 'number';
  6516. }
  6517. function __emval_is_string(handle) {
  6518. handle = Emval.toValue(handle);
  6519. return typeof handle == 'string';
  6520. }
  6521. function craftEmvalAllocator(argCount) {
  6522. /*This function returns a new function that looks like this:
  6523. function emval_allocator_3(constructor, argTypes, args) {
  6524. var argType0 = requireRegisteredType(HEAP32[(argTypes >> 2)], "parameter 0");
  6525. var arg0 = argType0['readValueFromPointer'](args);
  6526. var argType1 = requireRegisteredType(HEAP32[(argTypes >> 2) + 1], "parameter 1");
  6527. var arg1 = argType1['readValueFromPointer'](args + 8);
  6528. var argType2 = requireRegisteredType(HEAP32[(argTypes >> 2) + 2], "parameter 2");
  6529. var arg2 = argType2['readValueFromPointer'](args + 16);
  6530. var obj = new constructor(arg0, arg1, arg2);
  6531. return Emval.toHandle(obj);
  6532. } */
  6533. var argsList = "";
  6534. for (var i = 0; i < argCount; ++i) {
  6535. argsList += (i!==0?", ":"")+"arg"+i; // 'arg0, arg1, ..., argn'
  6536. }
  6537. // The body of the generated function does not have access to enclosing
  6538. // scope where HEAPU64/HEAPU32/etc are defined, and we cannot pass them
  6539. // directly as arguments (like we do the Module object) since memory
  6540. // growth can cause them to be re-bound.
  6541. var getMemory = () => HEAPU32;
  6542. var functionBody =
  6543. "return function emval_allocator_"+argCount+"(constructor, argTypes, args) {\n" +
  6544. " var HEAPU32 = getMemory();\n";
  6545. for (var i = 0; i < argCount; ++i) {
  6546. functionBody +=
  6547. "var argType"+i+" = requireRegisteredType(HEAPU32[((argTypes)>>2)], 'parameter "+i+"');\n" +
  6548. "var arg"+i+" = argType"+i+".readValueFromPointer(args);\n" +
  6549. "args += argType"+i+"['argPackAdvance'];\n" +
  6550. "argTypes += 4;\n";
  6551. }
  6552. functionBody +=
  6553. "var obj = new constructor("+argsList+");\n" +
  6554. "return valueToHandle(obj);\n" +
  6555. "}\n";
  6556. /*jshint evil:true*/
  6557. return (new Function("requireRegisteredType", "Module", "valueToHandle", "getMemory" , functionBody))(
  6558. requireRegisteredType, Module, Emval.toHandle, getMemory);
  6559. }
  6560. var emval_newers = {};
  6561. function __emval_new(handle, argCount, argTypes, args) {
  6562. handle = Emval.toValue(handle);
  6563. var newer = emval_newers[argCount];
  6564. if (!newer) {
  6565. newer = craftEmvalAllocator(argCount);
  6566. emval_newers[argCount] = newer;
  6567. }
  6568. return newer(handle, argTypes, args);
  6569. }
  6570. function __emval_new_array() {
  6571. return Emval.toHandle([]);
  6572. }
  6573. function __emval_new_cstring(v) {
  6574. return Emval.toHandle(getStringOrSymbol(v));
  6575. }
  6576. function __emval_new_object() {
  6577. return Emval.toHandle({});
  6578. }
  6579. function __emval_run_destructors(handle) {
  6580. var destructors = Emval.toValue(handle);
  6581. runDestructors(destructors);
  6582. __emval_decref(handle);
  6583. }
  6584. function __emval_set_property(handle, key, value) {
  6585. handle = Emval.toValue(handle);
  6586. key = Emval.toValue(key);
  6587. value = Emval.toValue(value);
  6588. handle[key] = value;
  6589. }
  6590. function __emval_take_value(type, arg) {
  6591. type = requireRegisteredType(type, '_emval_take_value');
  6592. var v = type['readValueFromPointer'](arg);
  6593. return Emval.toHandle(v);
  6594. }
  6595. function readI53FromI64(ptr) {
  6596. return HEAPU32[ptr>>2] + HEAP32[ptr+4>>2] * 4294967296;
  6597. }
  6598. function __gmtime_js(time, tmPtr) {
  6599. var date = new Date(readI53FromI64(time)*1000);
  6600. HEAP32[((tmPtr)>>2)] = date.getUTCSeconds();
  6601. HEAP32[(((tmPtr)+(4))>>2)] = date.getUTCMinutes();
  6602. HEAP32[(((tmPtr)+(8))>>2)] = date.getUTCHours();
  6603. HEAP32[(((tmPtr)+(12))>>2)] = date.getUTCDate();
  6604. HEAP32[(((tmPtr)+(16))>>2)] = date.getUTCMonth();
  6605. HEAP32[(((tmPtr)+(20))>>2)] = date.getUTCFullYear()-1900;
  6606. HEAP32[(((tmPtr)+(24))>>2)] = date.getUTCDay();
  6607. var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
  6608. var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0;
  6609. HEAP32[(((tmPtr)+(28))>>2)] = yday;
  6610. }
  6611. function __isLeapYear(year) {
  6612. return year%4 === 0 && (year%100 !== 0 || year%400 === 0);
  6613. }
  6614. var __MONTH_DAYS_LEAP_CUMULATIVE = [0,31,60,91,121,152,182,213,244,274,305,335];
  6615. var __MONTH_DAYS_REGULAR_CUMULATIVE = [0,31,59,90,120,151,181,212,243,273,304,334];
  6616. function __yday_from_date(date) {
  6617. var isLeapYear = __isLeapYear(date.getFullYear());
  6618. var monthDaysCumulative = (isLeapYear ? __MONTH_DAYS_LEAP_CUMULATIVE : __MONTH_DAYS_REGULAR_CUMULATIVE);
  6619. var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1; // -1 since it's days since Jan 1
  6620. return yday;
  6621. }
  6622. function __localtime_js(time, tmPtr) {
  6623. var date = new Date(readI53FromI64(time)*1000);
  6624. HEAP32[((tmPtr)>>2)] = date.getSeconds();
  6625. HEAP32[(((tmPtr)+(4))>>2)] = date.getMinutes();
  6626. HEAP32[(((tmPtr)+(8))>>2)] = date.getHours();
  6627. HEAP32[(((tmPtr)+(12))>>2)] = date.getDate();
  6628. HEAP32[(((tmPtr)+(16))>>2)] = date.getMonth();
  6629. HEAP32[(((tmPtr)+(20))>>2)] = date.getFullYear()-1900;
  6630. HEAP32[(((tmPtr)+(24))>>2)] = date.getDay();
  6631. var yday = __yday_from_date(date)|0;
  6632. HEAP32[(((tmPtr)+(28))>>2)] = yday;
  6633. HEAP32[(((tmPtr)+(36))>>2)] = -(date.getTimezoneOffset() * 60);
  6634. // Attention: DST is in December in South, and some regions don't have DST at all.
  6635. var start = new Date(date.getFullYear(), 0, 1);
  6636. var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
  6637. var winterOffset = start.getTimezoneOffset();
  6638. var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0;
  6639. HEAP32[(((tmPtr)+(32))>>2)] = dst;
  6640. }
  6641. function __mktime_js(tmPtr) {
  6642. var date = new Date(HEAP32[(((tmPtr)+(20))>>2)] + 1900,
  6643. HEAP32[(((tmPtr)+(16))>>2)],
  6644. HEAP32[(((tmPtr)+(12))>>2)],
  6645. HEAP32[(((tmPtr)+(8))>>2)],
  6646. HEAP32[(((tmPtr)+(4))>>2)],
  6647. HEAP32[((tmPtr)>>2)],
  6648. 0);
  6649. // There's an ambiguous hour when the time goes back; the tm_isdst field is
  6650. // used to disambiguate it. Date() basically guesses, so we fix it up if it
  6651. // guessed wrong, or fill in tm_isdst with the guess if it's -1.
  6652. var dst = HEAP32[(((tmPtr)+(32))>>2)];
  6653. var guessedOffset = date.getTimezoneOffset();
  6654. var start = new Date(date.getFullYear(), 0, 1);
  6655. var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
  6656. var winterOffset = start.getTimezoneOffset();
  6657. var dstOffset = Math.min(winterOffset, summerOffset); // DST is in December in South
  6658. if (dst < 0) {
  6659. // Attention: some regions don't have DST at all.
  6660. HEAP32[(((tmPtr)+(32))>>2)] = Number(summerOffset != winterOffset && dstOffset == guessedOffset);
  6661. } else if ((dst > 0) != (dstOffset == guessedOffset)) {
  6662. var nonDstOffset = Math.max(winterOffset, summerOffset);
  6663. var trueOffset = dst > 0 ? dstOffset : nonDstOffset;
  6664. // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.
  6665. date.setTime(date.getTime() + (trueOffset - guessedOffset)*60000);
  6666. }
  6667. HEAP32[(((tmPtr)+(24))>>2)] = date.getDay();
  6668. var yday = __yday_from_date(date)|0;
  6669. HEAP32[(((tmPtr)+(28))>>2)] = yday;
  6670. // To match expected behavior, update fields from date
  6671. HEAP32[((tmPtr)>>2)] = date.getSeconds();
  6672. HEAP32[(((tmPtr)+(4))>>2)] = date.getMinutes();
  6673. HEAP32[(((tmPtr)+(8))>>2)] = date.getHours();
  6674. HEAP32[(((tmPtr)+(12))>>2)] = date.getDate();
  6675. HEAP32[(((tmPtr)+(16))>>2)] = date.getMonth();
  6676. HEAP32[(((tmPtr)+(20))>>2)] = date.getYear();
  6677. return (date.getTime() / 1000)|0;
  6678. }
  6679. function allocateUTF8(str) {
  6680. var size = lengthBytesUTF8(str) + 1;
  6681. var ret = _malloc(size);
  6682. if (ret) stringToUTF8Array(str, HEAP8, ret, size);
  6683. return ret;
  6684. }
  6685. function __tzset_js(timezone, daylight, tzname) {
  6686. // TODO: Use (malleable) environment variables instead of system settings.
  6687. var currentYear = new Date().getFullYear();
  6688. var winter = new Date(currentYear, 0, 1);
  6689. var summer = new Date(currentYear, 6, 1);
  6690. var winterOffset = winter.getTimezoneOffset();
  6691. var summerOffset = summer.getTimezoneOffset();
  6692. // Local standard timezone offset. Local standard time is not adjusted for daylight savings.
  6693. // This code uses the fact that getTimezoneOffset returns a greater value during Standard Time versus Daylight Saving Time (DST).
  6694. // Thus it determines the expected output during Standard Time, and it compares whether the output of the given date the same (Standard) or less (DST).
  6695. var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
  6696. // timezone is specified as seconds west of UTC ("The external variable
  6697. // `timezone` shall be set to the difference, in seconds, between
  6698. // Coordinated Universal Time (UTC) and local standard time."), the same
  6699. // as returned by stdTimezoneOffset.
  6700. // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html
  6701. HEAPU32[((timezone)>>2)] = stdTimezoneOffset * 60;
  6702. HEAP32[((daylight)>>2)] = Number(winterOffset != summerOffset);
  6703. function extractZone(date) {
  6704. var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
  6705. return match ? match[1] : "GMT";
  6706. };
  6707. var winterName = extractZone(winter);
  6708. var summerName = extractZone(summer);
  6709. var winterNamePtr = allocateUTF8(winterName);
  6710. var summerNamePtr = allocateUTF8(summerName);
  6711. if (summerOffset < winterOffset) {
  6712. // Northern hemisphere
  6713. HEAPU32[((tzname)>>2)] = winterNamePtr;
  6714. HEAPU32[(((tzname)+(4))>>2)] = summerNamePtr;
  6715. } else {
  6716. HEAPU32[((tzname)>>2)] = summerNamePtr;
  6717. HEAPU32[(((tzname)+(4))>>2)] = winterNamePtr;
  6718. }
  6719. }
  6720. function _abort() {
  6721. abort('native code called abort()');
  6722. }
  6723. function _emscripten_console_error(str) {
  6724. assert(typeof str == 'number');
  6725. console.error(UTF8ToString(str));
  6726. }
  6727. function _emscripten_date_now() {
  6728. return Date.now();
  6729. }
  6730. function getHeapMax() {
  6731. // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
  6732. // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
  6733. // for any code that deals with heap sizes, which would require special
  6734. // casing all heap size related code to treat 0 specially.
  6735. return 2147483648;
  6736. }
  6737. function _emscripten_get_heap_max() {
  6738. return getHeapMax();
  6739. }
  6740. var _emscripten_get_now;if (ENVIRONMENT_IS_NODE) {
  6741. _emscripten_get_now = () => {
  6742. var t = process['hrtime']();
  6743. return t[0] * 1e3 + t[1] / 1e6;
  6744. };
  6745. } else _emscripten_get_now = () => performance.now();
  6746. ;
  6747. function _emscripten_memcpy_big(dest, src, num) {
  6748. HEAPU8.copyWithin(dest, src, src + num);
  6749. }
  6750. function emscripten_realloc_buffer(size) {
  6751. var b = wasmMemory.buffer;
  6752. try {
  6753. // round size grow request up to wasm page size (fixed 64KB per spec)
  6754. wasmMemory.grow((size - b.byteLength + 65535) >>> 16); // .grow() takes a delta compared to the previous size
  6755. updateMemoryViews();
  6756. return 1 /*success*/;
  6757. } catch(e) {
  6758. err('emscripten_realloc_buffer: Attempted to grow heap from ' + b.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e);
  6759. }
  6760. // implicit 0 return to save code size (caller will cast "undefined" into 0
  6761. // anyhow)
  6762. }
  6763. function _emscripten_resize_heap(requestedSize) {
  6764. var oldSize = HEAPU8.length;
  6765. requestedSize = requestedSize >>> 0;
  6766. // With multithreaded builds, races can happen (another thread might increase the size
  6767. // in between), so return a failure, and let the caller retry.
  6768. assert(requestedSize > oldSize);
  6769. // Memory resize rules:
  6770. // 1. Always increase heap size to at least the requested size, rounded up
  6771. // to next page multiple.
  6772. // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap
  6773. // geometrically: increase the heap size according to
  6774. // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most
  6775. // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
  6776. // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap
  6777. // linearly: increase the heap size by at least
  6778. // MEMORY_GROWTH_LINEAR_STEP bytes.
  6779. // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by
  6780. // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
  6781. // 4. If we were unable to allocate as much memory, it may be due to
  6782. // over-eager decision to excessively reserve due to (3) above.
  6783. // Hence if an allocation fails, cut down on the amount of excess
  6784. // growth, in an attempt to succeed to perform a smaller allocation.
  6785. // A limit is set for how much we can grow. We should not exceed that
  6786. // (the wasm binary specifies it, so if we tried, we'd fail anyhow).
  6787. var maxHeapSize = getHeapMax();
  6788. if (requestedSize > maxHeapSize) {
  6789. err('Cannot enlarge memory, asked to go up to ' + requestedSize + ' bytes, but the limit is ' + maxHeapSize + ' bytes!');
  6790. return false;
  6791. }
  6792. let alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple;
  6793. // Loop through potential heap size increases. If we attempt a too eager
  6794. // reservation that fails, cut down on the attempted size and reserve a
  6795. // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
  6796. for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
  6797. var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); // ensure geometric growth
  6798. // but limit overreserving (default to capping at +96MB overgrowth at most)
  6799. overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 );
  6800. var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
  6801. var replacement = emscripten_realloc_buffer(newSize);
  6802. if (replacement) {
  6803. return true;
  6804. }
  6805. }
  6806. err('Failed to grow the heap from ' + oldSize + ' bytes to ' + newSize + ' bytes, not enough memory!');
  6807. return false;
  6808. }
  6809. var ENV = {};
  6810. function getExecutableName() {
  6811. return thisProgram || './this.program';
  6812. }
  6813. function getEnvStrings() {
  6814. if (!getEnvStrings.strings) {
  6815. // Default values.
  6816. // Browser language detection #8751
  6817. var lang = ((typeof navigator == 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8';
  6818. var env = {
  6819. 'USER': 'web_user',
  6820. 'LOGNAME': 'web_user',
  6821. 'PATH': '/',
  6822. 'PWD': '/',
  6823. 'HOME': '/home/web_user',
  6824. 'LANG': lang,
  6825. '_': getExecutableName()
  6826. };
  6827. // Apply the user-provided values, if any.
  6828. for (var x in ENV) {
  6829. // x is a key in ENV; if ENV[x] is undefined, that means it was
  6830. // explicitly set to be so. We allow user code to do that to
  6831. // force variables with default values to remain unset.
  6832. if (ENV[x] === undefined) delete env[x];
  6833. else env[x] = ENV[x];
  6834. }
  6835. var strings = [];
  6836. for (var x in env) {
  6837. strings.push(x + '=' + env[x]);
  6838. }
  6839. getEnvStrings.strings = strings;
  6840. }
  6841. return getEnvStrings.strings;
  6842. }
  6843. /** @param {boolean=} dontAddNull */
  6844. function writeAsciiToMemory(str, buffer, dontAddNull) {
  6845. for (var i = 0; i < str.length; ++i) {
  6846. assert(str.charCodeAt(i) === (str.charCodeAt(i) & 0xff));
  6847. HEAP8[((buffer++)>>0)] = str.charCodeAt(i);
  6848. }
  6849. // Null-terminate the pointer to the HEAP.
  6850. if (!dontAddNull) HEAP8[((buffer)>>0)] = 0;
  6851. }
  6852. function _environ_get(__environ, environ_buf) {
  6853. var bufSize = 0;
  6854. getEnvStrings().forEach(function(string, i) {
  6855. var ptr = environ_buf + bufSize;
  6856. HEAPU32[(((__environ)+(i*4))>>2)] = ptr;
  6857. writeAsciiToMemory(string, ptr);
  6858. bufSize += string.length + 1;
  6859. });
  6860. return 0;
  6861. }
  6862. function _environ_sizes_get(penviron_count, penviron_buf_size) {
  6863. var strings = getEnvStrings();
  6864. HEAPU32[((penviron_count)>>2)] = strings.length;
  6865. var bufSize = 0;
  6866. strings.forEach(function(string) {
  6867. bufSize += string.length + 1;
  6868. });
  6869. HEAPU32[((penviron_buf_size)>>2)] = bufSize;
  6870. return 0;
  6871. }
  6872. function _proc_exit(code) {
  6873. EXITSTATUS = code;
  6874. if (!keepRuntimeAlive()) {
  6875. if (Module['onExit']) Module['onExit'](code);
  6876. ABORT = true;
  6877. }
  6878. quit_(code, new ExitStatus(code));
  6879. }
  6880. /** @param {boolean|number=} implicit */
  6881. function exitJS(status, implicit) {
  6882. EXITSTATUS = status;
  6883. checkUnflushedContent();
  6884. // if exit() was called explicitly, warn the user if the runtime isn't actually being shut down
  6885. if (keepRuntimeAlive() && !implicit) {
  6886. var msg = 'program exited (with status: ' + status + '), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)';
  6887. readyPromiseReject(msg);
  6888. err(msg);
  6889. }
  6890. _proc_exit(status);
  6891. }
  6892. var _exit = exitJS;
  6893. function _fd_close(fd) {
  6894. try {
  6895. var stream = SYSCALLS.getStreamFromFD(fd);
  6896. FS.close(stream);
  6897. return 0;
  6898. } catch (e) {
  6899. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  6900. return e.errno;
  6901. }
  6902. }
  6903. /** @param {number=} offset */
  6904. function doReadv(stream, iov, iovcnt, offset) {
  6905. var ret = 0;
  6906. for (var i = 0; i < iovcnt; i++) {
  6907. var ptr = HEAPU32[((iov)>>2)];
  6908. var len = HEAPU32[(((iov)+(4))>>2)];
  6909. iov += 8;
  6910. var curr = FS.read(stream, HEAP8,ptr, len, offset);
  6911. if (curr < 0) return -1;
  6912. ret += curr;
  6913. if (curr < len) break; // nothing more to read
  6914. if (typeof offset !== 'undefined') {
  6915. offset += curr;
  6916. }
  6917. }
  6918. return ret;
  6919. }
  6920. function _fd_read(fd, iov, iovcnt, pnum) {
  6921. try {
  6922. var stream = SYSCALLS.getStreamFromFD(fd);
  6923. var num = doReadv(stream, iov, iovcnt);
  6924. HEAPU32[((pnum)>>2)] = num;
  6925. return 0;
  6926. } catch (e) {
  6927. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  6928. return e.errno;
  6929. }
  6930. }
  6931. function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
  6932. try {
  6933. var offset = convertI32PairToI53Checked(offset_low, offset_high); if (isNaN(offset)) return 61;
  6934. var stream = SYSCALLS.getStreamFromFD(fd);
  6935. FS.llseek(stream, offset, whence);
  6936. (tempI64 = [stream.position>>>0,(tempDouble=stream.position,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((newOffset)>>2)] = tempI64[0],HEAP32[(((newOffset)+(4))>>2)] = tempI64[1]);
  6937. if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
  6938. return 0;
  6939. } catch (e) {
  6940. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  6941. return e.errno;
  6942. }
  6943. }
  6944. /** @param {number=} offset */
  6945. function doWritev(stream, iov, iovcnt, offset) {
  6946. var ret = 0;
  6947. for (var i = 0; i < iovcnt; i++) {
  6948. var ptr = HEAPU32[((iov)>>2)];
  6949. var len = HEAPU32[(((iov)+(4))>>2)];
  6950. iov += 8;
  6951. var curr = FS.write(stream, HEAP8,ptr, len, offset);
  6952. if (curr < 0) return -1;
  6953. ret += curr;
  6954. if (typeof offset !== 'undefined') {
  6955. offset += curr;
  6956. }
  6957. }
  6958. return ret;
  6959. }
  6960. function _fd_write(fd, iov, iovcnt, pnum) {
  6961. try {
  6962. var stream = SYSCALLS.getStreamFromFD(fd);
  6963. var num = doWritev(stream, iov, iovcnt);
  6964. HEAPU32[((pnum)>>2)] = num;
  6965. return 0;
  6966. } catch (e) {
  6967. if (typeof FS == 'undefined' || !(e instanceof FS.ErrnoError)) throw e;
  6968. return e.errno;
  6969. }
  6970. }
  6971. var FSNode = /** @constructor */ function(parent, name, mode, rdev) {
  6972. if (!parent) {
  6973. parent = this; // root node sets parent to itself
  6974. }
  6975. this.parent = parent;
  6976. this.mount = parent.mount;
  6977. this.mounted = null;
  6978. this.id = FS.nextInode++;
  6979. this.name = name;
  6980. this.mode = mode;
  6981. this.node_ops = {};
  6982. this.stream_ops = {};
  6983. this.rdev = rdev;
  6984. };
  6985. var readMode = 292/*292*/ | 73/*73*/;
  6986. var writeMode = 146/*146*/;
  6987. Object.defineProperties(FSNode.prototype, {
  6988. read: {
  6989. get: /** @this{FSNode} */function() {
  6990. return (this.mode & readMode) === readMode;
  6991. },
  6992. set: /** @this{FSNode} */function(val) {
  6993. val ? this.mode |= readMode : this.mode &= ~readMode;
  6994. }
  6995. },
  6996. write: {
  6997. get: /** @this{FSNode} */function() {
  6998. return (this.mode & writeMode) === writeMode;
  6999. },
  7000. set: /** @this{FSNode} */function(val) {
  7001. val ? this.mode |= writeMode : this.mode &= ~writeMode;
  7002. }
  7003. },
  7004. isFolder: {
  7005. get: /** @this{FSNode} */function() {
  7006. return FS.isDir(this.mode);
  7007. }
  7008. },
  7009. isDevice: {
  7010. get: /** @this{FSNode} */function() {
  7011. return FS.isChrdev(this.mode);
  7012. }
  7013. }
  7014. });
  7015. FS.FSNode = FSNode;
  7016. FS.staticInit();;
  7017. ERRNO_CODES = {
  7018. 'EPERM': 63,
  7019. 'ENOENT': 44,
  7020. 'ESRCH': 71,
  7021. 'EINTR': 27,
  7022. 'EIO': 29,
  7023. 'ENXIO': 60,
  7024. 'E2BIG': 1,
  7025. 'ENOEXEC': 45,
  7026. 'EBADF': 8,
  7027. 'ECHILD': 12,
  7028. 'EAGAIN': 6,
  7029. 'EWOULDBLOCK': 6,
  7030. 'ENOMEM': 48,
  7031. 'EACCES': 2,
  7032. 'EFAULT': 21,
  7033. 'ENOTBLK': 105,
  7034. 'EBUSY': 10,
  7035. 'EEXIST': 20,
  7036. 'EXDEV': 75,
  7037. 'ENODEV': 43,
  7038. 'ENOTDIR': 54,
  7039. 'EISDIR': 31,
  7040. 'EINVAL': 28,
  7041. 'ENFILE': 41,
  7042. 'EMFILE': 33,
  7043. 'ENOTTY': 59,
  7044. 'ETXTBSY': 74,
  7045. 'EFBIG': 22,
  7046. 'ENOSPC': 51,
  7047. 'ESPIPE': 70,
  7048. 'EROFS': 69,
  7049. 'EMLINK': 34,
  7050. 'EPIPE': 64,
  7051. 'EDOM': 18,
  7052. 'ERANGE': 68,
  7053. 'ENOMSG': 49,
  7054. 'EIDRM': 24,
  7055. 'ECHRNG': 106,
  7056. 'EL2NSYNC': 156,
  7057. 'EL3HLT': 107,
  7058. 'EL3RST': 108,
  7059. 'ELNRNG': 109,
  7060. 'EUNATCH': 110,
  7061. 'ENOCSI': 111,
  7062. 'EL2HLT': 112,
  7063. 'EDEADLK': 16,
  7064. 'ENOLCK': 46,
  7065. 'EBADE': 113,
  7066. 'EBADR': 114,
  7067. 'EXFULL': 115,
  7068. 'ENOANO': 104,
  7069. 'EBADRQC': 103,
  7070. 'EBADSLT': 102,
  7071. 'EDEADLOCK': 16,
  7072. 'EBFONT': 101,
  7073. 'ENOSTR': 100,
  7074. 'ENODATA': 116,
  7075. 'ETIME': 117,
  7076. 'ENOSR': 118,
  7077. 'ENONET': 119,
  7078. 'ENOPKG': 120,
  7079. 'EREMOTE': 121,
  7080. 'ENOLINK': 47,
  7081. 'EADV': 122,
  7082. 'ESRMNT': 123,
  7083. 'ECOMM': 124,
  7084. 'EPROTO': 65,
  7085. 'EMULTIHOP': 36,
  7086. 'EDOTDOT': 125,
  7087. 'EBADMSG': 9,
  7088. 'ENOTUNIQ': 126,
  7089. 'EBADFD': 127,
  7090. 'EREMCHG': 128,
  7091. 'ELIBACC': 129,
  7092. 'ELIBBAD': 130,
  7093. 'ELIBSCN': 131,
  7094. 'ELIBMAX': 132,
  7095. 'ELIBEXEC': 133,
  7096. 'ENOSYS': 52,
  7097. 'ENOTEMPTY': 55,
  7098. 'ENAMETOOLONG': 37,
  7099. 'ELOOP': 32,
  7100. 'EOPNOTSUPP': 138,
  7101. 'EPFNOSUPPORT': 139,
  7102. 'ECONNRESET': 15,
  7103. 'ENOBUFS': 42,
  7104. 'EAFNOSUPPORT': 5,
  7105. 'EPROTOTYPE': 67,
  7106. 'ENOTSOCK': 57,
  7107. 'ENOPROTOOPT': 50,
  7108. 'ESHUTDOWN': 140,
  7109. 'ECONNREFUSED': 14,
  7110. 'EADDRINUSE': 3,
  7111. 'ECONNABORTED': 13,
  7112. 'ENETUNREACH': 40,
  7113. 'ENETDOWN': 38,
  7114. 'ETIMEDOUT': 73,
  7115. 'EHOSTDOWN': 142,
  7116. 'EHOSTUNREACH': 23,
  7117. 'EINPROGRESS': 26,
  7118. 'EALREADY': 7,
  7119. 'EDESTADDRREQ': 17,
  7120. 'EMSGSIZE': 35,
  7121. 'EPROTONOSUPPORT': 66,
  7122. 'ESOCKTNOSUPPORT': 137,
  7123. 'EADDRNOTAVAIL': 4,
  7124. 'ENETRESET': 39,
  7125. 'EISCONN': 30,
  7126. 'ENOTCONN': 53,
  7127. 'ETOOMANYREFS': 141,
  7128. 'EUSERS': 136,
  7129. 'EDQUOT': 19,
  7130. 'ESTALE': 72,
  7131. 'ENOTSUP': 138,
  7132. 'ENOMEDIUM': 148,
  7133. 'EILSEQ': 25,
  7134. 'EOVERFLOW': 61,
  7135. 'ECANCELED': 11,
  7136. 'ENOTRECOVERABLE': 56,
  7137. 'EOWNERDEAD': 62,
  7138. 'ESTRPIPE': 135,
  7139. };;
  7140. InternalError = Module['InternalError'] = extendError(Error, 'InternalError');;
  7141. embind_init_charCodes();
  7142. BindingError = Module['BindingError'] = extendError(Error, 'BindingError');;
  7143. init_ClassHandle();
  7144. init_embind();;
  7145. init_RegisteredPointer();
  7146. UnboundTypeError = Module['UnboundTypeError'] = extendError(Error, 'UnboundTypeError');;
  7147. init_emval();;
  7148. var ASSERTIONS = true;
  7149. function checkIncomingModuleAPI() {
  7150. ignoredModuleProp('fetchSettings');
  7151. }
  7152. var asmLibraryArg = {
  7153. "__assert_fail": ___assert_fail,
  7154. "__cxa_throw": ___cxa_throw,
  7155. "__syscall_connect": ___syscall_connect,
  7156. "__syscall_faccessat": ___syscall_faccessat,
  7157. "__syscall_fcntl64": ___syscall_fcntl64,
  7158. "__syscall_fstat64": ___syscall_fstat64,
  7159. "__syscall_ftruncate64": ___syscall_ftruncate64,
  7160. "__syscall_ioctl": ___syscall_ioctl,
  7161. "__syscall_lstat64": ___syscall_lstat64,
  7162. "__syscall_newfstatat": ___syscall_newfstatat,
  7163. "__syscall_openat": ___syscall_openat,
  7164. "__syscall_socket": ___syscall_socket,
  7165. "__syscall_stat64": ___syscall_stat64,
  7166. "_embind_finalize_value_array": __embind_finalize_value_array,
  7167. "_embind_finalize_value_object": __embind_finalize_value_object,
  7168. "_embind_register_bigint": __embind_register_bigint,
  7169. "_embind_register_bool": __embind_register_bool,
  7170. "_embind_register_class": __embind_register_class,
  7171. "_embind_register_class_class_function": __embind_register_class_class_function,
  7172. "_embind_register_class_constructor": __embind_register_class_constructor,
  7173. "_embind_register_class_function": __embind_register_class_function,
  7174. "_embind_register_class_property": __embind_register_class_property,
  7175. "_embind_register_emval": __embind_register_emval,
  7176. "_embind_register_enum": __embind_register_enum,
  7177. "_embind_register_enum_value": __embind_register_enum_value,
  7178. "_embind_register_float": __embind_register_float,
  7179. "_embind_register_integer": __embind_register_integer,
  7180. "_embind_register_memory_view": __embind_register_memory_view,
  7181. "_embind_register_std_string": __embind_register_std_string,
  7182. "_embind_register_std_wstring": __embind_register_std_wstring,
  7183. "_embind_register_value_array": __embind_register_value_array,
  7184. "_embind_register_value_array_element": __embind_register_value_array_element,
  7185. "_embind_register_value_object": __embind_register_value_object,
  7186. "_embind_register_value_object_field": __embind_register_value_object_field,
  7187. "_embind_register_void": __embind_register_void,
  7188. "_emscripten_get_now_is_monotonic": __emscripten_get_now_is_monotonic,
  7189. "_emval_as": __emval_as,
  7190. "_emval_call_method": __emval_call_method,
  7191. "_emval_call_void_method": __emval_call_void_method,
  7192. "_emval_decref": __emval_decref,
  7193. "_emval_equals": __emval_equals,
  7194. "_emval_get_global": __emval_get_global,
  7195. "_emval_get_method_caller": __emval_get_method_caller,
  7196. "_emval_get_module_property": __emval_get_module_property,
  7197. "_emval_get_property": __emval_get_property,
  7198. "_emval_incref": __emval_incref,
  7199. "_emval_instanceof": __emval_instanceof,
  7200. "_emval_is_number": __emval_is_number,
  7201. "_emval_is_string": __emval_is_string,
  7202. "_emval_new": __emval_new,
  7203. "_emval_new_array": __emval_new_array,
  7204. "_emval_new_cstring": __emval_new_cstring,
  7205. "_emval_new_object": __emval_new_object,
  7206. "_emval_run_destructors": __emval_run_destructors,
  7207. "_emval_set_property": __emval_set_property,
  7208. "_emval_take_value": __emval_take_value,
  7209. "_gmtime_js": __gmtime_js,
  7210. "_localtime_js": __localtime_js,
  7211. "_mktime_js": __mktime_js,
  7212. "_tzset_js": __tzset_js,
  7213. "abort": _abort,
  7214. "emscripten_console_error": _emscripten_console_error,
  7215. "emscripten_date_now": _emscripten_date_now,
  7216. "emscripten_get_heap_max": _emscripten_get_heap_max,
  7217. "emscripten_get_now": _emscripten_get_now,
  7218. "emscripten_memcpy_big": _emscripten_memcpy_big,
  7219. "emscripten_resize_heap": _emscripten_resize_heap,
  7220. "environ_get": _environ_get,
  7221. "environ_sizes_get": _environ_sizes_get,
  7222. "exit": _exit,
  7223. "fd_close": _fd_close,
  7224. "fd_read": _fd_read,
  7225. "fd_seek": _fd_seek,
  7226. "fd_write": _fd_write
  7227. };
  7228. var asm = createWasm();
  7229. /** @type {function(...*):?} */
  7230. var ___wasm_call_ctors = Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors");
  7231. /** @type {function(...*):?} */
  7232. var _malloc = Module["_malloc"] = createExportWrapper("malloc");
  7233. /** @type {function(...*):?} */
  7234. var _fflush = Module["_fflush"] = createExportWrapper("fflush");
  7235. /** @type {function(...*):?} */
  7236. var _free = Module["_free"] = createExportWrapper("free");
  7237. /** @type {function(...*):?} */
  7238. var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location");
  7239. /** @type {function(...*):?} */
  7240. var ___getTypeName = Module["___getTypeName"] = createExportWrapper("__getTypeName");
  7241. /** @type {function(...*):?} */
  7242. var __embind_initialize_bindings = Module["__embind_initialize_bindings"] = createExportWrapper("_embind_initialize_bindings");
  7243. /** @type {function(...*):?} */
  7244. var _htons = Module["_htons"] = createExportWrapper("htons");
  7245. /** @type {function(...*):?} */
  7246. var _ntohs = Module["_ntohs"] = createExportWrapper("ntohs");
  7247. /** @type {function(...*):?} */
  7248. var _emscripten_stack_init = Module["_emscripten_stack_init"] = function() {
  7249. return (_emscripten_stack_init = Module["_emscripten_stack_init"] = Module["asm"]["emscripten_stack_init"]).apply(null, arguments);
  7250. };
  7251. /** @type {function(...*):?} */
  7252. var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() {
  7253. return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments);
  7254. };
  7255. /** @type {function(...*):?} */
  7256. var _emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = function() {
  7257. return (_emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = Module["asm"]["emscripten_stack_get_base"]).apply(null, arguments);
  7258. };
  7259. /** @type {function(...*):?} */
  7260. var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() {
  7261. return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments);
  7262. };
  7263. /** @type {function(...*):?} */
  7264. var stackSave = Module["stackSave"] = createExportWrapper("stackSave");
  7265. /** @type {function(...*):?} */
  7266. var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore");
  7267. /** @type {function(...*):?} */
  7268. var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc");
  7269. /** @type {function(...*):?} */
  7270. var _emscripten_stack_get_current = Module["_emscripten_stack_get_current"] = function() {
  7271. return (_emscripten_stack_get_current = Module["_emscripten_stack_get_current"] = Module["asm"]["emscripten_stack_get_current"]).apply(null, arguments);
  7272. };
  7273. /** @type {function(...*):?} */
  7274. var ___cxa_is_pointer_type = Module["___cxa_is_pointer_type"] = createExportWrapper("__cxa_is_pointer_type");
  7275. /** @type {function(...*):?} */
  7276. var dynCall_ji = Module["dynCall_ji"] = createExportWrapper("dynCall_ji");
  7277. /** @type {function(...*):?} */
  7278. var dynCall_iiijii = Module["dynCall_iiijii"] = createExportWrapper("dynCall_iiijii");
  7279. /** @type {function(...*):?} */
  7280. var dynCall_iij = Module["dynCall_iij"] = createExportWrapper("dynCall_iij");
  7281. /** @type {function(...*):?} */
  7282. var dynCall_vij = Module["dynCall_vij"] = createExportWrapper("dynCall_vij");
  7283. /** @type {function(...*):?} */
  7284. var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji");
  7285. // === Auto-generated postamble setup entry stuff ===
  7286. var unexportedRuntimeSymbols = [
  7287. 'run',
  7288. 'UTF8ArrayToString',
  7289. 'UTF8ToString',
  7290. 'stringToUTF8Array',
  7291. 'stringToUTF8',
  7292. 'lengthBytesUTF8',
  7293. 'addOnPreRun',
  7294. 'addOnInit',
  7295. 'addOnPreMain',
  7296. 'addOnExit',
  7297. 'addOnPostRun',
  7298. 'addRunDependency',
  7299. 'removeRunDependency',
  7300. 'FS_createFolder',
  7301. 'FS_createPath',
  7302. 'FS_createDataFile',
  7303. 'FS_createPreloadedFile',
  7304. 'FS_createLazyFile',
  7305. 'FS_createLink',
  7306. 'FS_createDevice',
  7307. 'FS_unlink',
  7308. 'getLEB',
  7309. 'getFunctionTables',
  7310. 'alignFunctionTables',
  7311. 'registerFunctions',
  7312. 'prettyPrint',
  7313. 'getCompilerSetting',
  7314. 'out',
  7315. 'err',
  7316. 'callMain',
  7317. 'abort',
  7318. 'keepRuntimeAlive',
  7319. 'wasmMemory',
  7320. 'stackAlloc',
  7321. 'stackSave',
  7322. 'stackRestore',
  7323. 'getTempRet0',
  7324. 'setTempRet0',
  7325. 'writeStackCookie',
  7326. 'checkStackCookie',
  7327. 'ptrToString',
  7328. 'zeroMemory',
  7329. 'stringToNewUTF8',
  7330. 'exitJS',
  7331. 'getHeapMax',
  7332. 'emscripten_realloc_buffer',
  7333. 'ENV',
  7334. 'ERRNO_CODES',
  7335. 'ERRNO_MESSAGES',
  7336. 'setErrNo',
  7337. 'inetPton4',
  7338. 'inetNtop4',
  7339. 'inetPton6',
  7340. 'inetNtop6',
  7341. 'readSockaddr',
  7342. 'writeSockaddr',
  7343. 'DNS',
  7344. 'getHostByName',
  7345. 'Protocols',
  7346. 'Sockets',
  7347. 'getRandomDevice',
  7348. 'warnOnce',
  7349. 'traverseStack',
  7350. 'UNWIND_CACHE',
  7351. 'convertPCtoSourceLocation',
  7352. 'readEmAsmArgsArray',
  7353. 'readEmAsmArgs',
  7354. 'runEmAsmFunction',
  7355. 'runMainThreadEmAsm',
  7356. 'jstoi_q',
  7357. 'jstoi_s',
  7358. 'getExecutableName',
  7359. 'listenOnce',
  7360. 'autoResumeAudioContext',
  7361. 'dynCallLegacy',
  7362. 'getDynCaller',
  7363. 'dynCall',
  7364. 'handleException',
  7365. 'runtimeKeepalivePush',
  7366. 'runtimeKeepalivePop',
  7367. 'callUserCallback',
  7368. 'maybeExit',
  7369. 'safeSetTimeout',
  7370. 'asmjsMangle',
  7371. 'asyncLoad',
  7372. 'alignMemory',
  7373. 'mmapAlloc',
  7374. 'handleAllocator',
  7375. 'writeI53ToI64',
  7376. 'writeI53ToI64Clamped',
  7377. 'writeI53ToI64Signaling',
  7378. 'writeI53ToU64Clamped',
  7379. 'writeI53ToU64Signaling',
  7380. 'readI53FromI64',
  7381. 'readI53FromU64',
  7382. 'convertI32PairToI53',
  7383. 'convertI32PairToI53Checked',
  7384. 'convertU32PairToI53',
  7385. 'getCFunc',
  7386. 'ccall',
  7387. 'cwrap',
  7388. 'uleb128Encode',
  7389. 'sigToWasmTypes',
  7390. 'generateFuncType',
  7391. 'convertJsFunctionToWasm',
  7392. 'freeTableIndexes',
  7393. 'functionsInTableMap',
  7394. 'getEmptyTableSlot',
  7395. 'updateTableMap',
  7396. 'addFunction',
  7397. 'removeFunction',
  7398. 'reallyNegative',
  7399. 'unSign',
  7400. 'strLen',
  7401. 'reSign',
  7402. 'formatString',
  7403. 'setValue',
  7404. 'getValue',
  7405. 'PATH',
  7406. 'PATH_FS',
  7407. 'intArrayFromString',
  7408. 'intArrayToString',
  7409. 'AsciiToString',
  7410. 'stringToAscii',
  7411. 'UTF16Decoder',
  7412. 'UTF16ToString',
  7413. 'stringToUTF16',
  7414. 'lengthBytesUTF16',
  7415. 'UTF32ToString',
  7416. 'stringToUTF32',
  7417. 'lengthBytesUTF32',
  7418. 'allocateUTF8',
  7419. 'allocateUTF8OnStack',
  7420. 'writeStringToMemory',
  7421. 'writeArrayToMemory',
  7422. 'writeAsciiToMemory',
  7423. 'SYSCALLS',
  7424. 'getSocketFromFD',
  7425. 'getSocketAddress',
  7426. 'JSEvents',
  7427. 'registerKeyEventCallback',
  7428. 'specialHTMLTargets',
  7429. 'maybeCStringToJsString',
  7430. 'findEventTarget',
  7431. 'findCanvasEventTarget',
  7432. 'getBoundingClientRect',
  7433. 'fillMouseEventData',
  7434. 'registerMouseEventCallback',
  7435. 'registerWheelEventCallback',
  7436. 'registerUiEventCallback',
  7437. 'registerFocusEventCallback',
  7438. 'fillDeviceOrientationEventData',
  7439. 'registerDeviceOrientationEventCallback',
  7440. 'fillDeviceMotionEventData',
  7441. 'registerDeviceMotionEventCallback',
  7442. 'screenOrientation',
  7443. 'fillOrientationChangeEventData',
  7444. 'registerOrientationChangeEventCallback',
  7445. 'fillFullscreenChangeEventData',
  7446. 'registerFullscreenChangeEventCallback',
  7447. 'JSEvents_requestFullscreen',
  7448. 'JSEvents_resizeCanvasForFullscreen',
  7449. 'registerRestoreOldStyle',
  7450. 'hideEverythingExceptGivenElement',
  7451. 'restoreHiddenElements',
  7452. 'setLetterbox',
  7453. 'currentFullscreenStrategy',
  7454. 'restoreOldWindowedStyle',
  7455. 'softFullscreenResizeWebGLRenderTarget',
  7456. 'doRequestFullscreen',
  7457. 'fillPointerlockChangeEventData',
  7458. 'registerPointerlockChangeEventCallback',
  7459. 'registerPointerlockErrorEventCallback',
  7460. 'requestPointerLock',
  7461. 'fillVisibilityChangeEventData',
  7462. 'registerVisibilityChangeEventCallback',
  7463. 'registerTouchEventCallback',
  7464. 'fillGamepadEventData',
  7465. 'registerGamepadEventCallback',
  7466. 'registerBeforeUnloadEventCallback',
  7467. 'fillBatteryEventData',
  7468. 'battery',
  7469. 'registerBatteryEventCallback',
  7470. 'setCanvasElementSize',
  7471. 'getCanvasElementSize',
  7472. 'demangle',
  7473. 'demangleAll',
  7474. 'jsStackTrace',
  7475. 'stackTrace',
  7476. 'ExitStatus',
  7477. 'getEnvStrings',
  7478. 'checkWasiClock',
  7479. 'doReadv',
  7480. 'doWritev',
  7481. 'dlopenMissingError',
  7482. 'createDyncallWrapper',
  7483. 'setImmediateWrapped',
  7484. 'clearImmediateWrapped',
  7485. 'polyfillSetImmediate',
  7486. 'promiseMap',
  7487. 'newNativePromise',
  7488. 'getPromise',
  7489. 'uncaughtExceptionCount',
  7490. 'exceptionLast',
  7491. 'exceptionCaught',
  7492. 'ExceptionInfo',
  7493. 'exception_addRef',
  7494. 'exception_decRef',
  7495. 'Browser',
  7496. 'setMainLoop',
  7497. 'wget',
  7498. 'FS',
  7499. 'MEMFS',
  7500. 'TTY',
  7501. 'PIPEFS',
  7502. 'SOCKFS',
  7503. '_setNetworkCallback',
  7504. 'tempFixedLengthArray',
  7505. 'miniTempWebGLFloatBuffers',
  7506. 'heapObjectForWebGLType',
  7507. 'heapAccessShiftForWebGLHeap',
  7508. 'GL',
  7509. 'emscriptenWebGLGet',
  7510. 'computeUnpackAlignedImageSize',
  7511. 'emscriptenWebGLGetTexPixelData',
  7512. 'emscriptenWebGLGetUniform',
  7513. 'webglGetUniformLocation',
  7514. 'webglPrepareUniformLocationsBeforeFirstUse',
  7515. 'webglGetLeftBracePos',
  7516. 'emscriptenWebGLGetVertexAttrib',
  7517. 'writeGLArray',
  7518. 'AL',
  7519. 'SDL_unicode',
  7520. 'SDL_ttfContext',
  7521. 'SDL_audio',
  7522. 'SDL',
  7523. 'SDL_gfx',
  7524. 'GLUT',
  7525. 'EGL',
  7526. 'GLFW_Window',
  7527. 'GLFW',
  7528. 'GLEW',
  7529. 'IDBStore',
  7530. 'runAndAbortIfError',
  7531. 'ALLOC_NORMAL',
  7532. 'ALLOC_STACK',
  7533. 'allocate',
  7534. 'InternalError',
  7535. 'BindingError',
  7536. 'UnboundTypeError',
  7537. 'PureVirtualError',
  7538. 'init_embind',
  7539. 'throwInternalError',
  7540. 'throwBindingError',
  7541. 'throwUnboundTypeError',
  7542. 'ensureOverloadTable',
  7543. 'exposePublicSymbol',
  7544. 'replacePublicSymbol',
  7545. 'extendError',
  7546. 'createNamedFunction',
  7547. 'embindRepr',
  7548. 'registeredInstances',
  7549. 'getBasestPointer',
  7550. 'registerInheritedInstance',
  7551. 'unregisterInheritedInstance',
  7552. 'getInheritedInstance',
  7553. 'getInheritedInstanceCount',
  7554. 'getLiveInheritedInstances',
  7555. 'registeredTypes',
  7556. 'awaitingDependencies',
  7557. 'typeDependencies',
  7558. 'registeredPointers',
  7559. 'registerType',
  7560. 'whenDependentTypesAreResolved',
  7561. 'embind_charCodes',
  7562. 'embind_init_charCodes',
  7563. 'readLatin1String',
  7564. 'getTypeName',
  7565. 'heap32VectorToArray',
  7566. 'requireRegisteredType',
  7567. 'getShiftFromSize',
  7568. 'integerReadValueFromPointer',
  7569. 'enumReadValueFromPointer',
  7570. 'floatReadValueFromPointer',
  7571. 'simpleReadValueFromPointer',
  7572. 'runDestructors',
  7573. 'new_',
  7574. 'craftInvokerFunction',
  7575. 'embind__requireFunction',
  7576. 'tupleRegistrations',
  7577. 'structRegistrations',
  7578. 'genericPointerToWireType',
  7579. 'constNoSmartPtrRawPointerToWireType',
  7580. 'nonConstNoSmartPtrRawPointerToWireType',
  7581. 'init_RegisteredPointer',
  7582. 'RegisteredPointer',
  7583. 'RegisteredPointer_getPointee',
  7584. 'RegisteredPointer_destructor',
  7585. 'RegisteredPointer_deleteObject',
  7586. 'RegisteredPointer_fromWireType',
  7587. 'runDestructor',
  7588. 'releaseClassHandle',
  7589. 'finalizationRegistry',
  7590. 'detachFinalizer_deps',
  7591. 'detachFinalizer',
  7592. 'attachFinalizer',
  7593. 'makeClassHandle',
  7594. 'init_ClassHandle',
  7595. 'ClassHandle',
  7596. 'ClassHandle_isAliasOf',
  7597. 'throwInstanceAlreadyDeleted',
  7598. 'ClassHandle_clone',
  7599. 'ClassHandle_delete',
  7600. 'deletionQueue',
  7601. 'ClassHandle_isDeleted',
  7602. 'ClassHandle_deleteLater',
  7603. 'flushPendingDeletes',
  7604. 'delayFunction',
  7605. 'setDelayFunction',
  7606. 'RegisteredClass',
  7607. 'shallowCopyInternalPointer',
  7608. 'downcastPointer',
  7609. 'upcastPointer',
  7610. 'validateThis',
  7611. 'char_0',
  7612. 'char_9',
  7613. 'makeLegalFunctionName',
  7614. 'emval_handle_array',
  7615. 'emval_free_list',
  7616. 'emval_symbols',
  7617. 'init_emval',
  7618. 'count_emval_handles',
  7619. 'get_first_emval',
  7620. 'getStringOrSymbol',
  7621. 'Emval',
  7622. 'emval_newers',
  7623. 'craftEmvalAllocator',
  7624. 'emval_get_global',
  7625. 'emval_lookupTypes',
  7626. 'emval_allocateDestructors',
  7627. 'emval_methodCallers',
  7628. 'emval_addMethodCaller',
  7629. 'emval_registeredMethods',
  7630. ];
  7631. unexportedRuntimeSymbols.forEach(unexportedRuntimeSymbol);
  7632. var missingLibrarySymbols = [
  7633. 'stringToNewUTF8',
  7634. 'writeSockaddr',
  7635. 'getHostByName',
  7636. 'traverseStack',
  7637. 'convertPCtoSourceLocation',
  7638. 'readEmAsmArgs',
  7639. 'runEmAsmFunction',
  7640. 'runMainThreadEmAsm',
  7641. 'jstoi_s',
  7642. 'listenOnce',
  7643. 'autoResumeAudioContext',
  7644. 'handleException',
  7645. 'runtimeKeepalivePush',
  7646. 'runtimeKeepalivePop',
  7647. 'callUserCallback',
  7648. 'maybeExit',
  7649. 'safeSetTimeout',
  7650. 'asmjsMangle',
  7651. 'handleAllocator',
  7652. 'writeI53ToI64',
  7653. 'writeI53ToI64Clamped',
  7654. 'writeI53ToI64Signaling',
  7655. 'writeI53ToU64Clamped',
  7656. 'writeI53ToU64Signaling',
  7657. 'readI53FromU64',
  7658. 'convertI32PairToI53',
  7659. 'convertU32PairToI53',
  7660. 'getCFunc',
  7661. 'ccall',
  7662. 'cwrap',
  7663. 'uleb128Encode',
  7664. 'sigToWasmTypes',
  7665. 'generateFuncType',
  7666. 'convertJsFunctionToWasm',
  7667. 'getEmptyTableSlot',
  7668. 'updateTableMap',
  7669. 'addFunction',
  7670. 'removeFunction',
  7671. 'reallyNegative',
  7672. 'unSign',
  7673. 'strLen',
  7674. 'reSign',
  7675. 'formatString',
  7676. 'intArrayToString',
  7677. 'AsciiToString',
  7678. 'stringToAscii',
  7679. 'allocateUTF8OnStack',
  7680. 'writeStringToMemory',
  7681. 'writeArrayToMemory',
  7682. 'registerKeyEventCallback',
  7683. 'maybeCStringToJsString',
  7684. 'findEventTarget',
  7685. 'findCanvasEventTarget',
  7686. 'getBoundingClientRect',
  7687. 'fillMouseEventData',
  7688. 'registerMouseEventCallback',
  7689. 'registerWheelEventCallback',
  7690. 'registerUiEventCallback',
  7691. 'registerFocusEventCallback',
  7692. 'fillDeviceOrientationEventData',
  7693. 'registerDeviceOrientationEventCallback',
  7694. 'fillDeviceMotionEventData',
  7695. 'registerDeviceMotionEventCallback',
  7696. 'screenOrientation',
  7697. 'fillOrientationChangeEventData',
  7698. 'registerOrientationChangeEventCallback',
  7699. 'fillFullscreenChangeEventData',
  7700. 'registerFullscreenChangeEventCallback',
  7701. 'JSEvents_requestFullscreen',
  7702. 'JSEvents_resizeCanvasForFullscreen',
  7703. 'registerRestoreOldStyle',
  7704. 'hideEverythingExceptGivenElement',
  7705. 'restoreHiddenElements',
  7706. 'setLetterbox',
  7707. 'softFullscreenResizeWebGLRenderTarget',
  7708. 'doRequestFullscreen',
  7709. 'fillPointerlockChangeEventData',
  7710. 'registerPointerlockChangeEventCallback',
  7711. 'registerPointerlockErrorEventCallback',
  7712. 'requestPointerLock',
  7713. 'fillVisibilityChangeEventData',
  7714. 'registerVisibilityChangeEventCallback',
  7715. 'registerTouchEventCallback',
  7716. 'fillGamepadEventData',
  7717. 'registerGamepadEventCallback',
  7718. 'registerBeforeUnloadEventCallback',
  7719. 'fillBatteryEventData',
  7720. 'battery',
  7721. 'registerBatteryEventCallback',
  7722. 'setCanvasElementSize',
  7723. 'getCanvasElementSize',
  7724. 'jsStackTrace',
  7725. 'stackTrace',
  7726. 'checkWasiClock',
  7727. 'createDyncallWrapper',
  7728. 'setImmediateWrapped',
  7729. 'clearImmediateWrapped',
  7730. 'polyfillSetImmediate',
  7731. 'newNativePromise',
  7732. 'getPromise',
  7733. 'exception_addRef',
  7734. 'exception_decRef',
  7735. 'setMainLoop',
  7736. '_setNetworkCallback',
  7737. 'heapObjectForWebGLType',
  7738. 'heapAccessShiftForWebGLHeap',
  7739. 'emscriptenWebGLGet',
  7740. 'computeUnpackAlignedImageSize',
  7741. 'emscriptenWebGLGetTexPixelData',
  7742. 'emscriptenWebGLGetUniform',
  7743. 'webglGetUniformLocation',
  7744. 'webglPrepareUniformLocationsBeforeFirstUse',
  7745. 'webglGetLeftBracePos',
  7746. 'emscriptenWebGLGetVertexAttrib',
  7747. 'writeGLArray',
  7748. 'SDL_unicode',
  7749. 'SDL_ttfContext',
  7750. 'SDL_audio',
  7751. 'GLFW_Window',
  7752. 'runAndAbortIfError',
  7753. 'ALLOC_NORMAL',
  7754. 'ALLOC_STACK',
  7755. 'allocate',
  7756. 'registerInheritedInstance',
  7757. 'unregisterInheritedInstance',
  7758. ];
  7759. missingLibrarySymbols.forEach(missingLibrarySymbol)
  7760. var calledRun;
  7761. dependenciesFulfilled = function runCaller() {
  7762. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  7763. if (!calledRun) run();
  7764. if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  7765. };
  7766. function stackCheckInit() {
  7767. // This is normally called automatically during __wasm_call_ctors but need to
  7768. // get these values before even running any of the ctors so we call it redundantly
  7769. // here.
  7770. _emscripten_stack_init();
  7771. // TODO(sbc): Move writeStackCookie to native to to avoid this.
  7772. writeStackCookie();
  7773. }
  7774. /** @type {function(Array=)} */
  7775. function run(args) {
  7776. args = args || arguments_;
  7777. if (runDependencies > 0) {
  7778. return;
  7779. }
  7780. stackCheckInit();
  7781. preRun();
  7782. // a preRun added a dependency, run will be called later
  7783. if (runDependencies > 0) {
  7784. return;
  7785. }
  7786. function doRun() {
  7787. // run may have just been called through dependencies being fulfilled just in this very frame,
  7788. // or while the async setStatus time below was happening
  7789. if (calledRun) return;
  7790. calledRun = true;
  7791. Module['calledRun'] = true;
  7792. if (ABORT) return;
  7793. initRuntime();
  7794. readyPromiseResolve(Module);
  7795. if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
  7796. assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
  7797. postRun();
  7798. }
  7799. if (Module['setStatus']) {
  7800. Module['setStatus']('Running...');
  7801. setTimeout(function() {
  7802. setTimeout(function() {
  7803. Module['setStatus']('');
  7804. }, 1);
  7805. doRun();
  7806. }, 1);
  7807. } else
  7808. {
  7809. doRun();
  7810. }
  7811. checkStackCookie();
  7812. }
  7813. function checkUnflushedContent() {
  7814. // Compiler settings do not allow exiting the runtime, so flushing
  7815. // the streams is not possible. but in ASSERTIONS mode we check
  7816. // if there was something to flush, and if so tell the user they
  7817. // should request that the runtime be exitable.
  7818. // Normally we would not even include flush() at all, but in ASSERTIONS
  7819. // builds we do so just for this check, and here we see if there is any
  7820. // content to flush, that is, we check if there would have been
  7821. // something a non-ASSERTIONS build would have not seen.
  7822. // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
  7823. // mode (which has its own special function for this; otherwise, all
  7824. // the code is inside libc)
  7825. var oldOut = out;
  7826. var oldErr = err;
  7827. var has = false;
  7828. out = err = (x) => {
  7829. has = true;
  7830. }
  7831. try { // it doesn't matter if it fails
  7832. _fflush(0);
  7833. // also flush in the JS FS layer
  7834. ['stdout', 'stderr'].forEach(function(name) {
  7835. var info = FS.analyzePath('/dev/' + name);
  7836. if (!info) return;
  7837. var stream = info.object;
  7838. var rdev = stream.rdev;
  7839. var tty = TTY.ttys[rdev];
  7840. if (tty && tty.output && tty.output.length) {
  7841. has = true;
  7842. }
  7843. });
  7844. } catch(e) {}
  7845. out = oldOut;
  7846. err = oldErr;
  7847. if (has) {
  7848. warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.');
  7849. }
  7850. }
  7851. if (Module['preInit']) {
  7852. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  7853. while (Module['preInit'].length > 0) {
  7854. Module['preInit'].pop()();
  7855. }
  7856. }
  7857. run();
  7858. return rhino3dm.ready
  7859. }
  7860. );
  7861. })();
  7862. if (typeof exports === 'object' && typeof module === 'object')
  7863. module.exports = rhino3dm;
  7864. else if (typeof define === 'function' && define['amd'])
  7865. define([], function() { return rhino3dm; });
  7866. else if (typeof exports === 'object')
  7867. exports["rhino3dm"] = rhino3dm;