rhino3dm.module.js 314 KB

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