wasm_runtime_common.c 205 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_platform.h"
  6. #include "bh_common.h"
  7. #include "bh_assert.h"
  8. #include "bh_log.h"
  9. #include "wasm_native.h"
  10. #include "wasm_runtime_common.h"
  11. #include "wasm_memory.h"
  12. #if WASM_ENABLE_INTERP != 0
  13. #include "../interpreter/wasm_runtime.h"
  14. #endif
  15. #if WASM_ENABLE_AOT != 0
  16. #include "../aot/aot_runtime.h"
  17. #if WASM_ENABLE_DEBUG_AOT != 0
  18. #include "../aot/debug/jit_debug.h"
  19. #endif
  20. #endif
  21. #if WASM_ENABLE_GC != 0
  22. #include "gc/gc_object.h"
  23. #endif
  24. #if WASM_ENABLE_THREAD_MGR != 0
  25. #include "../libraries/thread-mgr/thread_manager.h"
  26. #if WASM_ENABLE_DEBUG_INTERP != 0
  27. #include "../libraries/debug-engine/debug_engine.h"
  28. #endif
  29. #endif
  30. #if WASM_ENABLE_SHARED_MEMORY != 0
  31. #include "wasm_shared_memory.h"
  32. #endif
  33. #if WASM_ENABLE_FAST_JIT != 0
  34. #include "../fast-jit/jit_compiler.h"
  35. #endif
  36. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  37. #include "../compilation/aot_llvm.h"
  38. #endif
  39. #include "../common/wasm_c_api_internal.h"
  40. #include "../../version.h"
  41. /**
  42. * For runtime build, BH_MALLOC/BH_FREE should be defined as
  43. * wasm_runtime_malloc/wasm_runtime_free.
  44. */
  45. #define CHECK(a) CHECK1(a)
  46. #define CHECK1(a) SHOULD_BE_##a
  47. #define SHOULD_BE_wasm_runtime_malloc 1
  48. #if !CHECK(BH_MALLOC)
  49. #error unexpected BH_MALLOC
  50. #endif
  51. #undef SHOULD_BE_wasm_runtime_malloc
  52. #define SHOULD_BE_wasm_runtime_free 1
  53. #if !CHECK(BH_FREE)
  54. #error unexpected BH_FREE
  55. #endif
  56. #undef SHOULD_BE_wasm_runtime_free
  57. #undef CHECK
  58. #undef CHECK1
  59. #if WASM_ENABLE_MULTI_MODULE != 0
  60. /**
  61. * A safety insurance to prevent
  62. * circular depencies which leads stack overflow
  63. * try to break early
  64. */
  65. typedef struct LoadingModule {
  66. bh_list_link l;
  67. /* point to a string pool */
  68. const char *module_name;
  69. } LoadingModule;
  70. static bh_list loading_module_list_head;
  71. static bh_list *const loading_module_list = &loading_module_list_head;
  72. static korp_mutex loading_module_list_lock;
  73. /**
  74. * A list to store all exported functions/globals/memories/tables
  75. * of every fully loaded module
  76. */
  77. static bh_list registered_module_list_head;
  78. static bh_list *const registered_module_list = &registered_module_list_head;
  79. static korp_mutex registered_module_list_lock;
  80. static void
  81. wasm_runtime_destroy_registered_module_list();
  82. #endif /* WASM_ENABLE_MULTI_MODULE */
  83. #define E_TYPE_XIP 4
  84. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  85. /* Initialize externref hashmap */
  86. static bool
  87. wasm_externref_map_init();
  88. /* Destroy externref hashmap */
  89. static void
  90. wasm_externref_map_destroy();
  91. #endif /* end of WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */
  92. static void
  93. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  94. {
  95. if (error_buf != NULL)
  96. snprintf(error_buf, error_buf_size, "%s", string);
  97. }
  98. static void *
  99. runtime_malloc(uint64 size, WASMModuleInstanceCommon *module_inst,
  100. char *error_buf, uint32 error_buf_size)
  101. {
  102. void *mem;
  103. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  104. if (module_inst != NULL) {
  105. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  106. }
  107. else if (error_buf != NULL) {
  108. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  109. }
  110. return NULL;
  111. }
  112. memset(mem, 0, (uint32)size);
  113. return mem;
  114. }
  115. #if WASM_ENABLE_MULTI_MODULE != 0
  116. /* TODO: Let loader_malloc be a general API both for AOT and WASM. */
  117. #define loader_malloc(size, error_buf, error_buf_size) \
  118. runtime_malloc(size, NULL, error_buf, error_buf_size)
  119. static void
  120. set_error_buf_v(const WASMModuleCommon *module, char *error_buf,
  121. uint32 error_buf_size, const char *format, ...)
  122. {
  123. va_list args;
  124. char buf[128];
  125. if (error_buf != NULL) {
  126. va_start(args, format);
  127. vsnprintf(buf, sizeof(buf), format, args);
  128. va_end(args);
  129. if (module->module_type == Wasm_Module_AoT) {
  130. snprintf(error_buf, error_buf_size, "AOT module load failed: %s",
  131. buf);
  132. }
  133. else if (module->module_type == Wasm_Module_Bytecode) {
  134. snprintf(error_buf, error_buf_size, "WASM module load failed: %s",
  135. buf);
  136. }
  137. }
  138. }
  139. #endif
  140. #if WASM_ENABLE_FAST_JIT != 0
  141. static JitCompOptions jit_options = { 0 };
  142. #endif
  143. #if WASM_ENABLE_JIT != 0
  144. /* opt_level: 3, size_level: 3, segue-flags: 0,
  145. quick_invoke_c_api_import: false */
  146. static LLVMJITOptions llvm_jit_options = { 3, 3, 0, false };
  147. #endif
  148. #if WASM_ENABLE_GC != 0
  149. static uint32 gc_heap_size_default = GC_HEAP_SIZE_DEFAULT;
  150. #endif
  151. static RunningMode runtime_running_mode = Mode_Default;
  152. #ifdef OS_ENABLE_HW_BOUND_CHECK
  153. /* The exec_env of thread local storage, set before calling function
  154. and used in signal handler, as we cannot get it from the argument
  155. of signal handler */
  156. static os_thread_local_attribute WASMExecEnv *exec_env_tls = NULL;
  157. #ifndef BH_PLATFORM_WINDOWS
  158. static void
  159. runtime_signal_handler(void *sig_addr)
  160. {
  161. WASMModuleInstance *module_inst;
  162. WASMMemoryInstance *memory_inst;
  163. WASMJmpBuf *jmpbuf_node;
  164. uint8 *mapped_mem_start_addr = NULL;
  165. uint8 *mapped_mem_end_addr = NULL;
  166. uint32 page_size = os_getpagesize();
  167. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  168. uint8 *stack_min_addr;
  169. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  170. #endif
  171. /* Check whether current thread is running wasm function */
  172. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  173. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  174. /* Get mapped mem info of current instance */
  175. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  176. /* Get the default memory instance */
  177. memory_inst = wasm_get_default_memory(module_inst);
  178. if (memory_inst) {
  179. mapped_mem_start_addr = memory_inst->memory_data;
  180. mapped_mem_end_addr = memory_inst->memory_data + 8 * (uint64)BH_GB;
  181. }
  182. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  183. /* Get stack info of current thread */
  184. stack_min_addr = os_thread_get_stack_boundary();
  185. #endif
  186. if (memory_inst
  187. && (mapped_mem_start_addr <= (uint8 *)sig_addr
  188. && (uint8 *)sig_addr < mapped_mem_end_addr)) {
  189. /* The address which causes segmentation fault is inside
  190. the memory instance's guard regions */
  191. wasm_set_exception(module_inst, "out of bounds memory access");
  192. os_longjmp(jmpbuf_node->jmpbuf, 1);
  193. }
  194. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  195. else if (stack_min_addr - page_size <= (uint8 *)sig_addr
  196. && (uint8 *)sig_addr
  197. < stack_min_addr + page_size * guard_page_count) {
  198. /* The address which causes segmentation fault is inside
  199. native thread's guard page */
  200. wasm_set_exception(module_inst, "native stack overflow");
  201. os_longjmp(jmpbuf_node->jmpbuf, 1);
  202. }
  203. #endif
  204. else if (exec_env_tls->exce_check_guard_page <= (uint8 *)sig_addr
  205. && (uint8 *)sig_addr
  206. < exec_env_tls->exce_check_guard_page + page_size) {
  207. bh_assert(wasm_copy_exception(module_inst, NULL));
  208. os_longjmp(jmpbuf_node->jmpbuf, 1);
  209. }
  210. }
  211. }
  212. #else /* else of BH_PLATFORM_WINDOWS */
  213. #if WASM_ENABLE_AOT != 0
  214. #include <Zydis/Zydis.h>
  215. static uint32
  216. decode_insn(uint8 *insn)
  217. {
  218. uint8 *data = (uint8 *)insn;
  219. uint32 length = 32; /* reserve enough size */
  220. /* Initialize decoder context */
  221. ZydisDecoder decoder;
  222. ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64,
  223. ZYDIS_STACK_WIDTH_64);
  224. /* Initialize formatter */
  225. ZydisFormatter formatter;
  226. ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL);
  227. /* Loop over the instructions in our buffer */
  228. ZyanU64 runtime_address = (ZyanU64)(uintptr_t)data;
  229. ZyanUSize offset = 0;
  230. ZydisDecodedInstruction instruction;
  231. ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT_VISIBLE];
  232. char buffer[256];
  233. if (ZYAN_SUCCESS(ZydisDecoderDecodeFull(
  234. &decoder, data + offset, length - offset, &instruction, operands,
  235. ZYDIS_MAX_OPERAND_COUNT_VISIBLE,
  236. ZYDIS_DFLAG_VISIBLE_OPERANDS_ONLY))) {
  237. /* Format & print the binary instruction structure to
  238. human readable format */
  239. ZydisFormatterFormatInstruction(&formatter, &instruction, operands,
  240. instruction.operand_count_visible,
  241. buffer, sizeof(buffer),
  242. runtime_address);
  243. /* Print current instruction */
  244. /*
  245. os_printf("%012" PRIX64 " ", runtime_address);
  246. puts(buffer);
  247. */
  248. return instruction.length;
  249. }
  250. /* Decode failed */
  251. return 0;
  252. }
  253. #endif /* end of WASM_ENABLE_AOT != 0 */
  254. static LONG
  255. next_action(WASMModuleInstance *module_inst, EXCEPTION_POINTERS *exce_info)
  256. {
  257. #if WASM_ENABLE_AOT != 0
  258. uint32 insn_size;
  259. #endif
  260. if (module_inst->module_type == Wasm_Module_Bytecode
  261. && module_inst->e->running_mode == Mode_Interp) {
  262. /* Continue to search next exception handler for
  263. interpreter mode as it can be caught by
  264. `__try { .. } __except { .. }` sentences in
  265. wasm_runtime.c */
  266. return EXCEPTION_CONTINUE_SEARCH;
  267. }
  268. #if WASM_ENABLE_AOT != 0
  269. /* Skip current instruction and continue to run for AOT/JIT mode.
  270. TODO: implement unwind support for AOT/JIT code in Windows platform */
  271. insn_size = decode_insn((uint8 *)exce_info->ContextRecord->Rip);
  272. if (insn_size > 0) {
  273. exce_info->ContextRecord->Rip += insn_size;
  274. return EXCEPTION_CONTINUE_EXECUTION;
  275. }
  276. #endif
  277. /* return different value from EXCEPTION_CONTINUE_SEARCH (= 0)
  278. and EXCEPTION_CONTINUE_EXECUTION (= -1) */
  279. return -2;
  280. }
  281. static LONG
  282. runtime_exception_handler(EXCEPTION_POINTERS *exce_info)
  283. {
  284. PEXCEPTION_RECORD ExceptionRecord = exce_info->ExceptionRecord;
  285. uint8 *sig_addr = (uint8 *)ExceptionRecord->ExceptionInformation[1];
  286. WASMModuleInstance *module_inst;
  287. WASMMemoryInstance *memory_inst;
  288. WASMJmpBuf *jmpbuf_node;
  289. uint8 *mapped_mem_start_addr = NULL;
  290. uint8 *mapped_mem_end_addr = NULL;
  291. uint32 page_size = os_getpagesize();
  292. LONG ret;
  293. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  294. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  295. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  296. if (ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
  297. /* Get the default memory instance */
  298. memory_inst = wasm_get_default_memory(module_inst);
  299. if (memory_inst) {
  300. mapped_mem_start_addr = memory_inst->memory_data;
  301. mapped_mem_end_addr =
  302. memory_inst->memory_data + 8 * (uint64)BH_GB;
  303. }
  304. if (memory_inst && mapped_mem_start_addr <= (uint8 *)sig_addr
  305. && (uint8 *)sig_addr < mapped_mem_end_addr) {
  306. /* The address which causes segmentation fault is inside
  307. the memory instance's guard regions.
  308. Set exception and let the wasm func continue to run, when
  309. the wasm func returns, the caller will check whether the
  310. exception is thrown and return to runtime. */
  311. wasm_set_exception(module_inst, "out of bounds memory access");
  312. ret = next_action(module_inst, exce_info);
  313. if (ret == EXCEPTION_CONTINUE_SEARCH
  314. || ret == EXCEPTION_CONTINUE_EXECUTION)
  315. return ret;
  316. }
  317. else if (exec_env_tls->exce_check_guard_page <= (uint8 *)sig_addr
  318. && (uint8 *)sig_addr
  319. < exec_env_tls->exce_check_guard_page + page_size) {
  320. bh_assert(wasm_copy_exception(module_inst, NULL));
  321. ret = next_action(module_inst, exce_info);
  322. if (ret == EXCEPTION_CONTINUE_SEARCH
  323. || ret == EXCEPTION_CONTINUE_EXECUTION)
  324. return ret;
  325. }
  326. }
  327. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  328. else if (ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
  329. /* Set stack overflow exception and let the wasm func continue
  330. to run, when the wasm func returns, the caller will check
  331. whether the exception is thrown and return to runtime, and
  332. the damaged stack will be recovered by _resetstkoflw(). */
  333. wasm_set_exception(module_inst, "native stack overflow");
  334. ret = next_action(module_inst, exce_info);
  335. if (ret == EXCEPTION_CONTINUE_SEARCH
  336. || ret == EXCEPTION_CONTINUE_EXECUTION)
  337. return ret;
  338. }
  339. #endif
  340. }
  341. os_printf("Unhandled exception thrown: exception code: 0x%lx, "
  342. "exception address: %p, exception information: %p\n",
  343. ExceptionRecord->ExceptionCode, ExceptionRecord->ExceptionAddress,
  344. sig_addr);
  345. return EXCEPTION_CONTINUE_SEARCH;
  346. }
  347. #endif /* end of BH_PLATFORM_WINDOWS */
  348. static bool
  349. runtime_signal_init()
  350. {
  351. #ifndef BH_PLATFORM_WINDOWS
  352. return os_thread_signal_init(runtime_signal_handler) == 0 ? true : false;
  353. #else
  354. if (os_thread_signal_init() != 0)
  355. return false;
  356. if (!AddVectoredExceptionHandler(1, runtime_exception_handler)) {
  357. os_thread_signal_destroy();
  358. return false;
  359. }
  360. #endif
  361. return true;
  362. }
  363. static void
  364. runtime_signal_destroy()
  365. {
  366. #ifdef BH_PLATFORM_WINDOWS
  367. RemoveVectoredExceptionHandler(runtime_exception_handler);
  368. #endif
  369. os_thread_signal_destroy();
  370. }
  371. void
  372. wasm_runtime_set_exec_env_tls(WASMExecEnv *exec_env)
  373. {
  374. exec_env_tls = exec_env;
  375. }
  376. WASMExecEnv *
  377. wasm_runtime_get_exec_env_tls()
  378. {
  379. return exec_env_tls;
  380. }
  381. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  382. static bool
  383. wasm_runtime_env_init()
  384. {
  385. if (bh_platform_init() != 0)
  386. return false;
  387. if (wasm_native_init() == false) {
  388. goto fail1;
  389. }
  390. #if WASM_ENABLE_MULTI_MODULE
  391. if (BHT_OK != os_mutex_init(&registered_module_list_lock)) {
  392. goto fail2;
  393. }
  394. if (BHT_OK != os_mutex_init(&loading_module_list_lock)) {
  395. goto fail3;
  396. }
  397. #endif
  398. #if WASM_ENABLE_SHARED_MEMORY
  399. if (!wasm_shared_memory_init()) {
  400. goto fail4;
  401. }
  402. #endif
  403. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  404. if (!thread_manager_init()) {
  405. goto fail5;
  406. }
  407. #endif
  408. #ifdef OS_ENABLE_HW_BOUND_CHECK
  409. if (!runtime_signal_init()) {
  410. goto fail6;
  411. }
  412. #endif
  413. #if WASM_ENABLE_AOT != 0
  414. #if WASM_ENABLE_DEBUG_AOT != 0
  415. if (!jit_debug_engine_init()) {
  416. goto fail7;
  417. }
  418. #endif
  419. #endif
  420. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  421. if (!wasm_externref_map_init()) {
  422. goto fail8;
  423. }
  424. #endif
  425. #if WASM_ENABLE_FAST_JIT != 0
  426. if (!jit_compiler_init(&jit_options)) {
  427. goto fail9;
  428. }
  429. #endif
  430. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  431. if (!aot_compiler_init()) {
  432. goto fail10;
  433. }
  434. #endif
  435. #if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP)
  436. if (os_blocking_op_init() != BHT_OK) {
  437. goto fail11;
  438. }
  439. os_end_blocking_op();
  440. #endif
  441. return true;
  442. #if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP)
  443. fail11:
  444. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  445. aot_compiler_destroy();
  446. #endif
  447. #endif
  448. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  449. fail10:
  450. #if WASM_ENABLE_FAST_JIT != 0
  451. jit_compiler_destroy();
  452. #endif
  453. #endif
  454. #if WASM_ENABLE_FAST_JIT != 0
  455. fail9:
  456. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  457. wasm_externref_map_destroy();
  458. #endif
  459. #endif
  460. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  461. fail8:
  462. #endif
  463. #if WASM_ENABLE_AOT != 0
  464. #if WASM_ENABLE_DEBUG_AOT != 0
  465. jit_debug_engine_destroy();
  466. fail7:
  467. #endif
  468. #endif
  469. #ifdef OS_ENABLE_HW_BOUND_CHECK
  470. runtime_signal_destroy();
  471. fail6:
  472. #endif
  473. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  474. thread_manager_destroy();
  475. fail5:
  476. #endif
  477. #if WASM_ENABLE_SHARED_MEMORY
  478. wasm_shared_memory_destroy();
  479. fail4:
  480. #endif
  481. #if WASM_ENABLE_MULTI_MODULE
  482. os_mutex_destroy(&loading_module_list_lock);
  483. fail3:
  484. os_mutex_destroy(&registered_module_list_lock);
  485. fail2:
  486. #endif
  487. wasm_native_destroy();
  488. fail1:
  489. bh_platform_destroy();
  490. return false;
  491. }
  492. static bool
  493. wasm_runtime_exec_env_check(WASMExecEnv *exec_env)
  494. {
  495. return exec_env && exec_env->module_inst && exec_env->wasm_stack_size > 0
  496. && exec_env->wasm_stack.top_boundary
  497. == exec_env->wasm_stack.bottom + exec_env->wasm_stack_size
  498. && exec_env->wasm_stack.top <= exec_env->wasm_stack.top_boundary;
  499. }
  500. bool
  501. wasm_runtime_init()
  502. {
  503. if (!wasm_runtime_memory_init(Alloc_With_System_Allocator, NULL))
  504. return false;
  505. if (!wasm_runtime_env_init()) {
  506. wasm_runtime_memory_destroy();
  507. return false;
  508. }
  509. return true;
  510. }
  511. void
  512. wasm_runtime_destroy()
  513. {
  514. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  515. wasm_externref_map_destroy();
  516. #endif
  517. #if WASM_ENABLE_AOT != 0
  518. #if WASM_ENABLE_DEBUG_AOT != 0
  519. jit_debug_engine_destroy();
  520. #endif
  521. #endif
  522. #ifdef OS_ENABLE_HW_BOUND_CHECK
  523. runtime_signal_destroy();
  524. #endif
  525. /* runtime env destroy */
  526. #if WASM_ENABLE_MULTI_MODULE
  527. wasm_runtime_destroy_loading_module_list();
  528. os_mutex_destroy(&loading_module_list_lock);
  529. wasm_runtime_destroy_registered_module_list();
  530. os_mutex_destroy(&registered_module_list_lock);
  531. #endif
  532. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  533. /* Destroy LLVM-JIT compiler after destroying the modules
  534. * loaded by multi-module feature, since these modules may
  535. * create backend threads to compile the wasm functions,
  536. * which may access the LLVM resources. We wait until they
  537. * finish the compilation to avoid accessing the destroyed
  538. * resources in the compilation threads.
  539. */
  540. aot_compiler_destroy();
  541. #endif
  542. #if WASM_ENABLE_FAST_JIT != 0
  543. /* Destroy Fast-JIT compiler after destroying the modules
  544. * loaded by multi-module feature, since the Fast JIT's
  545. * code cache allocator may be used by these modules.
  546. */
  547. jit_compiler_destroy();
  548. #endif
  549. #if WASM_ENABLE_SHARED_MEMORY
  550. wasm_shared_memory_destroy();
  551. #endif
  552. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  553. #if WASM_ENABLE_DEBUG_INTERP != 0
  554. wasm_debug_engine_destroy();
  555. #endif
  556. thread_manager_destroy();
  557. #endif
  558. wasm_native_destroy();
  559. bh_platform_destroy();
  560. wasm_runtime_memory_destroy();
  561. }
  562. RunningMode
  563. wasm_runtime_get_default_running_mode(void)
  564. {
  565. return runtime_running_mode;
  566. }
  567. #if WASM_ENABLE_JIT != 0
  568. LLVMJITOptions *
  569. wasm_runtime_get_llvm_jit_options(void)
  570. {
  571. return &llvm_jit_options;
  572. }
  573. #endif
  574. #if WASM_ENABLE_GC != 0
  575. uint32
  576. wasm_runtime_get_gc_heap_size_default(void)
  577. {
  578. return gc_heap_size_default;
  579. }
  580. #endif
  581. bool
  582. wasm_runtime_full_init(RuntimeInitArgs *init_args)
  583. {
  584. if (!wasm_runtime_memory_init(init_args->mem_alloc_type,
  585. &init_args->mem_alloc_option))
  586. return false;
  587. if (!wasm_runtime_set_default_running_mode(init_args->running_mode)) {
  588. wasm_runtime_memory_destroy();
  589. return false;
  590. }
  591. #if WASM_ENABLE_FAST_JIT != 0
  592. jit_options.code_cache_size = init_args->fast_jit_code_cache_size;
  593. #endif
  594. #if WASM_ENABLE_GC != 0
  595. gc_heap_size_default = init_args->gc_heap_size;
  596. #endif
  597. #if WASM_ENABLE_JIT != 0
  598. llvm_jit_options.size_level = init_args->llvm_jit_size_level;
  599. llvm_jit_options.opt_level = init_args->llvm_jit_opt_level;
  600. llvm_jit_options.segue_flags = init_args->segue_flags;
  601. #endif
  602. #if WASM_ENABLE_LINUX_PERF != 0
  603. wasm_runtime_set_linux_perf(init_args->enable_linux_perf);
  604. #else
  605. if (init_args->enable_linux_perf)
  606. LOG_WARNING("warning: to enable linux perf support, please recompile "
  607. "with -DWAMR_BUILD_LINUX_PERF=1");
  608. #endif
  609. if (!wasm_runtime_env_init()) {
  610. wasm_runtime_memory_destroy();
  611. return false;
  612. }
  613. #if WASM_ENABLE_DEBUG_INTERP != 0
  614. if (strlen(init_args->ip_addr))
  615. if (!wasm_debug_engine_init(init_args->ip_addr,
  616. init_args->instance_port)) {
  617. wasm_runtime_destroy();
  618. return false;
  619. }
  620. #endif
  621. if (init_args->n_native_symbols > 0
  622. && !wasm_runtime_register_natives(init_args->native_module_name,
  623. init_args->native_symbols,
  624. init_args->n_native_symbols)) {
  625. wasm_runtime_destroy();
  626. return false;
  627. }
  628. #if WASM_ENABLE_THREAD_MGR != 0
  629. wasm_cluster_set_max_thread_num(init_args->max_thread_num);
  630. #endif
  631. return true;
  632. }
  633. void
  634. wasm_runtime_set_log_level(log_level_t level)
  635. {
  636. bh_log_set_verbose_level(level);
  637. }
  638. bool
  639. wasm_runtime_is_running_mode_supported(RunningMode running_mode)
  640. {
  641. if (running_mode == Mode_Default) {
  642. return true;
  643. }
  644. else if (running_mode == Mode_Interp) {
  645. #if WASM_ENABLE_INTERP != 0
  646. return true;
  647. #endif
  648. }
  649. else if (running_mode == Mode_Fast_JIT) {
  650. #if WASM_ENABLE_FAST_JIT != 0
  651. return true;
  652. #endif
  653. }
  654. else if (running_mode == Mode_LLVM_JIT) {
  655. #if WASM_ENABLE_JIT != 0
  656. return true;
  657. #endif
  658. }
  659. else if (running_mode == Mode_Multi_Tier_JIT) {
  660. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  661. && WASM_ENABLE_LAZY_JIT != 0
  662. return true;
  663. #endif
  664. }
  665. return false;
  666. }
  667. bool
  668. wasm_runtime_set_default_running_mode(RunningMode running_mode)
  669. {
  670. if (wasm_runtime_is_running_mode_supported(running_mode)) {
  671. runtime_running_mode = running_mode;
  672. return true;
  673. }
  674. return false;
  675. }
  676. PackageType
  677. get_package_type(const uint8 *buf, uint32 size)
  678. {
  679. #if (WASM_ENABLE_WORD_ALIGN_READ != 0)
  680. uint32 buf32 = *(uint32 *)buf;
  681. buf = (const uint8 *)&buf32;
  682. #endif
  683. if (buf && size >= 4) {
  684. if (buf[0] == '\0' && buf[1] == 'a' && buf[2] == 's' && buf[3] == 'm')
  685. return Wasm_Module_Bytecode;
  686. if (buf[0] == '\0' && buf[1] == 'a' && buf[2] == 'o' && buf[3] == 't')
  687. return Wasm_Module_AoT;
  688. }
  689. return Package_Type_Unknown;
  690. }
  691. #if WASM_ENABLE_AOT != 0
  692. static uint8 *
  693. align_ptr(const uint8 *p, uint32 b)
  694. {
  695. uintptr_t v = (uintptr_t)p;
  696. uintptr_t m = b - 1;
  697. return (uint8 *)((v + m) & ~m);
  698. }
  699. #define CHECK_BUF(buf, buf_end, length) \
  700. do { \
  701. if ((uintptr_t)buf + length < (uintptr_t)buf \
  702. || (uintptr_t)buf + length > (uintptr_t)buf_end) \
  703. return false; \
  704. } while (0)
  705. #define read_uint16(p, p_end, res) \
  706. do { \
  707. p = (uint8 *)align_ptr(p, sizeof(uint16)); \
  708. CHECK_BUF(p, p_end, sizeof(uint16)); \
  709. res = *(uint16 *)p; \
  710. p += sizeof(uint16); \
  711. } while (0)
  712. #define read_uint32(p, p_end, res) \
  713. do { \
  714. p = (uint8 *)align_ptr(p, sizeof(uint32)); \
  715. CHECK_BUF(p, p_end, sizeof(uint32)); \
  716. res = *(uint32 *)p; \
  717. p += sizeof(uint32); \
  718. } while (0)
  719. bool
  720. wasm_runtime_is_xip_file(const uint8 *buf, uint32 size)
  721. {
  722. const uint8 *p = buf, *p_end = buf + size;
  723. uint32 section_type, section_size;
  724. uint16 e_type;
  725. if (get_package_type(buf, size) != Wasm_Module_AoT)
  726. return false;
  727. CHECK_BUF(p, p_end, 8);
  728. p += 8;
  729. while (p < p_end) {
  730. read_uint32(p, p_end, section_type);
  731. read_uint32(p, p_end, section_size);
  732. CHECK_BUF(p, p_end, section_size);
  733. if (section_type == AOT_SECTION_TYPE_TARGET_INFO) {
  734. p += 4;
  735. read_uint16(p, p_end, e_type);
  736. return (e_type == E_TYPE_XIP) ? true : false;
  737. }
  738. else if (section_type >= AOT_SECTION_TYPE_SIGANATURE) {
  739. return false;
  740. }
  741. p += section_size;
  742. }
  743. return false;
  744. }
  745. #endif /* end of WASM_ENABLE_AOT */
  746. #if (WASM_ENABLE_THREAD_MGR != 0) && (WASM_ENABLE_DEBUG_INTERP != 0)
  747. uint32
  748. wasm_runtime_start_debug_instance_with_port(WASMExecEnv *exec_env, int32_t port)
  749. {
  750. WASMModuleInstanceCommon *module_inst =
  751. wasm_runtime_get_module_inst(exec_env);
  752. WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env);
  753. bh_assert(module_inst);
  754. bh_assert(cluster);
  755. if (module_inst->module_type != Wasm_Module_Bytecode) {
  756. LOG_WARNING("Attempt to create a debug instance for an AOT module");
  757. return 0;
  758. }
  759. if (cluster->debug_inst) {
  760. LOG_WARNING("Cluster already bind to a debug instance");
  761. return cluster->debug_inst->control_thread->port;
  762. }
  763. if (wasm_debug_instance_create(cluster, port)) {
  764. return cluster->debug_inst->control_thread->port;
  765. }
  766. return 0;
  767. }
  768. uint32
  769. wasm_runtime_start_debug_instance(WASMExecEnv *exec_env)
  770. {
  771. return wasm_runtime_start_debug_instance_with_port(exec_env, -1);
  772. }
  773. #endif
  774. #if WASM_ENABLE_MULTI_MODULE != 0
  775. static module_reader reader;
  776. static module_destroyer destroyer;
  777. void
  778. wasm_runtime_set_module_reader(const module_reader reader_cb,
  779. const module_destroyer destroyer_cb)
  780. {
  781. reader = reader_cb;
  782. destroyer = destroyer_cb;
  783. }
  784. module_reader
  785. wasm_runtime_get_module_reader()
  786. {
  787. return reader;
  788. }
  789. module_destroyer
  790. wasm_runtime_get_module_destroyer()
  791. {
  792. return destroyer;
  793. }
  794. static WASMRegisteredModule *
  795. wasm_runtime_find_module_registered_by_reference(WASMModuleCommon *module)
  796. {
  797. WASMRegisteredModule *reg_module = NULL;
  798. os_mutex_lock(&registered_module_list_lock);
  799. reg_module = bh_list_first_elem(registered_module_list);
  800. while (reg_module && module != reg_module->module) {
  801. reg_module = bh_list_elem_next(reg_module);
  802. }
  803. os_mutex_unlock(&registered_module_list_lock);
  804. return reg_module;
  805. }
  806. bool
  807. wasm_runtime_register_module_internal(const char *module_name,
  808. WASMModuleCommon *module,
  809. uint8 *orig_file_buf,
  810. uint32 orig_file_buf_size,
  811. char *error_buf, uint32 error_buf_size)
  812. {
  813. WASMRegisteredModule *node = NULL;
  814. node = wasm_runtime_find_module_registered_by_reference(module);
  815. if (node) { /* module has been registered */
  816. if (node->module_name) { /* module has name */
  817. if (!module_name || strcmp(node->module_name, module_name)) {
  818. /* module has different name */
  819. LOG_DEBUG("module(%p) has been registered with name %s", module,
  820. node->module_name);
  821. set_error_buf(error_buf, error_buf_size,
  822. "Register module failed: "
  823. "failed to rename the module");
  824. return false;
  825. }
  826. else {
  827. /* module has the same name */
  828. LOG_DEBUG(
  829. "module(%p) has been registered with the same name %s",
  830. module, node->module_name);
  831. return true;
  832. }
  833. }
  834. else {
  835. /* module has empyt name, reset it */
  836. node->module_name = module_name;
  837. return true;
  838. }
  839. }
  840. /* module hasn't been registered */
  841. node = runtime_malloc(sizeof(WASMRegisteredModule), NULL, NULL, 0);
  842. if (!node) {
  843. LOG_DEBUG("malloc WASMRegisteredModule failed. SZ=%d",
  844. sizeof(WASMRegisteredModule));
  845. return false;
  846. }
  847. /* share the string and the module */
  848. node->module_name = module_name;
  849. node->module = module;
  850. node->orig_file_buf = orig_file_buf;
  851. node->orig_file_buf_size = orig_file_buf_size;
  852. os_mutex_lock(&registered_module_list_lock);
  853. bh_list_status ret = bh_list_insert(registered_module_list, node);
  854. bh_assert(BH_LIST_SUCCESS == ret);
  855. (void)ret;
  856. os_mutex_unlock(&registered_module_list_lock);
  857. return true;
  858. }
  859. bool
  860. wasm_runtime_register_module(const char *module_name, WASMModuleCommon *module,
  861. char *error_buf, uint32 error_buf_size)
  862. {
  863. if (!error_buf || !error_buf_size) {
  864. LOG_ERROR("error buffer is required");
  865. return false;
  866. }
  867. if (!module_name || !module) {
  868. LOG_DEBUG("module_name and module are required");
  869. set_error_buf(error_buf, error_buf_size,
  870. "Register module failed: "
  871. "module_name and module are required");
  872. return false;
  873. }
  874. if (wasm_runtime_is_built_in_module(module_name)) {
  875. LOG_DEBUG("%s is a built-in module name", module_name);
  876. set_error_buf(error_buf, error_buf_size,
  877. "Register module failed: "
  878. "can not register as a built-in module");
  879. return false;
  880. }
  881. return wasm_runtime_register_module_internal(module_name, module, NULL, 0,
  882. error_buf, error_buf_size);
  883. }
  884. void
  885. wasm_runtime_unregister_module(const WASMModuleCommon *module)
  886. {
  887. WASMRegisteredModule *registered_module = NULL;
  888. os_mutex_lock(&registered_module_list_lock);
  889. registered_module = bh_list_first_elem(registered_module_list);
  890. while (registered_module && module != registered_module->module) {
  891. registered_module = bh_list_elem_next(registered_module);
  892. }
  893. /* it does not matter if it is not exist. after all, it is gone */
  894. if (registered_module) {
  895. bh_list_remove(registered_module_list, registered_module);
  896. wasm_runtime_free(registered_module);
  897. }
  898. os_mutex_unlock(&registered_module_list_lock);
  899. }
  900. WASMModuleCommon *
  901. wasm_runtime_find_module_registered(const char *module_name)
  902. {
  903. WASMRegisteredModule *module = NULL, *module_next;
  904. os_mutex_lock(&registered_module_list_lock);
  905. module = bh_list_first_elem(registered_module_list);
  906. while (module) {
  907. module_next = bh_list_elem_next(module);
  908. if (module->module_name && !strcmp(module_name, module->module_name)) {
  909. break;
  910. }
  911. module = module_next;
  912. }
  913. os_mutex_unlock(&registered_module_list_lock);
  914. return module ? module->module : NULL;
  915. }
  916. /*
  917. * simply destroy all
  918. */
  919. static void
  920. wasm_runtime_destroy_registered_module_list()
  921. {
  922. WASMRegisteredModule *reg_module = NULL;
  923. os_mutex_lock(&registered_module_list_lock);
  924. reg_module = bh_list_first_elem(registered_module_list);
  925. while (reg_module) {
  926. WASMRegisteredModule *next_reg_module = bh_list_elem_next(reg_module);
  927. bh_list_remove(registered_module_list, reg_module);
  928. /* now, it is time to release every module in the runtime */
  929. if (reg_module->module->module_type == Wasm_Module_Bytecode) {
  930. #if WASM_ENABLE_INTERP != 0
  931. wasm_unload((WASMModule *)reg_module->module);
  932. #endif
  933. }
  934. else {
  935. #if WASM_ENABLE_AOT != 0
  936. aot_unload((AOTModule *)reg_module->module);
  937. #endif
  938. }
  939. /* destroy the file buffer */
  940. if (destroyer && reg_module->orig_file_buf) {
  941. destroyer(reg_module->orig_file_buf,
  942. reg_module->orig_file_buf_size);
  943. reg_module->orig_file_buf = NULL;
  944. reg_module->orig_file_buf_size = 0;
  945. }
  946. wasm_runtime_free(reg_module);
  947. reg_module = next_reg_module;
  948. }
  949. os_mutex_unlock(&registered_module_list_lock);
  950. }
  951. bool
  952. wasm_runtime_add_loading_module(const char *module_name, char *error_buf,
  953. uint32 error_buf_size)
  954. {
  955. LOG_DEBUG("add %s into a loading list", module_name);
  956. LoadingModule *loadingModule =
  957. runtime_malloc(sizeof(LoadingModule), NULL, error_buf, error_buf_size);
  958. if (!loadingModule) {
  959. return false;
  960. }
  961. /* share the incoming string */
  962. loadingModule->module_name = module_name;
  963. os_mutex_lock(&loading_module_list_lock);
  964. bh_list_status ret = bh_list_insert(loading_module_list, loadingModule);
  965. bh_assert(BH_LIST_SUCCESS == ret);
  966. (void)ret;
  967. os_mutex_unlock(&loading_module_list_lock);
  968. return true;
  969. }
  970. void
  971. wasm_runtime_delete_loading_module(const char *module_name)
  972. {
  973. LOG_DEBUG("delete %s from a loading list", module_name);
  974. LoadingModule *module = NULL;
  975. os_mutex_lock(&loading_module_list_lock);
  976. module = bh_list_first_elem(loading_module_list);
  977. while (module && strcmp(module->module_name, module_name)) {
  978. module = bh_list_elem_next(module);
  979. }
  980. /* it does not matter if it is not exist. after all, it is gone */
  981. if (module) {
  982. bh_list_remove(loading_module_list, module);
  983. wasm_runtime_free(module);
  984. }
  985. os_mutex_unlock(&loading_module_list_lock);
  986. }
  987. bool
  988. wasm_runtime_is_loading_module(const char *module_name)
  989. {
  990. LOG_DEBUG("find %s in a loading list", module_name);
  991. LoadingModule *module = NULL;
  992. os_mutex_lock(&loading_module_list_lock);
  993. module = bh_list_first_elem(loading_module_list);
  994. while (module && strcmp(module_name, module->module_name)) {
  995. module = bh_list_elem_next(module);
  996. }
  997. os_mutex_unlock(&loading_module_list_lock);
  998. return module != NULL;
  999. }
  1000. void
  1001. wasm_runtime_destroy_loading_module_list()
  1002. {
  1003. LoadingModule *module = NULL;
  1004. os_mutex_lock(&loading_module_list_lock);
  1005. module = bh_list_first_elem(loading_module_list);
  1006. while (module) {
  1007. LoadingModule *next_module = bh_list_elem_next(module);
  1008. bh_list_remove(loading_module_list, module);
  1009. /*
  1010. * will not free the module_name since it is
  1011. * shared one of the const string pool
  1012. */
  1013. wasm_runtime_free(module);
  1014. module = next_module;
  1015. }
  1016. os_mutex_unlock(&loading_module_list_lock);
  1017. }
  1018. #endif /* WASM_ENABLE_MULTI_MODULE */
  1019. bool
  1020. wasm_runtime_is_built_in_module(const char *module_name)
  1021. {
  1022. return (!strcmp("env", module_name) || !strcmp("wasi_unstable", module_name)
  1023. || !strcmp("wasi_snapshot_preview1", module_name)
  1024. #if WASM_ENABLE_SPEC_TEST != 0
  1025. || !strcmp("spectest", module_name)
  1026. #endif
  1027. || !strcmp("", module_name));
  1028. }
  1029. #if WASM_ENABLE_THREAD_MGR != 0
  1030. bool
  1031. wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset,
  1032. uint32 size)
  1033. {
  1034. WASMModuleInstanceCommon *module_inst =
  1035. wasm_exec_env_get_module_inst(exec_env);
  1036. #if WASM_ENABLE_INTERP != 0
  1037. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1038. return wasm_set_aux_stack(exec_env, start_offset, size);
  1039. }
  1040. #endif
  1041. #if WASM_ENABLE_AOT != 0
  1042. if (module_inst->module_type == Wasm_Module_AoT) {
  1043. return aot_set_aux_stack(exec_env, start_offset, size);
  1044. }
  1045. #endif
  1046. return false;
  1047. }
  1048. bool
  1049. wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset,
  1050. uint32 *size)
  1051. {
  1052. WASMModuleInstanceCommon *module_inst =
  1053. wasm_exec_env_get_module_inst(exec_env);
  1054. #if WASM_ENABLE_INTERP != 0
  1055. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1056. return wasm_get_aux_stack(exec_env, start_offset, size);
  1057. }
  1058. #endif
  1059. #if WASM_ENABLE_AOT != 0
  1060. if (module_inst->module_type == Wasm_Module_AoT) {
  1061. return aot_get_aux_stack(exec_env, start_offset, size);
  1062. }
  1063. #endif
  1064. return false;
  1065. }
  1066. void
  1067. wasm_runtime_set_max_thread_num(uint32 num)
  1068. {
  1069. wasm_cluster_set_max_thread_num(num);
  1070. }
  1071. #endif /* end of WASM_ENABLE_THREAD_MGR */
  1072. static WASMModuleCommon *
  1073. register_module_with_null_name(WASMModuleCommon *module_common, char *error_buf,
  1074. uint32 error_buf_size)
  1075. {
  1076. #if WASM_ENABLE_MULTI_MODULE != 0
  1077. if (module_common) {
  1078. if (!wasm_runtime_register_module_internal(NULL, module_common, NULL, 0,
  1079. error_buf, error_buf_size)) {
  1080. wasm_runtime_unload(module_common);
  1081. return NULL;
  1082. }
  1083. return module_common;
  1084. }
  1085. else
  1086. return NULL;
  1087. #else
  1088. return module_common;
  1089. #endif
  1090. }
  1091. WASMModuleCommon *
  1092. wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf,
  1093. uint32 error_buf_size)
  1094. {
  1095. WASMModuleCommon *module_common = NULL;
  1096. if (get_package_type(buf, size) == Wasm_Module_Bytecode) {
  1097. #if WASM_ENABLE_INTERP != 0
  1098. module_common =
  1099. (WASMModuleCommon *)wasm_load(buf, size,
  1100. #if WASM_ENABLE_MULTI_MODULE != 0
  1101. true,
  1102. #endif
  1103. error_buf, error_buf_size);
  1104. #endif
  1105. }
  1106. else if (get_package_type(buf, size) == Wasm_Module_AoT) {
  1107. #if WASM_ENABLE_AOT != 0
  1108. module_common = (WASMModuleCommon *)aot_load_from_aot_file(
  1109. buf, size, error_buf, error_buf_size);
  1110. #endif
  1111. }
  1112. else {
  1113. if (size < 4)
  1114. set_error_buf(error_buf, error_buf_size,
  1115. "WASM module load failed: unexpected end");
  1116. else
  1117. set_error_buf(error_buf, error_buf_size,
  1118. "WASM module load failed: magic header not detected");
  1119. return NULL;
  1120. }
  1121. if (!module_common) {
  1122. LOG_DEBUG("WASM module load failed");
  1123. return NULL;
  1124. }
  1125. return register_module_with_null_name(module_common, error_buf,
  1126. error_buf_size);
  1127. }
  1128. WASMModuleCommon *
  1129. wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot,
  1130. char *error_buf, uint32 error_buf_size)
  1131. {
  1132. WASMModuleCommon *module_common;
  1133. if (!is_aot) {
  1134. #if WASM_ENABLE_INTERP != 0
  1135. module_common = (WASMModuleCommon *)wasm_load_from_sections(
  1136. section_list, error_buf, error_buf_size);
  1137. if (!module_common) {
  1138. LOG_DEBUG("WASM module load failed from sections");
  1139. return NULL;
  1140. }
  1141. return register_module_with_null_name(module_common, error_buf,
  1142. error_buf_size);
  1143. #endif
  1144. }
  1145. else {
  1146. #if WASM_ENABLE_AOT != 0
  1147. module_common = (WASMModuleCommon *)aot_load_from_sections(
  1148. section_list, error_buf, error_buf_size);
  1149. if (!module_common) {
  1150. LOG_DEBUG("WASM module load failed from sections");
  1151. return NULL;
  1152. }
  1153. return register_module_with_null_name(module_common, error_buf,
  1154. error_buf_size);
  1155. #endif
  1156. }
  1157. #if WASM_ENABLE_INTERP == 0 || WASM_ENABLE_AOT == 0
  1158. set_error_buf(error_buf, error_buf_size,
  1159. "WASM module load failed: invalid section list type");
  1160. return NULL;
  1161. #endif
  1162. }
  1163. void
  1164. wasm_runtime_unload(WASMModuleCommon *module)
  1165. {
  1166. #if WASM_ENABLE_MULTI_MODULE != 0
  1167. /**
  1168. * since we will unload and free all module when runtime_destroy()
  1169. * we don't want users to unwillingly disrupt it
  1170. */
  1171. return;
  1172. #endif
  1173. #if WASM_ENABLE_INTERP != 0
  1174. if (module->module_type == Wasm_Module_Bytecode) {
  1175. wasm_unload((WASMModule *)module);
  1176. return;
  1177. }
  1178. #endif
  1179. #if WASM_ENABLE_AOT != 0
  1180. if (module->module_type == Wasm_Module_AoT) {
  1181. aot_unload((AOTModule *)module);
  1182. return;
  1183. }
  1184. #endif
  1185. }
  1186. WASMModuleInstanceCommon *
  1187. wasm_runtime_instantiate_internal(WASMModuleCommon *module,
  1188. WASMModuleInstanceCommon *parent,
  1189. WASMExecEnv *exec_env_main, uint32 stack_size,
  1190. uint32 heap_size, char *error_buf,
  1191. uint32 error_buf_size)
  1192. {
  1193. #if WASM_ENABLE_INTERP != 0
  1194. if (module->module_type == Wasm_Module_Bytecode)
  1195. return (WASMModuleInstanceCommon *)wasm_instantiate(
  1196. (WASMModule *)module, (WASMModuleInstance *)parent, exec_env_main,
  1197. stack_size, heap_size, error_buf, error_buf_size);
  1198. #endif
  1199. #if WASM_ENABLE_AOT != 0
  1200. if (module->module_type == Wasm_Module_AoT)
  1201. return (WASMModuleInstanceCommon *)aot_instantiate(
  1202. (AOTModule *)module, (AOTModuleInstance *)parent, exec_env_main,
  1203. stack_size, heap_size, error_buf, error_buf_size);
  1204. #endif
  1205. set_error_buf(error_buf, error_buf_size,
  1206. "Instantiate module failed, invalid module type");
  1207. return NULL;
  1208. }
  1209. WASMModuleInstanceCommon *
  1210. wasm_runtime_instantiate(WASMModuleCommon *module, uint32 stack_size,
  1211. uint32 heap_size, char *error_buf,
  1212. uint32 error_buf_size)
  1213. {
  1214. return wasm_runtime_instantiate_internal(
  1215. module, NULL, NULL, stack_size, heap_size, error_buf, error_buf_size);
  1216. }
  1217. void
  1218. wasm_runtime_deinstantiate_internal(WASMModuleInstanceCommon *module_inst,
  1219. bool is_sub_inst)
  1220. {
  1221. #if WASM_ENABLE_INTERP != 0
  1222. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1223. wasm_deinstantiate((WASMModuleInstance *)module_inst, is_sub_inst);
  1224. return;
  1225. }
  1226. #endif
  1227. #if WASM_ENABLE_AOT != 0
  1228. if (module_inst->module_type == Wasm_Module_AoT) {
  1229. aot_deinstantiate((AOTModuleInstance *)module_inst, is_sub_inst);
  1230. return;
  1231. }
  1232. #endif
  1233. }
  1234. bool
  1235. wasm_runtime_set_running_mode(wasm_module_inst_t module_inst,
  1236. RunningMode running_mode)
  1237. {
  1238. #if WASM_ENABLE_AOT != 0
  1239. if (module_inst->module_type == Wasm_Module_AoT)
  1240. return true;
  1241. #endif
  1242. #if WASM_ENABLE_INTERP != 0
  1243. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1244. WASMModuleInstance *module_inst_interp =
  1245. (WASMModuleInstance *)module_inst;
  1246. return wasm_set_running_mode(module_inst_interp, running_mode);
  1247. }
  1248. #endif
  1249. return false;
  1250. }
  1251. RunningMode
  1252. wasm_runtime_get_running_mode(wasm_module_inst_t module_inst)
  1253. {
  1254. #if WASM_ENABLE_INTERP != 0
  1255. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1256. WASMModuleInstance *module_inst_interp =
  1257. (WASMModuleInstance *)module_inst;
  1258. return module_inst_interp->e->running_mode;
  1259. }
  1260. #endif
  1261. return Mode_Default;
  1262. }
  1263. void
  1264. wasm_runtime_deinstantiate(WASMModuleInstanceCommon *module_inst)
  1265. {
  1266. wasm_runtime_deinstantiate_internal(module_inst, false);
  1267. }
  1268. WASMModuleCommon *
  1269. wasm_runtime_get_module(WASMModuleInstanceCommon *module_inst)
  1270. {
  1271. return (WASMModuleCommon *)((WASMModuleInstance *)module_inst)->module;
  1272. }
  1273. WASMExecEnv *
  1274. wasm_runtime_create_exec_env(WASMModuleInstanceCommon *module_inst,
  1275. uint32 stack_size)
  1276. {
  1277. return wasm_exec_env_create(module_inst, stack_size);
  1278. }
  1279. void
  1280. wasm_runtime_destroy_exec_env(WASMExecEnv *exec_env)
  1281. {
  1282. wasm_exec_env_destroy(exec_env);
  1283. }
  1284. bool
  1285. wasm_runtime_init_thread_env(void)
  1286. {
  1287. #ifdef BH_PLATFORM_WINDOWS
  1288. if (os_thread_env_init() != 0)
  1289. return false;
  1290. #endif
  1291. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1292. if (!runtime_signal_init()) {
  1293. #ifdef BH_PLATFORM_WINDOWS
  1294. os_thread_env_destroy();
  1295. #endif
  1296. return false;
  1297. }
  1298. #endif
  1299. #if WASM_ENABLE_THREAD_MGR != 0 && defined(OS_ENABLE_WAKEUP_BLOCKING_OP)
  1300. os_end_blocking_op();
  1301. #endif
  1302. return true;
  1303. }
  1304. void
  1305. wasm_runtime_destroy_thread_env(void)
  1306. {
  1307. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1308. runtime_signal_destroy();
  1309. #endif
  1310. #ifdef BH_PLATFORM_WINDOWS
  1311. os_thread_env_destroy();
  1312. #endif
  1313. }
  1314. bool
  1315. wasm_runtime_thread_env_inited(void)
  1316. {
  1317. #ifdef BH_PLATFORM_WINDOWS
  1318. if (!os_thread_env_inited())
  1319. return false;
  1320. #endif
  1321. #if WASM_ENABLE_AOT != 0
  1322. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1323. if (!os_thread_signal_inited())
  1324. return false;
  1325. #endif
  1326. #endif
  1327. return true;
  1328. }
  1329. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  1330. void
  1331. wasm_runtime_dump_module_mem_consumption(const WASMModuleCommon *module)
  1332. {
  1333. WASMModuleMemConsumption mem_conspn = { 0 };
  1334. #if WASM_ENABLE_INTERP != 0
  1335. if (module->module_type == Wasm_Module_Bytecode) {
  1336. wasm_get_module_mem_consumption((WASMModule *)module, &mem_conspn);
  1337. }
  1338. #endif
  1339. #if WASM_ENABLE_AOT != 0
  1340. if (module->module_type == Wasm_Module_AoT) {
  1341. aot_get_module_mem_consumption((AOTModule *)module, &mem_conspn);
  1342. }
  1343. #endif
  1344. os_printf("WASM module memory consumption, total size: %u\n",
  1345. mem_conspn.total_size);
  1346. os_printf(" module struct size: %u\n", mem_conspn.module_struct_size);
  1347. os_printf(" types size: %u\n", mem_conspn.types_size);
  1348. os_printf(" imports size: %u\n", mem_conspn.imports_size);
  1349. os_printf(" funcs size: %u\n", mem_conspn.functions_size);
  1350. os_printf(" tables size: %u\n", mem_conspn.tables_size);
  1351. os_printf(" memories size: %u\n", mem_conspn.memories_size);
  1352. os_printf(" globals size: %u\n", mem_conspn.globals_size);
  1353. os_printf(" exports size: %u\n", mem_conspn.exports_size);
  1354. os_printf(" table segs size: %u\n", mem_conspn.table_segs_size);
  1355. os_printf(" data segs size: %u\n", mem_conspn.data_segs_size);
  1356. os_printf(" const strings size: %u\n", mem_conspn.const_strs_size);
  1357. #if WASM_ENABLE_AOT != 0
  1358. os_printf(" aot code size: %u\n", mem_conspn.aot_code_size);
  1359. #endif
  1360. }
  1361. void
  1362. wasm_runtime_dump_module_inst_mem_consumption(
  1363. const WASMModuleInstanceCommon *module_inst)
  1364. {
  1365. WASMModuleInstMemConsumption mem_conspn = { 0 };
  1366. #if WASM_ENABLE_INTERP != 0
  1367. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1368. wasm_get_module_inst_mem_consumption((WASMModuleInstance *)module_inst,
  1369. &mem_conspn);
  1370. }
  1371. #endif
  1372. #if WASM_ENABLE_AOT != 0
  1373. if (module_inst->module_type == Wasm_Module_AoT) {
  1374. aot_get_module_inst_mem_consumption((AOTModuleInstance *)module_inst,
  1375. &mem_conspn);
  1376. }
  1377. #endif
  1378. os_printf("WASM module inst memory consumption, total size: %u\n",
  1379. mem_conspn.total_size);
  1380. os_printf(" module inst struct size: %u\n",
  1381. mem_conspn.module_inst_struct_size);
  1382. os_printf(" memories size: %u\n", mem_conspn.memories_size);
  1383. os_printf(" app heap size: %u\n", mem_conspn.app_heap_size);
  1384. os_printf(" tables size: %u\n", mem_conspn.tables_size);
  1385. os_printf(" functions size: %u\n", mem_conspn.functions_size);
  1386. os_printf(" globals size: %u\n", mem_conspn.globals_size);
  1387. os_printf(" exports size: %u\n", mem_conspn.exports_size);
  1388. }
  1389. void
  1390. wasm_runtime_dump_exec_env_mem_consumption(const WASMExecEnv *exec_env)
  1391. {
  1392. uint32 total_size =
  1393. offsetof(WASMExecEnv, wasm_stack_u.bottom) + exec_env->wasm_stack_size;
  1394. os_printf("Exec env memory consumption, total size: %u\n", total_size);
  1395. os_printf(" exec env struct size: %u\n",
  1396. offsetof(WASMExecEnv, wasm_stack_u.bottom));
  1397. #if WASM_ENABLE_INTERP != 0 && WASM_ENABLE_FAST_INTERP == 0
  1398. os_printf(" block addr cache size: %u\n",
  1399. sizeof(exec_env->block_addr_cache));
  1400. #endif
  1401. os_printf(" stack size: %u\n", exec_env->wasm_stack_size);
  1402. }
  1403. uint32
  1404. gc_get_heap_highmark_size(void *heap);
  1405. void
  1406. wasm_runtime_dump_mem_consumption(WASMExecEnv *exec_env)
  1407. {
  1408. WASMModuleInstMemConsumption module_inst_mem_consps;
  1409. WASMModuleMemConsumption module_mem_consps;
  1410. WASMModuleInstanceCommon *module_inst_common;
  1411. WASMModuleCommon *module_common = NULL;
  1412. void *heap_handle = NULL;
  1413. uint32 total_size = 0, app_heap_peak_size = 0;
  1414. uint32 max_aux_stack_used = -1;
  1415. module_inst_common = exec_env->module_inst;
  1416. #if WASM_ENABLE_INTERP != 0
  1417. if (module_inst_common->module_type == Wasm_Module_Bytecode) {
  1418. WASMModuleInstance *wasm_module_inst =
  1419. (WASMModuleInstance *)module_inst_common;
  1420. WASMModule *wasm_module = wasm_module_inst->module;
  1421. module_common = (WASMModuleCommon *)wasm_module;
  1422. if (wasm_module_inst->memories) {
  1423. heap_handle = wasm_module_inst->memories[0]->heap_handle;
  1424. }
  1425. wasm_get_module_inst_mem_consumption(wasm_module_inst,
  1426. &module_inst_mem_consps);
  1427. wasm_get_module_mem_consumption(wasm_module, &module_mem_consps);
  1428. if (wasm_module_inst->module->aux_stack_top_global_index != (uint32)-1)
  1429. max_aux_stack_used = wasm_module_inst->e->max_aux_stack_used;
  1430. }
  1431. #endif
  1432. #if WASM_ENABLE_AOT != 0
  1433. if (module_inst_common->module_type == Wasm_Module_AoT) {
  1434. AOTModuleInstance *aot_module_inst =
  1435. (AOTModuleInstance *)module_inst_common;
  1436. AOTModule *aot_module = (AOTModule *)aot_module_inst->module;
  1437. module_common = (WASMModuleCommon *)aot_module;
  1438. if (aot_module_inst->memories) {
  1439. AOTMemoryInstance **memories = aot_module_inst->memories;
  1440. heap_handle = memories[0]->heap_handle;
  1441. }
  1442. aot_get_module_inst_mem_consumption(aot_module_inst,
  1443. &module_inst_mem_consps);
  1444. aot_get_module_mem_consumption(aot_module, &module_mem_consps);
  1445. }
  1446. #endif
  1447. bh_assert(module_common != NULL);
  1448. if (heap_handle) {
  1449. app_heap_peak_size = gc_get_heap_highmark_size(heap_handle);
  1450. }
  1451. total_size = offsetof(WASMExecEnv, wasm_stack_u.bottom)
  1452. + exec_env->wasm_stack_size + module_mem_consps.total_size
  1453. + module_inst_mem_consps.total_size;
  1454. os_printf("\nMemory consumption summary (bytes):\n");
  1455. wasm_runtime_dump_module_mem_consumption(module_common);
  1456. wasm_runtime_dump_module_inst_mem_consumption(module_inst_common);
  1457. wasm_runtime_dump_exec_env_mem_consumption(exec_env);
  1458. os_printf("\nTotal memory consumption of module, module inst and "
  1459. "exec env: %u\n",
  1460. total_size);
  1461. os_printf("Total interpreter stack used: %u\n",
  1462. exec_env->max_wasm_stack_used);
  1463. if (max_aux_stack_used != (uint32)-1)
  1464. os_printf("Total auxiliary stack used: %u\n", max_aux_stack_used);
  1465. else
  1466. os_printf("Total aux stack used: no enough info to profile\n");
  1467. /*
  1468. * Report the native stack usage estimation.
  1469. *
  1470. * Unlike the aux stack above, we report the amount unused
  1471. * because we don't know the stack "bottom".
  1472. *
  1473. * Note that this is just about what the runtime itself observed.
  1474. * It doesn't cover host func implementations, signal handlers, etc.
  1475. */
  1476. if (exec_env->native_stack_top_min != (void *)UINTPTR_MAX)
  1477. os_printf("Native stack left: %zd\n",
  1478. exec_env->native_stack_top_min
  1479. - exec_env->native_stack_boundary);
  1480. else
  1481. os_printf("Native stack left: no enough info to profile\n");
  1482. os_printf("Total app heap used: %u\n", app_heap_peak_size);
  1483. }
  1484. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  1485. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  1486. #if WASM_ENABLE_PERF_PROFILING != 0
  1487. void
  1488. wasm_runtime_dump_perf_profiling(WASMModuleInstanceCommon *module_inst)
  1489. {
  1490. #if WASM_ENABLE_INTERP != 0
  1491. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1492. wasm_dump_perf_profiling((WASMModuleInstance *)module_inst);
  1493. }
  1494. #endif
  1495. #if WASM_ENABLE_AOT != 0
  1496. if (module_inst->module_type == Wasm_Module_AoT) {
  1497. aot_dump_perf_profiling((AOTModuleInstance *)module_inst);
  1498. }
  1499. #endif
  1500. }
  1501. #endif
  1502. WASMModuleInstanceCommon *
  1503. wasm_runtime_get_module_inst(WASMExecEnv *exec_env)
  1504. {
  1505. return wasm_exec_env_get_module_inst(exec_env);
  1506. }
  1507. void
  1508. wasm_runtime_set_module_inst(WASMExecEnv *exec_env,
  1509. WASMModuleInstanceCommon *const module_inst)
  1510. {
  1511. wasm_exec_env_set_module_inst(exec_env, module_inst);
  1512. }
  1513. void *
  1514. wasm_runtime_get_function_attachment(WASMExecEnv *exec_env)
  1515. {
  1516. return exec_env->attachment;
  1517. }
  1518. void
  1519. wasm_runtime_set_user_data(WASMExecEnv *exec_env, void *user_data)
  1520. {
  1521. exec_env->user_data = user_data;
  1522. }
  1523. void *
  1524. wasm_runtime_get_user_data(WASMExecEnv *exec_env)
  1525. {
  1526. return exec_env->user_data;
  1527. }
  1528. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1529. void
  1530. wasm_runtime_access_exce_check_guard_page()
  1531. {
  1532. if (exec_env_tls && exec_env_tls->handle == os_self_thread()) {
  1533. uint32 page_size = os_getpagesize();
  1534. memset(exec_env_tls->exce_check_guard_page, 0, page_size);
  1535. }
  1536. }
  1537. #endif
  1538. WASMFuncType *
  1539. wasm_runtime_get_function_type(const WASMFunctionInstanceCommon *function,
  1540. uint32 module_type)
  1541. {
  1542. WASMFuncType *type = NULL;
  1543. #if WASM_ENABLE_INTERP != 0
  1544. if (module_type == Wasm_Module_Bytecode) {
  1545. WASMFunctionInstance *wasm_func = (WASMFunctionInstance *)function;
  1546. type = wasm_func->is_import_func ? wasm_func->u.func_import->func_type
  1547. : wasm_func->u.func->func_type;
  1548. }
  1549. #endif
  1550. #if WASM_ENABLE_AOT != 0
  1551. if (module_type == Wasm_Module_AoT) {
  1552. AOTFunctionInstance *aot_func = (AOTFunctionInstance *)function;
  1553. type = aot_func->is_import_func ? aot_func->u.func_import->func_type
  1554. : aot_func->u.func.func_type;
  1555. }
  1556. #endif
  1557. return type;
  1558. }
  1559. WASMFunctionInstanceCommon *
  1560. wasm_runtime_lookup_function(WASMModuleInstanceCommon *const module_inst,
  1561. const char *name, const char *signature)
  1562. {
  1563. #if WASM_ENABLE_INTERP != 0
  1564. if (module_inst->module_type == Wasm_Module_Bytecode)
  1565. return (WASMFunctionInstanceCommon *)wasm_lookup_function(
  1566. (const WASMModuleInstance *)module_inst, name, signature);
  1567. #endif
  1568. #if WASM_ENABLE_AOT != 0
  1569. if (module_inst->module_type == Wasm_Module_AoT)
  1570. return (WASMFunctionInstanceCommon *)aot_lookup_function(
  1571. (const AOTModuleInstance *)module_inst, name, signature);
  1572. #endif
  1573. return NULL;
  1574. }
  1575. uint32
  1576. wasm_func_get_param_count(WASMFunctionInstanceCommon *const func_inst,
  1577. WASMModuleInstanceCommon *const module_inst)
  1578. {
  1579. WASMFuncType *type =
  1580. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1581. bh_assert(type);
  1582. return type->param_count;
  1583. }
  1584. uint32
  1585. wasm_func_get_result_count(WASMFunctionInstanceCommon *const func_inst,
  1586. WASMModuleInstanceCommon *const module_inst)
  1587. {
  1588. WASMFuncType *type =
  1589. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1590. bh_assert(type);
  1591. return type->result_count;
  1592. }
  1593. static uint8
  1594. val_type_to_val_kind(uint8 value_type)
  1595. {
  1596. switch (value_type) {
  1597. case VALUE_TYPE_I32:
  1598. return WASM_I32;
  1599. case VALUE_TYPE_I64:
  1600. return WASM_I64;
  1601. case VALUE_TYPE_F32:
  1602. return WASM_F32;
  1603. case VALUE_TYPE_F64:
  1604. return WASM_F64;
  1605. case VALUE_TYPE_FUNCREF:
  1606. return WASM_FUNCREF;
  1607. case VALUE_TYPE_EXTERNREF:
  1608. return WASM_ANYREF;
  1609. default:
  1610. bh_assert(0);
  1611. return 0;
  1612. }
  1613. }
  1614. void
  1615. wasm_func_get_param_types(WASMFunctionInstanceCommon *const func_inst,
  1616. WASMModuleInstanceCommon *const module_inst,
  1617. wasm_valkind_t *param_types)
  1618. {
  1619. WASMFuncType *type =
  1620. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1621. uint32 i;
  1622. bh_assert(type);
  1623. for (i = 0; i < type->param_count; i++) {
  1624. param_types[i] = val_type_to_val_kind(type->types[i]);
  1625. }
  1626. }
  1627. void
  1628. wasm_func_get_result_types(WASMFunctionInstanceCommon *const func_inst,
  1629. WASMModuleInstanceCommon *const module_inst,
  1630. wasm_valkind_t *result_types)
  1631. {
  1632. WASMFuncType *type =
  1633. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1634. uint32 i;
  1635. bh_assert(type);
  1636. for (i = 0; i < type->result_count; i++) {
  1637. result_types[i] =
  1638. val_type_to_val_kind(type->types[type->param_count + i]);
  1639. }
  1640. }
  1641. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  1642. /* (uintptr_t)externref -> (uint32)index */
  1643. /* argv -> *ret_argv */
  1644. static bool
  1645. wasm_runtime_prepare_call_function(WASMExecEnv *exec_env,
  1646. WASMFunctionInstanceCommon *function,
  1647. uint32 *argv, uint32 argc, uint32 **ret_argv,
  1648. uint32 *ret_argc_param,
  1649. uint32 *ret_argc_result)
  1650. {
  1651. uint32 *new_argv = NULL, argv_i = 0, new_argv_i = 0, param_i = 0,
  1652. result_i = 0;
  1653. bool need_param_transform = false, need_result_transform = false;
  1654. uint64 size = 0;
  1655. WASMFuncType *func_type = wasm_runtime_get_function_type(
  1656. function, exec_env->module_inst->module_type);
  1657. bh_assert(func_type);
  1658. *ret_argc_param = func_type->param_cell_num;
  1659. *ret_argc_result = func_type->ret_cell_num;
  1660. for (param_i = 0; param_i < func_type->param_count; param_i++) {
  1661. if (VALUE_TYPE_EXTERNREF == func_type->types[param_i]) {
  1662. need_param_transform = true;
  1663. }
  1664. }
  1665. for (result_i = 0; result_i < func_type->result_count; result_i++) {
  1666. if (VALUE_TYPE_EXTERNREF
  1667. == func_type->types[func_type->param_count + result_i]) {
  1668. need_result_transform = true;
  1669. }
  1670. }
  1671. if (!need_param_transform && !need_result_transform) {
  1672. *ret_argv = argv;
  1673. return true;
  1674. }
  1675. if (func_type->param_cell_num >= func_type->ret_cell_num) {
  1676. size = sizeof(uint32) * func_type->param_cell_num;
  1677. }
  1678. else {
  1679. size = sizeof(uint32) * func_type->ret_cell_num;
  1680. }
  1681. if (!(new_argv = runtime_malloc(size, exec_env->module_inst, NULL, 0))) {
  1682. return false;
  1683. }
  1684. if (!need_param_transform) {
  1685. bh_memcpy_s(new_argv, (uint32)size, argv, (uint32)size);
  1686. }
  1687. else {
  1688. for (param_i = 0; param_i < func_type->param_count && argv_i < argc
  1689. && new_argv_i < func_type->param_cell_num;
  1690. param_i++) {
  1691. uint8 param_type = func_type->types[param_i];
  1692. if (VALUE_TYPE_EXTERNREF == param_type) {
  1693. void *externref_obj;
  1694. uint32 externref_index;
  1695. #if UINTPTR_MAX == UINT32_MAX
  1696. externref_obj = (void *)argv[argv_i];
  1697. #else
  1698. union {
  1699. uintptr_t val;
  1700. uint32 parts[2];
  1701. } u;
  1702. u.parts[0] = argv[argv_i];
  1703. u.parts[1] = argv[argv_i + 1];
  1704. externref_obj = (void *)u.val;
  1705. #endif
  1706. if (!wasm_externref_obj2ref(exec_env->module_inst,
  1707. externref_obj, &externref_index)) {
  1708. wasm_runtime_free(new_argv);
  1709. return false;
  1710. }
  1711. new_argv[new_argv_i] = externref_index;
  1712. argv_i += sizeof(uintptr_t) / sizeof(uint32);
  1713. new_argv_i++;
  1714. }
  1715. else {
  1716. uint16 param_cell_num = wasm_value_type_cell_num(param_type);
  1717. uint32 param_size = sizeof(uint32) * param_cell_num;
  1718. bh_memcpy_s(new_argv + new_argv_i, param_size, argv + argv_i,
  1719. param_size);
  1720. argv_i += param_cell_num;
  1721. new_argv_i += param_cell_num;
  1722. }
  1723. }
  1724. }
  1725. *ret_argv = new_argv;
  1726. return true;
  1727. }
  1728. /* (uintptr_t)externref <- (uint32)index */
  1729. /* argv <- new_argv */
  1730. static bool
  1731. wasm_runtime_finalize_call_function(WASMExecEnv *exec_env,
  1732. WASMFunctionInstanceCommon *function,
  1733. uint32 *argv, uint32 argc, uint32 *ret_argv)
  1734. {
  1735. uint32 argv_i = 0, result_i = 0, ret_argv_i = 0;
  1736. WASMFuncType *func_type;
  1737. bh_assert((argv && ret_argv) || (argc == 0));
  1738. if (argv == ret_argv) {
  1739. /* no need to transfrom externref results */
  1740. return true;
  1741. }
  1742. func_type = wasm_runtime_get_function_type(
  1743. function, exec_env->module_inst->module_type);
  1744. bh_assert(func_type);
  1745. for (result_i = 0; result_i < func_type->result_count && argv_i < argc;
  1746. result_i++) {
  1747. uint8 result_type = func_type->types[func_type->param_count + result_i];
  1748. if (result_type == VALUE_TYPE_EXTERNREF) {
  1749. void *externref_obj;
  1750. #if UINTPTR_MAX != UINT32_MAX
  1751. union {
  1752. uintptr_t val;
  1753. uint32 parts[2];
  1754. } u;
  1755. #endif
  1756. if (!wasm_externref_ref2obj(argv[argv_i], &externref_obj)) {
  1757. wasm_runtime_free(argv);
  1758. return false;
  1759. }
  1760. #if UINTPTR_MAX == UINT32_MAX
  1761. ret_argv[ret_argv_i] = (uintptr_t)externref_obj;
  1762. #else
  1763. u.val = (uintptr_t)externref_obj;
  1764. ret_argv[ret_argv_i] = u.parts[0];
  1765. ret_argv[ret_argv_i + 1] = u.parts[1];
  1766. #endif
  1767. argv_i += 1;
  1768. ret_argv_i += sizeof(uintptr_t) / sizeof(uint32);
  1769. }
  1770. else {
  1771. uint16 result_cell_num = wasm_value_type_cell_num(result_type);
  1772. uint32 result_size = sizeof(uint32) * result_cell_num;
  1773. bh_memcpy_s(ret_argv + ret_argv_i, result_size, argv + argv_i,
  1774. result_size);
  1775. argv_i += result_cell_num;
  1776. ret_argv_i += result_cell_num;
  1777. }
  1778. }
  1779. wasm_runtime_free(argv);
  1780. return true;
  1781. }
  1782. #endif
  1783. bool
  1784. wasm_runtime_call_wasm(WASMExecEnv *exec_env,
  1785. WASMFunctionInstanceCommon *function, uint32 argc,
  1786. uint32 argv[])
  1787. {
  1788. bool ret = false;
  1789. uint32 *new_argv = NULL, param_argc;
  1790. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  1791. uint32 result_argc = 0;
  1792. #endif
  1793. if (!wasm_runtime_exec_env_check(exec_env)) {
  1794. LOG_ERROR("Invalid exec env stack info.");
  1795. return false;
  1796. }
  1797. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  1798. if (!wasm_runtime_prepare_call_function(exec_env, function, argv, argc,
  1799. &new_argv, &param_argc,
  1800. &result_argc)) {
  1801. wasm_runtime_set_exception(exec_env->module_inst,
  1802. "the arguments conversion is failed");
  1803. return false;
  1804. }
  1805. #else
  1806. new_argv = argv;
  1807. param_argc = argc;
  1808. #endif
  1809. #if WASM_ENABLE_INTERP != 0
  1810. if (exec_env->module_inst->module_type == Wasm_Module_Bytecode)
  1811. ret = wasm_call_function(exec_env, (WASMFunctionInstance *)function,
  1812. param_argc, new_argv);
  1813. #endif
  1814. #if WASM_ENABLE_AOT != 0
  1815. if (exec_env->module_inst->module_type == Wasm_Module_AoT)
  1816. ret = aot_call_function(exec_env, (AOTFunctionInstance *)function,
  1817. param_argc, new_argv);
  1818. #endif
  1819. if (!ret) {
  1820. if (new_argv != argv) {
  1821. wasm_runtime_free(new_argv);
  1822. }
  1823. return false;
  1824. }
  1825. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  1826. if (!wasm_runtime_finalize_call_function(exec_env, function, new_argv,
  1827. result_argc, argv)) {
  1828. wasm_runtime_set_exception(exec_env->module_inst,
  1829. "the result conversion is failed");
  1830. return false;
  1831. }
  1832. #endif
  1833. return ret;
  1834. }
  1835. static void
  1836. parse_args_to_uint32_array(WASMFuncType *type, wasm_val_t *args,
  1837. uint32 *out_argv)
  1838. {
  1839. uint32 i, p;
  1840. for (i = 0, p = 0; i < type->param_count; i++) {
  1841. switch (args[i].kind) {
  1842. case WASM_I32:
  1843. out_argv[p++] = args[i].of.i32;
  1844. break;
  1845. case WASM_I64:
  1846. {
  1847. union {
  1848. uint64 val;
  1849. uint32 parts[2];
  1850. } u;
  1851. u.val = args[i].of.i64;
  1852. out_argv[p++] = u.parts[0];
  1853. out_argv[p++] = u.parts[1];
  1854. break;
  1855. }
  1856. case WASM_F32:
  1857. {
  1858. union {
  1859. float32 val;
  1860. uint32 part;
  1861. } u;
  1862. u.val = args[i].of.f32;
  1863. out_argv[p++] = u.part;
  1864. break;
  1865. }
  1866. case WASM_F64:
  1867. {
  1868. union {
  1869. float64 val;
  1870. uint32 parts[2];
  1871. } u;
  1872. u.val = args[i].of.f64;
  1873. out_argv[p++] = u.parts[0];
  1874. out_argv[p++] = u.parts[1];
  1875. break;
  1876. }
  1877. #if WASM_ENABLE_REF_TYPES != 0
  1878. #if WASM_ENABLE_GC == 0
  1879. case WASM_FUNCREF:
  1880. {
  1881. out_argv[p++] = args[i].of.i32;
  1882. break;
  1883. }
  1884. #else
  1885. case WASM_FUNCREF:
  1886. #endif
  1887. case WASM_ANYREF:
  1888. {
  1889. #if UINTPTR_MAX == UINT32_MAX
  1890. out_argv[p++] = args[i].of.foreign;
  1891. #else
  1892. union {
  1893. uintptr_t val;
  1894. uint32 parts[2];
  1895. } u;
  1896. u.val = (uintptr_t)args[i].of.foreign;
  1897. out_argv[p++] = u.parts[0];
  1898. out_argv[p++] = u.parts[1];
  1899. #endif
  1900. break;
  1901. }
  1902. #endif
  1903. default:
  1904. bh_assert(0);
  1905. break;
  1906. }
  1907. }
  1908. }
  1909. static void
  1910. parse_uint32_array_to_results(WASMFuncType *type, uint32 *argv,
  1911. wasm_val_t *out_results)
  1912. {
  1913. uint32 i, p;
  1914. for (i = 0, p = 0; i < type->result_count; i++) {
  1915. switch (type->types[type->param_count + i]) {
  1916. case VALUE_TYPE_I32:
  1917. out_results[i].kind = WASM_I32;
  1918. out_results[i].of.i32 = (int32)argv[p++];
  1919. break;
  1920. case VALUE_TYPE_I64:
  1921. {
  1922. union {
  1923. uint64 val;
  1924. uint32 parts[2];
  1925. } u;
  1926. u.parts[0] = argv[p++];
  1927. u.parts[1] = argv[p++];
  1928. out_results[i].kind = WASM_I64;
  1929. out_results[i].of.i64 = u.val;
  1930. break;
  1931. }
  1932. case VALUE_TYPE_F32:
  1933. {
  1934. union {
  1935. float32 val;
  1936. uint32 part;
  1937. } u;
  1938. u.part = argv[p++];
  1939. out_results[i].kind = WASM_F32;
  1940. out_results[i].of.f32 = u.val;
  1941. break;
  1942. }
  1943. case VALUE_TYPE_F64:
  1944. {
  1945. union {
  1946. float64 val;
  1947. uint32 parts[2];
  1948. } u;
  1949. u.parts[0] = argv[p++];
  1950. u.parts[1] = argv[p++];
  1951. out_results[i].kind = WASM_F64;
  1952. out_results[i].of.f64 = u.val;
  1953. break;
  1954. }
  1955. #if WASM_ENABLE_REF_TYPES != 0
  1956. #if WASM_ENABLE_GC == 0
  1957. case VALUE_TYPE_FUNCREF:
  1958. {
  1959. out_results[i].kind = WASM_I32;
  1960. out_results[i].of.i32 = (int32)argv[p++];
  1961. break;
  1962. }
  1963. case VALUE_TYPE_EXTERNREF:
  1964. #else
  1965. case REF_TYPE_FUNCREF:
  1966. case REF_TYPE_EXTERNREF:
  1967. case REF_TYPE_ANYREF:
  1968. case REF_TYPE_EQREF:
  1969. case REF_TYPE_HT_NULLABLE:
  1970. case REF_TYPE_HT_NON_NULLABLE:
  1971. case REF_TYPE_I31REF:
  1972. case REF_TYPE_NULLFUNCREF:
  1973. case REF_TYPE_NULLEXTERNREF:
  1974. case REF_TYPE_STRUCTREF:
  1975. case REF_TYPE_ARRAYREF:
  1976. case REF_TYPE_NULLREF:
  1977. #endif /* end of WASM_ENABLE_GC == 0 */
  1978. {
  1979. #if UINTPTR_MAX == UINT32_MAX
  1980. out_results[i].kind = WASM_ANYREF;
  1981. out_results[i].of.foreign = (uintptr_t)argv[p++];
  1982. #else
  1983. union {
  1984. uintptr_t val;
  1985. uint32 parts[2];
  1986. } u;
  1987. u.parts[0] = argv[p++];
  1988. u.parts[1] = argv[p++];
  1989. out_results[i].kind = WASM_ANYREF;
  1990. out_results[i].of.foreign = u.val;
  1991. #endif
  1992. break;
  1993. }
  1994. #endif /* end of WASM_ENABLE_REF_TYPES != 0 */
  1995. default:
  1996. bh_assert(0);
  1997. break;
  1998. }
  1999. }
  2000. }
  2001. bool
  2002. wasm_runtime_call_wasm_a(WASMExecEnv *exec_env,
  2003. WASMFunctionInstanceCommon *function,
  2004. uint32 num_results, wasm_val_t results[],
  2005. uint32 num_args, wasm_val_t args[])
  2006. {
  2007. uint32 argc, argv_buf[16] = { 0 }, *argv = argv_buf, cell_num, module_type;
  2008. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2009. uint32 i, param_size_in_double_world = 0, result_size_in_double_world = 0;
  2010. #endif
  2011. uint64 total_size;
  2012. WASMFuncType *type;
  2013. bool ret = false;
  2014. module_type = exec_env->module_inst->module_type;
  2015. type = wasm_runtime_get_function_type(function, module_type);
  2016. if (!type) {
  2017. LOG_ERROR("Function type get failed, WAMR Interpreter and AOT must be "
  2018. "enabled at least one.");
  2019. goto fail1;
  2020. }
  2021. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2022. for (i = 0; i < type->param_count; i++) {
  2023. param_size_in_double_world +=
  2024. wasm_value_type_cell_num_outside(type->types[i]);
  2025. }
  2026. for (i = 0; i < type->result_count; i++) {
  2027. result_size_in_double_world += wasm_value_type_cell_num_outside(
  2028. type->types[type->param_count + i]);
  2029. }
  2030. argc = param_size_in_double_world;
  2031. cell_num = (argc >= result_size_in_double_world)
  2032. ? argc
  2033. : result_size_in_double_world;
  2034. #else
  2035. argc = type->param_cell_num;
  2036. cell_num = (argc > type->ret_cell_num) ? argc : type->ret_cell_num;
  2037. #endif
  2038. if (num_results != type->result_count) {
  2039. LOG_ERROR(
  2040. "The result value number does not match the function declaration.");
  2041. goto fail1;
  2042. }
  2043. if (num_args != type->param_count) {
  2044. LOG_ERROR("The argument value number does not match the function "
  2045. "declaration.");
  2046. goto fail1;
  2047. }
  2048. total_size = sizeof(uint32) * (uint64)(cell_num > 2 ? cell_num : 2);
  2049. if (total_size > sizeof(argv_buf)) {
  2050. if (!(argv =
  2051. runtime_malloc(total_size, exec_env->module_inst, NULL, 0))) {
  2052. goto fail1;
  2053. }
  2054. }
  2055. parse_args_to_uint32_array(type, args, argv);
  2056. if (!(ret = wasm_runtime_call_wasm(exec_env, function, argc, argv)))
  2057. goto fail2;
  2058. parse_uint32_array_to_results(type, argv, results);
  2059. fail2:
  2060. if (argv != argv_buf)
  2061. wasm_runtime_free(argv);
  2062. fail1:
  2063. return ret;
  2064. }
  2065. bool
  2066. wasm_runtime_call_wasm_v(WASMExecEnv *exec_env,
  2067. WASMFunctionInstanceCommon *function,
  2068. uint32 num_results, wasm_val_t results[],
  2069. uint32 num_args, ...)
  2070. {
  2071. wasm_val_t args_buf[8] = { 0 }, *args = args_buf;
  2072. WASMFuncType *type = NULL;
  2073. bool ret = false;
  2074. uint64 total_size;
  2075. uint32 i = 0, module_type;
  2076. va_list vargs;
  2077. module_type = exec_env->module_inst->module_type;
  2078. type = wasm_runtime_get_function_type(function, module_type);
  2079. if (!type) {
  2080. LOG_ERROR("Function type get failed, WAMR Interpreter and AOT "
  2081. "must be enabled at least one.");
  2082. goto fail1;
  2083. }
  2084. if (num_args != type->param_count) {
  2085. LOG_ERROR("The argument value number does not match the "
  2086. "function declaration.");
  2087. goto fail1;
  2088. }
  2089. total_size = sizeof(wasm_val_t) * (uint64)num_args;
  2090. if (total_size > sizeof(args_buf)) {
  2091. if (!(args =
  2092. runtime_malloc(total_size, exec_env->module_inst, NULL, 0))) {
  2093. goto fail1;
  2094. }
  2095. }
  2096. va_start(vargs, num_args);
  2097. for (i = 0; i < num_args; i++) {
  2098. switch (type->types[i]) {
  2099. case VALUE_TYPE_I32:
  2100. args[i].kind = WASM_I32;
  2101. args[i].of.i32 = va_arg(vargs, uint32);
  2102. break;
  2103. case VALUE_TYPE_I64:
  2104. args[i].kind = WASM_I64;
  2105. args[i].of.i64 = va_arg(vargs, uint64);
  2106. break;
  2107. case VALUE_TYPE_F32:
  2108. args[i].kind = WASM_F32;
  2109. args[i].of.f32 = (float32)va_arg(vargs, float64);
  2110. break;
  2111. case VALUE_TYPE_F64:
  2112. args[i].kind = WASM_F64;
  2113. args[i].of.f64 = va_arg(vargs, float64);
  2114. break;
  2115. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2116. case VALUE_TYPE_FUNCREF:
  2117. {
  2118. args[i].kind = WASM_FUNCREF;
  2119. args[i].of.i32 = va_arg(vargs, uint32);
  2120. break;
  2121. }
  2122. case VALUE_TYPE_EXTERNREF:
  2123. {
  2124. args[i].kind = WASM_ANYREF;
  2125. args[i].of.foreign = va_arg(vargs, uintptr_t);
  2126. break;
  2127. }
  2128. #endif
  2129. default:
  2130. bh_assert(0);
  2131. break;
  2132. }
  2133. }
  2134. va_end(vargs);
  2135. ret = wasm_runtime_call_wasm_a(exec_env, function, num_results, results,
  2136. num_args, args);
  2137. if (args != args_buf)
  2138. wasm_runtime_free(args);
  2139. fail1:
  2140. return ret;
  2141. }
  2142. bool
  2143. wasm_runtime_create_exec_env_singleton(
  2144. WASMModuleInstanceCommon *module_inst_comm)
  2145. {
  2146. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2147. WASMExecEnv *exec_env = NULL;
  2148. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2149. || module_inst_comm->module_type == Wasm_Module_AoT);
  2150. if (module_inst->exec_env_singleton) {
  2151. return true;
  2152. }
  2153. exec_env = wasm_exec_env_create(module_inst_comm,
  2154. module_inst->default_wasm_stack_size);
  2155. if (exec_env)
  2156. module_inst->exec_env_singleton = exec_env;
  2157. return exec_env ? true : false;
  2158. }
  2159. WASMExecEnv *
  2160. wasm_runtime_get_exec_env_singleton(WASMModuleInstanceCommon *module_inst_comm)
  2161. {
  2162. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2163. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2164. || module_inst_comm->module_type == Wasm_Module_AoT);
  2165. if (!module_inst->exec_env_singleton) {
  2166. wasm_runtime_create_exec_env_singleton(module_inst_comm);
  2167. }
  2168. return module_inst->exec_env_singleton;
  2169. }
  2170. static void
  2171. wasm_set_exception_local(WASMModuleInstance *module_inst, const char *exception)
  2172. {
  2173. exception_lock(module_inst);
  2174. if (exception) {
  2175. snprintf(module_inst->cur_exception, sizeof(module_inst->cur_exception),
  2176. "Exception: %s", exception);
  2177. }
  2178. else {
  2179. module_inst->cur_exception[0] = '\0';
  2180. }
  2181. exception_unlock(module_inst);
  2182. }
  2183. void
  2184. wasm_set_exception(WASMModuleInstance *module_inst, const char *exception)
  2185. {
  2186. #if WASM_ENABLE_THREAD_MGR != 0
  2187. WASMExecEnv *exec_env =
  2188. wasm_clusters_search_exec_env((WASMModuleInstanceCommon *)module_inst);
  2189. if (exec_env) {
  2190. wasm_cluster_set_exception(exec_env, exception);
  2191. }
  2192. else {
  2193. wasm_set_exception_local(module_inst, exception);
  2194. }
  2195. #else
  2196. wasm_set_exception_local(module_inst, exception);
  2197. #endif
  2198. }
  2199. /* clang-format off */
  2200. static const char *exception_msgs[] = {
  2201. "unreachable", /* EXCE_UNREACHABLE */
  2202. "allocate memory failed", /* EXCE_OUT_OF_MEMORY */
  2203. "out of bounds memory access", /* EXCE_OUT_OF_BOUNDS_MEMORY_ACCESS */
  2204. "integer overflow", /* EXCE_INTEGER_OVERFLOW */
  2205. "integer divide by zero", /* EXCE_INTEGER_DIVIDE_BY_ZERO */
  2206. "invalid conversion to integer", /* EXCE_INVALID_CONVERSION_TO_INTEGER */
  2207. "indirect call type mismatch", /* EXCE_INVALID_FUNCTION_TYPE_INDEX */
  2208. "invalid function index", /* EXCE_INVALID_FUNCTION_INDEX */
  2209. "undefined element", /* EXCE_UNDEFINED_ELEMENT */
  2210. "uninitialized element", /* EXCE_UNINITIALIZED_ELEMENT */
  2211. "failed to call unlinked import function", /* EXCE_CALL_UNLINKED_IMPORT_FUNC */
  2212. "native stack overflow", /* EXCE_NATIVE_STACK_OVERFLOW */
  2213. "unaligned atomic", /* EXCE_UNALIGNED_ATOMIC */
  2214. "wasm auxiliary stack overflow", /* EXCE_AUX_STACK_OVERFLOW */
  2215. "wasm auxiliary stack underflow", /* EXCE_AUX_STACK_UNDERFLOW */
  2216. "out of bounds table access", /* EXCE_OUT_OF_BOUNDS_TABLE_ACCESS */
  2217. "wasm operand stack overflow", /* EXCE_OPERAND_STACK_OVERFLOW */
  2218. "failed to compile fast jit function", /* EXCE_FAILED_TO_COMPILE_FAST_JIT_FUNC */
  2219. /* GC related exceptions */
  2220. "null function object", /* EXCE_NULL_FUNC_OBJ */
  2221. "null structure object", /* EXCE_NULL_STRUCT_OBJ */
  2222. "null array reference", /* EXCE_NULL_ARRAY_OBJ */
  2223. "null i31 reference", /* EXCE_NULL_I31_OBJ */
  2224. "null reference", /* EXCE_NULL_REFERENCE */
  2225. "create rtt type failed", /* EXCE_FAILED_TO_CREATE_RTT_TYPE */
  2226. "create struct object failed", /* EXCE_FAILED_TO_CREATE_STRUCT_OBJ */
  2227. "create array object failed", /* EXCE_FAILED_TO_CREATE_ARRAY_OBJ */
  2228. "create externref object failed", /* EXCE_FAILED_TO_CREATE_EXTERNREF_OBJ */
  2229. "cast failure", /* EXCE_CAST_FAILURE */
  2230. "out of bounds array access", /* EXCE_ARRAY_IDX_OOB */
  2231. /* stringref related exceptions */
  2232. "create string object failed", /* EXCE_FAILED_TO_CREATE_STRING */
  2233. "create stringref failed", /* EXCE_FAILED_TO_CREATE_STRINGREF */
  2234. "create stringview failed", /* EXCE_FAILED_TO_CREATE_STRINGVIEW */
  2235. "encode failed", /* EXCE_FAILED_TO_ENCODE_STRING */
  2236. "", /* EXCE_ALREADY_THROWN */
  2237. };
  2238. /* clang-format on */
  2239. void
  2240. wasm_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  2241. {
  2242. if (id < EXCE_NUM)
  2243. wasm_set_exception(module_inst, exception_msgs[id]);
  2244. else
  2245. wasm_set_exception(module_inst, "unknown exception");
  2246. }
  2247. const char *
  2248. wasm_get_exception(WASMModuleInstance *module_inst)
  2249. {
  2250. if (module_inst->cur_exception[0] == '\0')
  2251. return NULL;
  2252. else
  2253. return module_inst->cur_exception;
  2254. }
  2255. bool
  2256. wasm_copy_exception(WASMModuleInstance *module_inst, char *exception_buf)
  2257. {
  2258. bool has_exception = false;
  2259. exception_lock(module_inst);
  2260. if (module_inst->cur_exception[0] != '\0') {
  2261. /* NULL is passed if the caller is not interested in getting the
  2262. * exception content, but only in knowing if an exception has been
  2263. * raised
  2264. */
  2265. if (exception_buf != NULL)
  2266. bh_memcpy_s(exception_buf, sizeof(module_inst->cur_exception),
  2267. module_inst->cur_exception,
  2268. sizeof(module_inst->cur_exception));
  2269. has_exception = true;
  2270. }
  2271. exception_unlock(module_inst);
  2272. return has_exception;
  2273. }
  2274. void
  2275. wasm_runtime_set_exception(WASMModuleInstanceCommon *module_inst_comm,
  2276. const char *exception)
  2277. {
  2278. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2279. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2280. || module_inst_comm->module_type == Wasm_Module_AoT);
  2281. wasm_set_exception(module_inst, exception);
  2282. }
  2283. const char *
  2284. wasm_runtime_get_exception(WASMModuleInstanceCommon *module_inst_comm)
  2285. {
  2286. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2287. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2288. || module_inst_comm->module_type == Wasm_Module_AoT);
  2289. return wasm_get_exception(module_inst);
  2290. }
  2291. bool
  2292. wasm_runtime_copy_exception(WASMModuleInstanceCommon *module_inst_comm,
  2293. char *exception_buf)
  2294. {
  2295. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2296. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2297. || module_inst_comm->module_type == Wasm_Module_AoT);
  2298. return wasm_copy_exception(module_inst, exception_buf);
  2299. }
  2300. void
  2301. wasm_runtime_clear_exception(WASMModuleInstanceCommon *module_inst_comm)
  2302. {
  2303. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2304. || module_inst_comm->module_type == Wasm_Module_AoT);
  2305. wasm_runtime_set_exception(module_inst_comm, NULL);
  2306. }
  2307. void
  2308. wasm_runtime_terminate(WASMModuleInstanceCommon *module_inst_comm)
  2309. {
  2310. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2311. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2312. || module_inst_comm->module_type == Wasm_Module_AoT);
  2313. wasm_set_exception(module_inst, "terminated by user");
  2314. }
  2315. void
  2316. wasm_runtime_set_custom_data_internal(
  2317. WASMModuleInstanceCommon *module_inst_comm, void *custom_data)
  2318. {
  2319. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2320. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2321. || module_inst_comm->module_type == Wasm_Module_AoT);
  2322. module_inst->custom_data = custom_data;
  2323. }
  2324. void
  2325. wasm_runtime_set_custom_data(WASMModuleInstanceCommon *module_inst,
  2326. void *custom_data)
  2327. {
  2328. #if WASM_ENABLE_THREAD_MGR != 0
  2329. wasm_cluster_spread_custom_data(module_inst, custom_data);
  2330. #else
  2331. wasm_runtime_set_custom_data_internal(module_inst, custom_data);
  2332. #endif
  2333. }
  2334. void *
  2335. wasm_runtime_get_custom_data(WASMModuleInstanceCommon *module_inst_comm)
  2336. {
  2337. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2338. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2339. || module_inst_comm->module_type == Wasm_Module_AoT);
  2340. return module_inst->custom_data;
  2341. }
  2342. #if WASM_CONFIGURABLE_BOUNDS_CHECKS != 0
  2343. void
  2344. wasm_runtime_set_bounds_checks(WASMModuleInstanceCommon *module_inst,
  2345. bool enable)
  2346. {
  2347. /* Alwary disable bounds checks if hw bounds checks enabled */
  2348. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2349. enable = false;
  2350. #endif
  2351. #if WASM_ENABLE_INTERP != 0
  2352. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2353. ((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)->e)
  2354. ->common.disable_bounds_checks = enable ? false : true;
  2355. }
  2356. #endif
  2357. #if WASM_ENABLE_AOT != 0
  2358. if (module_inst->module_type == Wasm_Module_AoT) {
  2359. ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e)
  2360. ->common.disable_bounds_checks = enable ? false : true;
  2361. }
  2362. #endif
  2363. }
  2364. bool
  2365. wasm_runtime_is_bounds_checks_enabled(WASMModuleInstanceCommon *module_inst)
  2366. {
  2367. #if WASM_ENABLE_INTERP != 0
  2368. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2369. return !((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)
  2370. ->e)
  2371. ->common.disable_bounds_checks;
  2372. }
  2373. #endif
  2374. #if WASM_ENABLE_AOT != 0
  2375. if (module_inst->module_type == Wasm_Module_AoT) {
  2376. return !((AOTModuleInstanceExtra *)((WASMModuleInstance *)module_inst)
  2377. ->e)
  2378. ->common.disable_bounds_checks;
  2379. }
  2380. #endif
  2381. return true;
  2382. }
  2383. #endif
  2384. uint32
  2385. wasm_runtime_module_malloc_internal(WASMModuleInstanceCommon *module_inst,
  2386. WASMExecEnv *exec_env, uint32 size,
  2387. void **p_native_addr)
  2388. {
  2389. #if WASM_ENABLE_INTERP != 0
  2390. if (module_inst->module_type == Wasm_Module_Bytecode)
  2391. return wasm_module_malloc_internal((WASMModuleInstance *)module_inst,
  2392. exec_env, size, p_native_addr);
  2393. #endif
  2394. #if WASM_ENABLE_AOT != 0
  2395. if (module_inst->module_type == Wasm_Module_AoT)
  2396. return aot_module_malloc_internal((AOTModuleInstance *)module_inst,
  2397. exec_env, size, p_native_addr);
  2398. #endif
  2399. return 0;
  2400. }
  2401. uint32
  2402. wasm_runtime_module_realloc_internal(WASMModuleInstanceCommon *module_inst,
  2403. WASMExecEnv *exec_env, uint32 ptr,
  2404. uint32 size, void **p_native_addr)
  2405. {
  2406. #if WASM_ENABLE_INTERP != 0
  2407. if (module_inst->module_type == Wasm_Module_Bytecode)
  2408. return wasm_module_realloc_internal((WASMModuleInstance *)module_inst,
  2409. exec_env, ptr, size, p_native_addr);
  2410. #endif
  2411. #if WASM_ENABLE_AOT != 0
  2412. if (module_inst->module_type == Wasm_Module_AoT)
  2413. return aot_module_realloc_internal((AOTModuleInstance *)module_inst,
  2414. exec_env, ptr, size, p_native_addr);
  2415. #endif
  2416. return 0;
  2417. }
  2418. void
  2419. wasm_runtime_module_free_internal(WASMModuleInstanceCommon *module_inst,
  2420. WASMExecEnv *exec_env, uint32 ptr)
  2421. {
  2422. #if WASM_ENABLE_INTERP != 0
  2423. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2424. wasm_module_free_internal((WASMModuleInstance *)module_inst, exec_env,
  2425. ptr);
  2426. return;
  2427. }
  2428. #endif
  2429. #if WASM_ENABLE_AOT != 0
  2430. if (module_inst->module_type == Wasm_Module_AoT) {
  2431. aot_module_free_internal((AOTModuleInstance *)module_inst, exec_env,
  2432. ptr);
  2433. return;
  2434. }
  2435. #endif
  2436. }
  2437. uint32
  2438. wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint32 size,
  2439. void **p_native_addr)
  2440. {
  2441. #if WASM_ENABLE_INTERP != 0
  2442. if (module_inst->module_type == Wasm_Module_Bytecode)
  2443. return wasm_module_malloc((WASMModuleInstance *)module_inst, size,
  2444. p_native_addr);
  2445. #endif
  2446. #if WASM_ENABLE_AOT != 0
  2447. if (module_inst->module_type == Wasm_Module_AoT)
  2448. return aot_module_malloc((AOTModuleInstance *)module_inst, size,
  2449. p_native_addr);
  2450. #endif
  2451. return 0;
  2452. }
  2453. uint32
  2454. wasm_runtime_module_realloc(WASMModuleInstanceCommon *module_inst, uint32 ptr,
  2455. uint32 size, void **p_native_addr)
  2456. {
  2457. #if WASM_ENABLE_INTERP != 0
  2458. if (module_inst->module_type == Wasm_Module_Bytecode)
  2459. return wasm_module_realloc((WASMModuleInstance *)module_inst, ptr, size,
  2460. p_native_addr);
  2461. #endif
  2462. #if WASM_ENABLE_AOT != 0
  2463. if (module_inst->module_type == Wasm_Module_AoT)
  2464. return aot_module_realloc((AOTModuleInstance *)module_inst, ptr, size,
  2465. p_native_addr);
  2466. #endif
  2467. return 0;
  2468. }
  2469. void
  2470. wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint32 ptr)
  2471. {
  2472. #if WASM_ENABLE_INTERP != 0
  2473. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2474. wasm_module_free((WASMModuleInstance *)module_inst, ptr);
  2475. return;
  2476. }
  2477. #endif
  2478. #if WASM_ENABLE_AOT != 0
  2479. if (module_inst->module_type == Wasm_Module_AoT) {
  2480. aot_module_free((AOTModuleInstance *)module_inst, ptr);
  2481. return;
  2482. }
  2483. #endif
  2484. }
  2485. uint32
  2486. wasm_runtime_module_dup_data(WASMModuleInstanceCommon *module_inst,
  2487. const char *src, uint32 size)
  2488. {
  2489. #if WASM_ENABLE_INTERP != 0
  2490. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2491. return wasm_module_dup_data((WASMModuleInstance *)module_inst, src,
  2492. size);
  2493. }
  2494. #endif
  2495. #if WASM_ENABLE_AOT != 0
  2496. if (module_inst->module_type == Wasm_Module_AoT) {
  2497. return aot_module_dup_data((AOTModuleInstance *)module_inst, src, size);
  2498. }
  2499. #endif
  2500. return 0;
  2501. }
  2502. #if WASM_ENABLE_LIBC_WASI != 0
  2503. static WASIArguments *
  2504. get_wasi_args_from_module(wasm_module_t module)
  2505. {
  2506. WASIArguments *wasi_args = NULL;
  2507. #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0
  2508. if (module->module_type == Wasm_Module_Bytecode)
  2509. wasi_args = &((WASMModule *)module)->wasi_args;
  2510. #endif
  2511. #if WASM_ENABLE_AOT != 0
  2512. if (module->module_type == Wasm_Module_AoT)
  2513. wasi_args = &((AOTModule *)module)->wasi_args;
  2514. #endif
  2515. return wasi_args;
  2516. }
  2517. void
  2518. wasm_runtime_set_wasi_args_ex(WASMModuleCommon *module, const char *dir_list[],
  2519. uint32 dir_count, const char *map_dir_list[],
  2520. uint32 map_dir_count, const char *env_list[],
  2521. uint32 env_count, char *argv[], int argc,
  2522. int64 stdinfd, int64 stdoutfd, int64 stderrfd)
  2523. {
  2524. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2525. bh_assert(wasi_args);
  2526. wasi_args->dir_list = dir_list;
  2527. wasi_args->dir_count = dir_count;
  2528. wasi_args->map_dir_list = map_dir_list;
  2529. wasi_args->map_dir_count = map_dir_count;
  2530. wasi_args->env = env_list;
  2531. wasi_args->env_count = env_count;
  2532. wasi_args->argv = argv;
  2533. wasi_args->argc = (uint32)argc;
  2534. wasi_args->stdio[0] = (os_raw_file_handle)stdinfd;
  2535. wasi_args->stdio[1] = (os_raw_file_handle)stdoutfd;
  2536. wasi_args->stdio[2] = (os_raw_file_handle)stderrfd;
  2537. #if WASM_ENABLE_MULTI_MODULE != 0
  2538. #if WASM_ENABLE_INTERP != 0
  2539. if (module->module_type == Wasm_Module_Bytecode) {
  2540. wasm_propagate_wasi_args((WASMModule *)module);
  2541. }
  2542. #endif
  2543. #endif
  2544. }
  2545. void
  2546. wasm_runtime_set_wasi_args(WASMModuleCommon *module, const char *dir_list[],
  2547. uint32 dir_count, const char *map_dir_list[],
  2548. uint32 map_dir_count, const char *env_list[],
  2549. uint32 env_count, char *argv[], int argc)
  2550. {
  2551. wasm_runtime_set_wasi_args_ex(module, dir_list, dir_count, map_dir_list,
  2552. map_dir_count, env_list, env_count, argv,
  2553. argc, -1, -1, -1);
  2554. }
  2555. void
  2556. wasm_runtime_set_wasi_addr_pool(wasm_module_t module, const char *addr_pool[],
  2557. uint32 addr_pool_size)
  2558. {
  2559. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2560. if (wasi_args) {
  2561. wasi_args->addr_pool = addr_pool;
  2562. wasi_args->addr_count = addr_pool_size;
  2563. }
  2564. }
  2565. void
  2566. wasm_runtime_set_wasi_ns_lookup_pool(wasm_module_t module,
  2567. const char *ns_lookup_pool[],
  2568. uint32 ns_lookup_pool_size)
  2569. {
  2570. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2571. if (wasi_args) {
  2572. wasi_args->ns_lookup_pool = ns_lookup_pool;
  2573. wasi_args->ns_lookup_count = ns_lookup_pool_size;
  2574. }
  2575. }
  2576. #if WASM_ENABLE_UVWASI == 0
  2577. static bool
  2578. copy_string_array(const char *array[], uint32 array_size, char **buf_ptr,
  2579. char ***list_ptr, uint64 *out_buf_size)
  2580. {
  2581. uint64 buf_size = 0, total_size;
  2582. uint32 buf_offset = 0, i;
  2583. char *buf = NULL, **list = NULL;
  2584. for (i = 0; i < array_size; i++)
  2585. buf_size += strlen(array[i]) + 1;
  2586. /* We add +1 to generate null-terminated array of strings */
  2587. total_size = sizeof(char *) * ((uint64)array_size + 1);
  2588. if (total_size >= UINT32_MAX
  2589. || (total_size > 0 && !(list = wasm_runtime_malloc((uint32)total_size)))
  2590. || buf_size >= UINT32_MAX
  2591. || (buf_size > 0 && !(buf = wasm_runtime_malloc((uint32)buf_size)))) {
  2592. if (buf)
  2593. wasm_runtime_free(buf);
  2594. if (list)
  2595. wasm_runtime_free(list);
  2596. return false;
  2597. }
  2598. for (i = 0; i < array_size; i++) {
  2599. list[i] = buf + buf_offset;
  2600. bh_strcpy_s(buf + buf_offset, (uint32)buf_size - buf_offset, array[i]);
  2601. buf_offset += (uint32)(strlen(array[i]) + 1);
  2602. }
  2603. list[array_size] = NULL;
  2604. *list_ptr = list;
  2605. *buf_ptr = buf;
  2606. if (out_buf_size)
  2607. *out_buf_size = buf_size;
  2608. return true;
  2609. }
  2610. bool
  2611. wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst,
  2612. const char *dir_list[], uint32 dir_count,
  2613. const char *map_dir_list[], uint32 map_dir_count,
  2614. const char *env[], uint32 env_count,
  2615. const char *addr_pool[], uint32 addr_pool_size,
  2616. const char *ns_lookup_pool[], uint32 ns_lookup_pool_size,
  2617. char *argv[], uint32 argc, os_raw_file_handle stdinfd,
  2618. os_raw_file_handle stdoutfd, os_raw_file_handle stderrfd,
  2619. char *error_buf, uint32 error_buf_size)
  2620. {
  2621. WASIContext *wasi_ctx;
  2622. char *argv_buf = NULL;
  2623. char **argv_list = NULL;
  2624. char *env_buf = NULL;
  2625. char **env_list = NULL;
  2626. char *ns_lookup_buf = NULL;
  2627. char **ns_lookup_list = NULL;
  2628. uint64 argv_buf_size = 0, env_buf_size = 0;
  2629. struct fd_table *curfds = NULL;
  2630. struct fd_prestats *prestats = NULL;
  2631. struct argv_environ_values *argv_environ = NULL;
  2632. struct addr_pool *apool = NULL;
  2633. bool fd_table_inited = false, fd_prestats_inited = false;
  2634. bool argv_environ_inited = false;
  2635. bool addr_pool_inited = false;
  2636. __wasi_fd_t wasm_fd = 3;
  2637. os_file_handle file_handle;
  2638. char *path, resolved_path[PATH_MAX];
  2639. uint32 i;
  2640. if (!(wasi_ctx = runtime_malloc(sizeof(WASIContext), NULL, error_buf,
  2641. error_buf_size))) {
  2642. return false;
  2643. }
  2644. wasm_runtime_set_wasi_ctx(module_inst, wasi_ctx);
  2645. /* process argv[0], trip the path and suffix, only keep the program name
  2646. */
  2647. if (!copy_string_array((const char **)argv, argc, &argv_buf, &argv_list,
  2648. &argv_buf_size)) {
  2649. set_error_buf(error_buf, error_buf_size,
  2650. "Init wasi environment failed: allocate memory failed");
  2651. goto fail;
  2652. }
  2653. if (!copy_string_array(env, env_count, &env_buf, &env_list,
  2654. &env_buf_size)) {
  2655. set_error_buf(error_buf, error_buf_size,
  2656. "Init wasi environment failed: allocate memory failed");
  2657. goto fail;
  2658. }
  2659. if (!(curfds = wasm_runtime_malloc(sizeof(struct fd_table)))
  2660. || !(prestats = wasm_runtime_malloc(sizeof(struct fd_prestats)))
  2661. || !(argv_environ =
  2662. wasm_runtime_malloc(sizeof(struct argv_environ_values)))
  2663. || !(apool = wasm_runtime_malloc(sizeof(struct addr_pool)))) {
  2664. set_error_buf(error_buf, error_buf_size,
  2665. "Init wasi environment failed: allocate memory failed");
  2666. goto fail;
  2667. }
  2668. if (!fd_table_init(curfds)) {
  2669. set_error_buf(error_buf, error_buf_size,
  2670. "Init wasi environment failed: "
  2671. "init fd table failed");
  2672. goto fail;
  2673. }
  2674. fd_table_inited = true;
  2675. if (!fd_prestats_init(prestats)) {
  2676. set_error_buf(error_buf, error_buf_size,
  2677. "Init wasi environment failed: "
  2678. "init fd prestats failed");
  2679. goto fail;
  2680. }
  2681. fd_prestats_inited = true;
  2682. if (!argv_environ_init(argv_environ, argv_buf, argv_buf_size, argv_list,
  2683. argc, env_buf, env_buf_size, env_list, env_count)) {
  2684. set_error_buf(error_buf, error_buf_size,
  2685. "Init wasi environment failed: "
  2686. "init argument environment failed");
  2687. goto fail;
  2688. }
  2689. argv_environ_inited = true;
  2690. if (!addr_pool_init(apool)) {
  2691. set_error_buf(error_buf, error_buf_size,
  2692. "Init wasi environment failed: "
  2693. "init the address pool failed");
  2694. goto fail;
  2695. }
  2696. addr_pool_inited = true;
  2697. os_file_handle stdin_file_handle = os_convert_stdin_handle(stdinfd);
  2698. os_file_handle stdout_file_handle = os_convert_stdout_handle(stdoutfd);
  2699. os_file_handle stderr_file_handle = os_convert_stderr_handle(stderrfd);
  2700. if (!os_is_handle_valid(&stdin_file_handle)
  2701. || !os_is_handle_valid(&stdout_file_handle)
  2702. || !os_is_handle_valid(&stderr_file_handle))
  2703. goto fail;
  2704. /* Prepopulate curfds with stdin, stdout, and stderr file descriptors. */
  2705. if (!fd_table_insert_existing(curfds, 0, stdin_file_handle, true)
  2706. || !fd_table_insert_existing(curfds, 1, stdout_file_handle, true)
  2707. || !fd_table_insert_existing(curfds, 2, stderr_file_handle, true)) {
  2708. set_error_buf(error_buf, error_buf_size,
  2709. "Init wasi environment failed: init fd table failed");
  2710. goto fail;
  2711. }
  2712. wasm_fd = 3;
  2713. for (i = 0; i < dir_count; i++, wasm_fd++) {
  2714. path = os_realpath(dir_list[i], resolved_path);
  2715. if (!path) {
  2716. if (error_buf)
  2717. snprintf(error_buf, error_buf_size,
  2718. "error while pre-opening directory %s: %d\n",
  2719. dir_list[i], errno);
  2720. goto fail;
  2721. }
  2722. __wasi_errno_t error = os_open_preopendir(path, &file_handle);
  2723. if (error != __WASI_ESUCCESS) {
  2724. if (error_buf)
  2725. snprintf(error_buf, error_buf_size,
  2726. "error while pre-opening directory %s: %d\n",
  2727. dir_list[i], error);
  2728. goto fail;
  2729. }
  2730. if (!fd_table_insert_existing(curfds, wasm_fd, file_handle, false)) {
  2731. if (error_buf)
  2732. snprintf(error_buf, error_buf_size,
  2733. "error inserting preopen fd %u (directory %s) into fd "
  2734. "table",
  2735. (unsigned int)wasm_fd, dir_list[i]);
  2736. goto fail;
  2737. }
  2738. if (!fd_prestats_insert(prestats, dir_list[i], wasm_fd)) {
  2739. if (error_buf)
  2740. snprintf(error_buf, error_buf_size,
  2741. "error inserting preopen fd %u (directory %s) into "
  2742. "prestats table",
  2743. (unsigned int)wasm_fd, dir_list[i]);
  2744. goto fail;
  2745. }
  2746. }
  2747. for (i = 0; i < map_dir_count; i++, wasm_fd++) {
  2748. char mapping_copy_buf[256];
  2749. char *mapping_copy = mapping_copy_buf;
  2750. char *map_mapped = NULL, *map_host = NULL;
  2751. const unsigned long max_len = strlen(map_dir_list[i]) * 2 + 3;
  2752. /* Allocation limit for runtime environments with reduced stack size */
  2753. if (max_len > 256) {
  2754. if (!(mapping_copy = wasm_runtime_malloc(max_len))) {
  2755. snprintf(error_buf, error_buf_size,
  2756. "error while allocating for directory mapping\n");
  2757. goto fail;
  2758. }
  2759. }
  2760. bh_memcpy_s(mapping_copy, max_len, map_dir_list[i],
  2761. (uint32)(strlen(map_dir_list[i]) + 1));
  2762. map_mapped = strtok(mapping_copy, "::");
  2763. map_host = strtok(NULL, "::");
  2764. if (!map_mapped || !map_host) {
  2765. if (error_buf)
  2766. snprintf(error_buf, error_buf_size,
  2767. "error while pre-opening mapped directory: "
  2768. "invalid map\n");
  2769. if (mapping_copy != mapping_copy_buf)
  2770. wasm_runtime_free(mapping_copy);
  2771. goto fail;
  2772. }
  2773. path = os_realpath(map_host, resolved_path);
  2774. if (!path) {
  2775. if (error_buf)
  2776. snprintf(error_buf, error_buf_size,
  2777. "error while pre-opening mapped directory %s: %d\n",
  2778. map_host, errno);
  2779. if (mapping_copy != mapping_copy_buf)
  2780. wasm_runtime_free(mapping_copy);
  2781. goto fail;
  2782. }
  2783. __wasi_errno_t error = os_open_preopendir(path, &file_handle);
  2784. if (error != __WASI_ESUCCESS) {
  2785. if (error_buf)
  2786. snprintf(error_buf, error_buf_size,
  2787. "error while pre-opening mapped directory %s: %d\n",
  2788. map_host, errno);
  2789. if (mapping_copy != mapping_copy_buf)
  2790. wasm_runtime_free(mapping_copy);
  2791. goto fail;
  2792. }
  2793. if (!fd_table_insert_existing(curfds, wasm_fd, file_handle, false)
  2794. || !fd_prestats_insert(prestats, map_mapped, wasm_fd)) {
  2795. if (error_buf)
  2796. snprintf(error_buf, error_buf_size,
  2797. "error while pre-opening mapped directory %s: "
  2798. "insertion failed\n",
  2799. dir_list[i]);
  2800. if (mapping_copy != mapping_copy_buf)
  2801. wasm_runtime_free(mapping_copy);
  2802. goto fail;
  2803. }
  2804. if (mapping_copy != mapping_copy_buf)
  2805. wasm_runtime_free(mapping_copy);
  2806. }
  2807. /* addr_pool(textual) -> apool */
  2808. for (i = 0; i < addr_pool_size; i++) {
  2809. char *cp, *address, *mask;
  2810. bool ret = false;
  2811. cp = bh_strdup(addr_pool[i]);
  2812. if (!cp) {
  2813. set_error_buf(error_buf, error_buf_size,
  2814. "Init wasi environment failed: copy address failed");
  2815. goto fail;
  2816. }
  2817. address = strtok(cp, "/");
  2818. mask = strtok(NULL, "/");
  2819. ret = addr_pool_insert(apool, address, (uint8)(mask ? atoi(mask) : 0));
  2820. wasm_runtime_free(cp);
  2821. if (!ret) {
  2822. set_error_buf(error_buf, error_buf_size,
  2823. "Init wasi environment failed: store address failed");
  2824. goto fail;
  2825. }
  2826. }
  2827. if (!copy_string_array(ns_lookup_pool, ns_lookup_pool_size, &ns_lookup_buf,
  2828. &ns_lookup_list, NULL)) {
  2829. set_error_buf(error_buf, error_buf_size,
  2830. "Init wasi environment failed: allocate memory failed");
  2831. goto fail;
  2832. }
  2833. wasi_ctx->curfds = curfds;
  2834. wasi_ctx->prestats = prestats;
  2835. wasi_ctx->argv_environ = argv_environ;
  2836. wasi_ctx->addr_pool = apool;
  2837. wasi_ctx->argv_buf = argv_buf;
  2838. wasi_ctx->argv_list = argv_list;
  2839. wasi_ctx->env_buf = env_buf;
  2840. wasi_ctx->env_list = env_list;
  2841. wasi_ctx->ns_lookup_buf = ns_lookup_buf;
  2842. wasi_ctx->ns_lookup_list = ns_lookup_list;
  2843. return true;
  2844. fail:
  2845. if (argv_environ_inited)
  2846. argv_environ_destroy(argv_environ);
  2847. if (fd_prestats_inited)
  2848. fd_prestats_destroy(prestats);
  2849. if (fd_table_inited)
  2850. fd_table_destroy(curfds);
  2851. if (addr_pool_inited)
  2852. addr_pool_destroy(apool);
  2853. if (curfds)
  2854. wasm_runtime_free(curfds);
  2855. if (prestats)
  2856. wasm_runtime_free(prestats);
  2857. if (argv_environ)
  2858. wasm_runtime_free(argv_environ);
  2859. if (apool)
  2860. wasm_runtime_free(apool);
  2861. if (argv_buf)
  2862. wasm_runtime_free(argv_buf);
  2863. if (argv_list)
  2864. wasm_runtime_free(argv_list);
  2865. if (env_buf)
  2866. wasm_runtime_free(env_buf);
  2867. if (env_list)
  2868. wasm_runtime_free(env_list);
  2869. if (ns_lookup_buf)
  2870. wasm_runtime_free(ns_lookup_buf);
  2871. if (ns_lookup_list)
  2872. wasm_runtime_free(ns_lookup_list);
  2873. return false;
  2874. }
  2875. #else /* else of WASM_ENABLE_UVWASI == 0 */
  2876. static void *
  2877. wasm_uvwasi_malloc(size_t size, void *mem_user_data)
  2878. {
  2879. return runtime_malloc(size, NULL, NULL, 0);
  2880. (void)mem_user_data;
  2881. }
  2882. static void
  2883. wasm_uvwasi_free(void *ptr, void *mem_user_data)
  2884. {
  2885. if (ptr)
  2886. wasm_runtime_free(ptr);
  2887. (void)mem_user_data;
  2888. }
  2889. static void *
  2890. wasm_uvwasi_calloc(size_t nmemb, size_t size, void *mem_user_data)
  2891. {
  2892. uint64 total_size = (uint64)nmemb * size;
  2893. return runtime_malloc(total_size, NULL, NULL, 0);
  2894. (void)mem_user_data;
  2895. }
  2896. static void *
  2897. wasm_uvwasi_realloc(void *ptr, size_t size, void *mem_user_data)
  2898. {
  2899. if (size >= UINT32_MAX) {
  2900. return NULL;
  2901. }
  2902. return wasm_runtime_realloc(ptr, (uint32)size);
  2903. }
  2904. /* clang-format off */
  2905. static uvwasi_mem_t uvwasi_allocator = {
  2906. .mem_user_data = 0,
  2907. .malloc = wasm_uvwasi_malloc,
  2908. .free = wasm_uvwasi_free,
  2909. .calloc = wasm_uvwasi_calloc,
  2910. .realloc = wasm_uvwasi_realloc
  2911. };
  2912. /* clang-format on */
  2913. bool
  2914. wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst,
  2915. const char *dir_list[], uint32 dir_count,
  2916. const char *map_dir_list[], uint32 map_dir_count,
  2917. const char *env[], uint32 env_count,
  2918. const char *addr_pool[], uint32 addr_pool_size,
  2919. const char *ns_lookup_pool[], uint32 ns_lookup_pool_size,
  2920. char *argv[], uint32 argc, os_raw_file_handle stdinfd,
  2921. os_raw_file_handle stdoutfd, os_raw_file_handle stderrfd,
  2922. char *error_buf, uint32 error_buf_size)
  2923. {
  2924. WASIContext *ctx;
  2925. uvwasi_t *uvwasi;
  2926. uvwasi_options_t init_options;
  2927. const char **envp = NULL;
  2928. uint64 total_size;
  2929. uint32 i;
  2930. bool ret = false;
  2931. ctx = runtime_malloc(sizeof(*ctx), module_inst, error_buf, error_buf_size);
  2932. if (!ctx)
  2933. return false;
  2934. uvwasi = &ctx->uvwasi;
  2935. /* Setup the initialization options */
  2936. uvwasi_options_init(&init_options);
  2937. init_options.allocator = &uvwasi_allocator;
  2938. init_options.argc = argc;
  2939. init_options.argv = (const char **)argv;
  2940. init_options.in = (stdinfd != -1) ? (uvwasi_fd_t)stdinfd : init_options.in;
  2941. init_options.out =
  2942. (stdoutfd != -1) ? (uvwasi_fd_t)stdoutfd : init_options.out;
  2943. init_options.err =
  2944. (stderrfd != -1) ? (uvwasi_fd_t)stderrfd : init_options.err;
  2945. if (dir_count > 0) {
  2946. init_options.preopenc = dir_count;
  2947. total_size = sizeof(uvwasi_preopen_t) * (uint64)init_options.preopenc;
  2948. init_options.preopens = (uvwasi_preopen_t *)runtime_malloc(
  2949. total_size, module_inst, error_buf, error_buf_size);
  2950. if (init_options.preopens == NULL)
  2951. goto fail;
  2952. for (i = 0; i < init_options.preopenc; i++) {
  2953. init_options.preopens[i].real_path = dir_list[i];
  2954. init_options.preopens[i].mapped_path =
  2955. (i < map_dir_count) ? map_dir_list[i] : dir_list[i];
  2956. }
  2957. }
  2958. if (env_count > 0) {
  2959. total_size = sizeof(char *) * (uint64)(env_count + 1);
  2960. envp =
  2961. runtime_malloc(total_size, module_inst, error_buf, error_buf_size);
  2962. if (envp == NULL)
  2963. goto fail;
  2964. for (i = 0; i < env_count; i++) {
  2965. envp[i] = env[i];
  2966. }
  2967. envp[env_count] = NULL;
  2968. init_options.envp = envp;
  2969. }
  2970. if (UVWASI_ESUCCESS != uvwasi_init(uvwasi, &init_options)) {
  2971. set_error_buf(error_buf, error_buf_size, "uvwasi init failed");
  2972. goto fail;
  2973. }
  2974. wasm_runtime_set_wasi_ctx(module_inst, ctx);
  2975. ret = true;
  2976. fail:
  2977. if (envp)
  2978. wasm_runtime_free((void *)envp);
  2979. if (init_options.preopens)
  2980. wasm_runtime_free(init_options.preopens);
  2981. if (!ret && uvwasi)
  2982. wasm_runtime_free(uvwasi);
  2983. return ret;
  2984. }
  2985. #endif /* end of WASM_ENABLE_UVWASI */
  2986. bool
  2987. wasm_runtime_is_wasi_mode(WASMModuleInstanceCommon *module_inst)
  2988. {
  2989. #if WASM_ENABLE_INTERP != 0
  2990. if (module_inst->module_type == Wasm_Module_Bytecode
  2991. && ((WASMModuleInstance *)module_inst)->module->import_wasi_api)
  2992. return true;
  2993. #endif
  2994. #if WASM_ENABLE_AOT != 0
  2995. if (module_inst->module_type == Wasm_Module_AoT
  2996. && ((AOTModule *)((AOTModuleInstance *)module_inst)->module)
  2997. ->import_wasi_api)
  2998. return true;
  2999. #endif
  3000. return false;
  3001. }
  3002. WASMFunctionInstanceCommon *
  3003. wasm_runtime_lookup_wasi_start_function(WASMModuleInstanceCommon *module_inst)
  3004. {
  3005. uint32 i;
  3006. #if WASM_ENABLE_INTERP != 0
  3007. if (module_inst->module_type == Wasm_Module_Bytecode) {
  3008. WASMModuleInstance *wasm_inst = (WASMModuleInstance *)module_inst;
  3009. WASMFunctionInstance *func;
  3010. for (i = 0; i < wasm_inst->export_func_count; i++) {
  3011. if (!strcmp(wasm_inst->export_functions[i].name, "_start")) {
  3012. func = wasm_inst->export_functions[i].function;
  3013. if (func->u.func->func_type->param_count != 0
  3014. || func->u.func->func_type->result_count != 0) {
  3015. LOG_ERROR("Lookup wasi _start function failed: "
  3016. "invalid function type.\n");
  3017. return NULL;
  3018. }
  3019. return (WASMFunctionInstanceCommon *)func;
  3020. }
  3021. }
  3022. return NULL;
  3023. }
  3024. #endif
  3025. #if WASM_ENABLE_AOT != 0
  3026. if (module_inst->module_type == Wasm_Module_AoT) {
  3027. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  3028. AOTFunctionInstance *export_funcs =
  3029. (AOTFunctionInstance *)aot_inst->export_functions;
  3030. for (i = 0; i < aot_inst->export_func_count; i++) {
  3031. if (!strcmp(export_funcs[i].func_name, "_start")) {
  3032. AOTFuncType *func_type = export_funcs[i].u.func.func_type;
  3033. if (func_type->param_count != 0
  3034. || func_type->result_count != 0) {
  3035. LOG_ERROR("Lookup wasi _start function failed: "
  3036. "invalid function type.\n");
  3037. return NULL;
  3038. }
  3039. return (WASMFunctionInstanceCommon *)&export_funcs[i];
  3040. }
  3041. }
  3042. return NULL;
  3043. }
  3044. #endif /* end of WASM_ENABLE_AOT */
  3045. return NULL;
  3046. }
  3047. #if WASM_ENABLE_UVWASI == 0
  3048. void
  3049. wasm_runtime_destroy_wasi(WASMModuleInstanceCommon *module_inst)
  3050. {
  3051. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  3052. if (wasi_ctx) {
  3053. if (wasi_ctx->argv_environ) {
  3054. argv_environ_destroy(wasi_ctx->argv_environ);
  3055. wasm_runtime_free(wasi_ctx->argv_environ);
  3056. }
  3057. if (wasi_ctx->curfds) {
  3058. fd_table_destroy(wasi_ctx->curfds);
  3059. wasm_runtime_free(wasi_ctx->curfds);
  3060. }
  3061. if (wasi_ctx->prestats) {
  3062. fd_prestats_destroy(wasi_ctx->prestats);
  3063. wasm_runtime_free(wasi_ctx->prestats);
  3064. }
  3065. if (wasi_ctx->addr_pool) {
  3066. addr_pool_destroy(wasi_ctx->addr_pool);
  3067. wasm_runtime_free(wasi_ctx->addr_pool);
  3068. }
  3069. if (wasi_ctx->argv_buf)
  3070. wasm_runtime_free(wasi_ctx->argv_buf);
  3071. if (wasi_ctx->argv_list)
  3072. wasm_runtime_free(wasi_ctx->argv_list);
  3073. if (wasi_ctx->env_buf)
  3074. wasm_runtime_free(wasi_ctx->env_buf);
  3075. if (wasi_ctx->env_list)
  3076. wasm_runtime_free(wasi_ctx->env_list);
  3077. if (wasi_ctx->ns_lookup_buf)
  3078. wasm_runtime_free(wasi_ctx->ns_lookup_buf);
  3079. if (wasi_ctx->ns_lookup_list)
  3080. wasm_runtime_free(wasi_ctx->ns_lookup_list);
  3081. wasm_runtime_free(wasi_ctx);
  3082. }
  3083. }
  3084. #else
  3085. void
  3086. wasm_runtime_destroy_wasi(WASMModuleInstanceCommon *module_inst)
  3087. {
  3088. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  3089. if (wasi_ctx) {
  3090. uvwasi_destroy(&wasi_ctx->uvwasi);
  3091. wasm_runtime_free(wasi_ctx);
  3092. }
  3093. }
  3094. #endif
  3095. uint32_t
  3096. wasm_runtime_get_wasi_exit_code(WASMModuleInstanceCommon *module_inst)
  3097. {
  3098. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  3099. #if WASM_ENABLE_THREAD_MGR != 0
  3100. WASMCluster *cluster;
  3101. WASMExecEnv *exec_env;
  3102. exec_env = wasm_runtime_get_exec_env_singleton(module_inst);
  3103. if (exec_env && (cluster = wasm_exec_env_get_cluster(exec_env))) {
  3104. /**
  3105. * The main thread may exit earlier than other threads, and
  3106. * the exit_code of wasi_ctx may be changed by other thread
  3107. * when it runs into wasi_proc_exit, here we wait until all
  3108. * other threads exit to avoid getting invalid exit_code.
  3109. */
  3110. wasm_cluster_wait_for_all_except_self(cluster, exec_env);
  3111. }
  3112. #endif
  3113. return wasi_ctx->exit_code;
  3114. }
  3115. #endif /* end of WASM_ENABLE_LIBC_WASI */
  3116. WASMModuleCommon *
  3117. wasm_exec_env_get_module(WASMExecEnv *exec_env)
  3118. {
  3119. WASMModuleInstanceCommon *module_inst_comm =
  3120. wasm_runtime_get_module_inst(exec_env);
  3121. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  3122. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  3123. || module_inst_comm->module_type == Wasm_Module_AoT);
  3124. return (WASMModuleCommon *)module_inst->module;
  3125. }
  3126. #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0
  3127. const uint8 *
  3128. wasm_runtime_get_custom_section(WASMModuleCommon *const module_comm,
  3129. const char *name, uint32 *len)
  3130. {
  3131. #if WASM_ENABLE_INTERP != 0
  3132. if (module_comm->module_type == Wasm_Module_Bytecode)
  3133. return wasm_loader_get_custom_section((WASMModule *)module_comm, name,
  3134. len);
  3135. #endif
  3136. #if WASM_ENABLE_AOT != 0
  3137. if (module_comm->module_type == Wasm_Module_AoT)
  3138. return aot_get_custom_section((AOTModule *)module_comm, name, len);
  3139. #endif
  3140. return NULL;
  3141. }
  3142. #endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 */
  3143. static union {
  3144. int a;
  3145. char b;
  3146. } __ue = { .a = 1 };
  3147. #define is_little_endian() (__ue.b == 1)
  3148. bool
  3149. wasm_runtime_register_natives(const char *module_name,
  3150. NativeSymbol *native_symbols,
  3151. uint32 n_native_symbols)
  3152. {
  3153. return wasm_native_register_natives(module_name, native_symbols,
  3154. n_native_symbols);
  3155. }
  3156. bool
  3157. wasm_runtime_register_natives_raw(const char *module_name,
  3158. NativeSymbol *native_symbols,
  3159. uint32 n_native_symbols)
  3160. {
  3161. return wasm_native_register_natives_raw(module_name, native_symbols,
  3162. n_native_symbols);
  3163. }
  3164. bool
  3165. wasm_runtime_unregister_natives(const char *module_name,
  3166. NativeSymbol *native_symbols)
  3167. {
  3168. return wasm_native_unregister_natives(module_name, native_symbols);
  3169. }
  3170. bool
  3171. wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr,
  3172. const WASMFuncType *func_type,
  3173. const char *signature, void *attachment,
  3174. uint32 *argv, uint32 argc, uint32 *argv_ret)
  3175. {
  3176. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3177. typedef void (*NativeRawFuncPtr)(WASMExecEnv *, uint64 *);
  3178. NativeRawFuncPtr invokeNativeRaw = (NativeRawFuncPtr)func_ptr;
  3179. uint64 argv_buf[16] = { 0 }, *argv1 = argv_buf, *argv_dst, size;
  3180. uint32 *argv_src = argv, i, argc1, ptr_len;
  3181. uint32 arg_i32;
  3182. bool ret = false;
  3183. argc1 = func_type->param_count;
  3184. if (argc1 > sizeof(argv_buf) / sizeof(uint64)) {
  3185. size = sizeof(uint64) * (uint64)argc1;
  3186. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3187. 0))) {
  3188. return false;
  3189. }
  3190. }
  3191. argv_dst = argv1;
  3192. /* Traverse secondly to fill in each argument */
  3193. for (i = 0; i < func_type->param_count; i++, argv_dst++) {
  3194. switch (func_type->types[i]) {
  3195. case VALUE_TYPE_I32:
  3196. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3197. case VALUE_TYPE_FUNCREF:
  3198. #endif
  3199. {
  3200. *(uint32 *)argv_dst = arg_i32 = *argv_src++;
  3201. if (signature) {
  3202. if (signature[i + 1] == '*') {
  3203. /* param is a pointer */
  3204. if (signature[i + 2] == '~')
  3205. /* pointer with length followed */
  3206. ptr_len = *argv_src;
  3207. else
  3208. /* pointer without length followed */
  3209. ptr_len = 1;
  3210. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3211. ptr_len))
  3212. goto fail;
  3213. *(uintptr_t *)argv_dst =
  3214. (uintptr_t)wasm_runtime_addr_app_to_native(module,
  3215. arg_i32);
  3216. }
  3217. else if (signature[i + 1] == '$') {
  3218. /* param is a string */
  3219. if (!wasm_runtime_validate_app_str_addr(module,
  3220. arg_i32))
  3221. goto fail;
  3222. *(uintptr_t *)argv_dst =
  3223. (uintptr_t)wasm_runtime_addr_app_to_native(module,
  3224. arg_i32);
  3225. }
  3226. }
  3227. break;
  3228. }
  3229. case VALUE_TYPE_I64:
  3230. case VALUE_TYPE_F64:
  3231. bh_memcpy_s(argv_dst, sizeof(uint64), argv_src,
  3232. sizeof(uint32) * 2);
  3233. argv_src += 2;
  3234. break;
  3235. case VALUE_TYPE_F32:
  3236. *(float32 *)argv_dst = *(float32 *)argv_src++;
  3237. break;
  3238. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3239. case VALUE_TYPE_EXTERNREF:
  3240. {
  3241. uint32 externref_idx = *argv_src++;
  3242. void *externref_obj;
  3243. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3244. goto fail;
  3245. bh_memcpy_s(argv_dst, sizeof(uintptr_t), argv_src,
  3246. sizeof(uintptr_t));
  3247. break;
  3248. }
  3249. #endif
  3250. #if WASM_ENABLE_GC != 0
  3251. case REF_TYPE_FUNCREF:
  3252. case REF_TYPE_EXTERNREF:
  3253. case REF_TYPE_ANYREF:
  3254. case REF_TYPE_EQREF:
  3255. case REF_TYPE_HT_NULLABLE:
  3256. case REF_TYPE_HT_NON_NULLABLE:
  3257. case REF_TYPE_I31REF:
  3258. case REF_TYPE_NULLFUNCREF:
  3259. case REF_TYPE_NULLEXTERNREF:
  3260. case REF_TYPE_STRUCTREF:
  3261. case REF_TYPE_ARRAYREF:
  3262. case REF_TYPE_NULLREF:
  3263. #if WASM_ENABLE_STRINGREF != 0
  3264. case REF_TYPE_STRINGREF:
  3265. case REF_TYPE_STRINGVIEWWTF8:
  3266. case REF_TYPE_STRINGVIEWWTF16:
  3267. case REF_TYPE_STRINGVIEWITER:
  3268. #endif
  3269. {
  3270. bh_memcpy_s(argv_dst, sizeof(uintptr_t), argv_src,
  3271. sizeof(uintptr_t));
  3272. argv_src += sizeof(uintptr_t) / sizeof(uint32);
  3273. break;
  3274. }
  3275. #endif
  3276. default:
  3277. bh_assert(0);
  3278. break;
  3279. }
  3280. }
  3281. exec_env->attachment = attachment;
  3282. invokeNativeRaw(exec_env, argv1);
  3283. exec_env->attachment = NULL;
  3284. if (func_type->result_count > 0) {
  3285. switch (func_type->types[func_type->param_count]) {
  3286. case VALUE_TYPE_I32:
  3287. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3288. case VALUE_TYPE_FUNCREF:
  3289. #endif
  3290. argv_ret[0] = *(uint32 *)argv1;
  3291. break;
  3292. case VALUE_TYPE_F32:
  3293. *(float32 *)argv_ret = *(float32 *)argv1;
  3294. break;
  3295. case VALUE_TYPE_I64:
  3296. case VALUE_TYPE_F64:
  3297. bh_memcpy_s(argv_ret, sizeof(uint32) * 2, argv1,
  3298. sizeof(uint64));
  3299. break;
  3300. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3301. case VALUE_TYPE_EXTERNREF:
  3302. {
  3303. uint32 externref_idx;
  3304. uint64 externref_obj;
  3305. bh_memcpy_s(&externref_obj, sizeof(uint64), argv1,
  3306. sizeof(uint64));
  3307. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3308. (void *)(uintptr_t)externref_obj,
  3309. &externref_idx))
  3310. goto fail;
  3311. argv_ret[0] = externref_idx;
  3312. break;
  3313. }
  3314. #endif
  3315. #if WASM_ENABLE_GC != 0
  3316. case REF_TYPE_FUNCREF:
  3317. case REF_TYPE_EXTERNREF:
  3318. case REF_TYPE_ANYREF:
  3319. case REF_TYPE_EQREF:
  3320. case REF_TYPE_HT_NULLABLE:
  3321. case REF_TYPE_HT_NON_NULLABLE:
  3322. case REF_TYPE_I31REF:
  3323. case REF_TYPE_NULLFUNCREF:
  3324. case REF_TYPE_NULLEXTERNREF:
  3325. case REF_TYPE_STRUCTREF:
  3326. case REF_TYPE_ARRAYREF:
  3327. case REF_TYPE_NULLREF:
  3328. #if WASM_ENABLE_STRINGREF != 0
  3329. case REF_TYPE_STRINGREF:
  3330. case REF_TYPE_STRINGVIEWWTF8:
  3331. case REF_TYPE_STRINGVIEWWTF16:
  3332. case REF_TYPE_STRINGVIEWITER:
  3333. #endif
  3334. {
  3335. bh_memcpy_s(argv_ret, sizeof(uintptr_t), argv1,
  3336. sizeof(uintptr_t));
  3337. break;
  3338. }
  3339. #endif
  3340. default:
  3341. bh_assert(0);
  3342. break;
  3343. }
  3344. }
  3345. ret = !wasm_runtime_copy_exception(module, NULL);
  3346. fail:
  3347. if (argv1 != argv_buf)
  3348. wasm_runtime_free(argv1);
  3349. return ret;
  3350. }
  3351. /**
  3352. * Implementation of wasm_runtime_invoke_native()
  3353. */
  3354. /* The invoke native implementation on ARM platform with VFP co-processor */
  3355. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP) \
  3356. || defined(BUILD_TARGET_RISCV32_ILP32D) \
  3357. || defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3358. typedef void (*GenericFunctionPointer)();
  3359. void
  3360. invokeNative(GenericFunctionPointer f, uint32 *args, uint32 n_stacks);
  3361. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3362. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3363. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3364. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3365. typedef void (*VoidFuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3366. static volatile Float64FuncPtr invokeNative_Float64 =
  3367. (Float64FuncPtr)(uintptr_t)invokeNative;
  3368. static volatile Float32FuncPtr invokeNative_Float32 =
  3369. (Float32FuncPtr)(uintptr_t)invokeNative;
  3370. static volatile Int64FuncPtr invokeNative_Int64 =
  3371. (Int64FuncPtr)(uintptr_t)invokeNative;
  3372. static volatile Int32FuncPtr invokeNative_Int32 =
  3373. (Int32FuncPtr)(uintptr_t)invokeNative;
  3374. static volatile VoidFuncPtr invokeNative_Void =
  3375. (VoidFuncPtr)(uintptr_t)invokeNative;
  3376. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3377. #define MAX_REG_INTS 4
  3378. #define MAX_REG_FLOATS 16
  3379. #else
  3380. #define MAX_REG_INTS 8
  3381. #define MAX_REG_FLOATS 8
  3382. #endif
  3383. bool
  3384. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  3385. const WASMFuncType *func_type, const char *signature,
  3386. void *attachment, uint32 *argv, uint32 argc,
  3387. uint32 *argv_ret)
  3388. {
  3389. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3390. /* argv buf layout: int args(fix cnt) + float args(fix cnt) + stack args
  3391. */
  3392. uint32 argv_buf[32], *argv1 = argv_buf, *ints, *stacks, size;
  3393. uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0;
  3394. uint32 arg_i32, ptr_len;
  3395. uint32 result_count = func_type->result_count;
  3396. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  3397. bool ret = false;
  3398. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3399. bool is_aot_func = (NULL == signature);
  3400. #endif
  3401. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3402. uint32 *fps;
  3403. int n_fps = 0;
  3404. #else
  3405. #define fps ints
  3406. #define n_fps n_ints
  3407. #endif
  3408. n_ints++; /* exec env */
  3409. /* Traverse firstly to calculate stack args count */
  3410. for (i = 0; i < func_type->param_count; i++) {
  3411. switch (func_type->types[i]) {
  3412. case VALUE_TYPE_I32:
  3413. #if WASM_ENABLE_GC != 0
  3414. case REF_TYPE_FUNCREF:
  3415. case REF_TYPE_EXTERNREF:
  3416. case REF_TYPE_ANYREF:
  3417. case REF_TYPE_EQREF:
  3418. case REF_TYPE_HT_NULLABLE:
  3419. case REF_TYPE_HT_NON_NULLABLE:
  3420. case REF_TYPE_I31REF:
  3421. case REF_TYPE_NULLFUNCREF:
  3422. case REF_TYPE_NULLEXTERNREF:
  3423. case REF_TYPE_STRUCTREF:
  3424. case REF_TYPE_ARRAYREF:
  3425. case REF_TYPE_NULLREF:
  3426. #if WASM_ENABLE_STRINGREF != 0
  3427. case REF_TYPE_STRINGREF:
  3428. case REF_TYPE_STRINGVIEWWTF8:
  3429. case REF_TYPE_STRINGVIEWWTF16:
  3430. case REF_TYPE_STRINGVIEWITER:
  3431. #endif
  3432. #endif
  3433. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3434. case VALUE_TYPE_FUNCREF:
  3435. case VALUE_TYPE_EXTERNREF:
  3436. #endif
  3437. if (n_ints < MAX_REG_INTS)
  3438. n_ints++;
  3439. else
  3440. n_stacks++;
  3441. break;
  3442. case VALUE_TYPE_I64:
  3443. if (n_ints < MAX_REG_INTS - 1) {
  3444. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3445. /* 64-bit data must be 8 bytes aligned in arm */
  3446. if (n_ints & 1)
  3447. n_ints++;
  3448. #endif
  3449. n_ints += 2;
  3450. }
  3451. #if defined(BUILD_TARGET_RISCV32_ILP32) \
  3452. || defined(BUILD_TARGET_RISCV32_ILP32D) || defined(BUILD_TARGET_ARC)
  3453. /* part in register, part in stack */
  3454. else if (n_ints == MAX_REG_INTS - 1) {
  3455. n_ints++;
  3456. n_stacks++;
  3457. }
  3458. #endif
  3459. else {
  3460. /* 64-bit data in stack must be 8 bytes aligned
  3461. in arm and riscv32 */
  3462. #if !defined(BUILD_TARGET_ARC)
  3463. if (n_stacks & 1)
  3464. n_stacks++;
  3465. #endif
  3466. n_stacks += 2;
  3467. }
  3468. break;
  3469. #if !defined(BUILD_TARGET_RISCV32_ILP32D)
  3470. case VALUE_TYPE_F32:
  3471. if (n_fps < MAX_REG_FLOATS)
  3472. n_fps++;
  3473. else
  3474. n_stacks++;
  3475. break;
  3476. case VALUE_TYPE_F64:
  3477. if (n_fps < MAX_REG_FLOATS - 1) {
  3478. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3479. /* 64-bit data must be 8 bytes aligned in arm */
  3480. if (n_fps & 1)
  3481. n_fps++;
  3482. #endif
  3483. n_fps += 2;
  3484. }
  3485. #if defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3486. else if (n_fps == MAX_REG_FLOATS - 1) {
  3487. n_fps++;
  3488. n_stacks++;
  3489. }
  3490. #endif
  3491. else {
  3492. /* 64-bit data in stack must be 8 bytes aligned
  3493. in arm and riscv32 */
  3494. #if !defined(BUILD_TARGET_ARC)
  3495. if (n_stacks & 1)
  3496. n_stacks++;
  3497. #endif
  3498. n_stacks += 2;
  3499. }
  3500. break;
  3501. #else /* BUILD_TARGET_RISCV32_ILP32D */
  3502. case VALUE_TYPE_F32:
  3503. case VALUE_TYPE_F64:
  3504. if (n_fps < MAX_REG_FLOATS) {
  3505. n_fps++;
  3506. }
  3507. else if (func_type->types[i] == VALUE_TYPE_F32
  3508. && n_ints < MAX_REG_INTS) {
  3509. /* use int reg firstly if available */
  3510. n_ints++;
  3511. }
  3512. else if (func_type->types[i] == VALUE_TYPE_F64
  3513. && n_ints < MAX_REG_INTS - 1) {
  3514. /* use int regs firstly if available */
  3515. if (n_ints & 1)
  3516. n_ints++;
  3517. ints += 2;
  3518. }
  3519. else {
  3520. /* 64-bit data in stack must be 8 bytes aligned in riscv32
  3521. */
  3522. if (n_stacks & 1)
  3523. n_stacks++;
  3524. n_stacks += 2;
  3525. }
  3526. break;
  3527. #endif /* BUILD_TARGET_RISCV32_ILP32D */
  3528. default:
  3529. bh_assert(0);
  3530. break;
  3531. }
  3532. }
  3533. for (i = 0; i < ext_ret_count; i++) {
  3534. if (n_ints < MAX_REG_INTS)
  3535. n_ints++;
  3536. else
  3537. n_stacks++;
  3538. }
  3539. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3540. argc1 = MAX_REG_INTS + MAX_REG_FLOATS + n_stacks;
  3541. #elif defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3542. argc1 = MAX_REG_INTS + n_stacks;
  3543. #else /* for BUILD_TARGET_RISCV32_ILP32D */
  3544. argc1 = MAX_REG_INTS + MAX_REG_FLOATS * 2 + n_stacks;
  3545. #endif
  3546. if (argc1 > sizeof(argv_buf) / sizeof(uint32)) {
  3547. size = sizeof(uint32) * (uint32)argc1;
  3548. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3549. 0))) {
  3550. return false;
  3551. }
  3552. }
  3553. ints = argv1;
  3554. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3555. fps = ints + MAX_REG_INTS;
  3556. stacks = fps + MAX_REG_FLOATS;
  3557. #elif defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3558. stacks = ints + MAX_REG_INTS;
  3559. #else /* for BUILD_TARGET_RISCV32_ILP32D */
  3560. fps = ints + MAX_REG_INTS;
  3561. stacks = fps + MAX_REG_FLOATS * 2;
  3562. #endif
  3563. n_ints = 0;
  3564. n_fps = 0;
  3565. n_stacks = 0;
  3566. ints[n_ints++] = (uint32)(uintptr_t)exec_env;
  3567. /* Traverse secondly to fill in each argument */
  3568. for (i = 0; i < func_type->param_count; i++) {
  3569. switch (func_type->types[i]) {
  3570. case VALUE_TYPE_I32:
  3571. #if WASM_ENABLE_GC != 0
  3572. case REF_TYPE_FUNCREF:
  3573. case REF_TYPE_EXTERNREF:
  3574. case REF_TYPE_ANYREF:
  3575. case REF_TYPE_EQREF:
  3576. case REF_TYPE_HT_NULLABLE:
  3577. case REF_TYPE_HT_NON_NULLABLE:
  3578. case REF_TYPE_I31REF:
  3579. case REF_TYPE_NULLFUNCREF:
  3580. case REF_TYPE_NULLEXTERNREF:
  3581. case REF_TYPE_STRUCTREF:
  3582. case REF_TYPE_ARRAYREF:
  3583. case REF_TYPE_NULLREF:
  3584. #if WASM_ENABLE_STRINGREF != 0
  3585. case REF_TYPE_STRINGREF:
  3586. case REF_TYPE_STRINGVIEWWTF8:
  3587. case REF_TYPE_STRINGVIEWWTF16:
  3588. case REF_TYPE_STRINGVIEWITER:
  3589. #endif
  3590. #endif
  3591. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3592. case VALUE_TYPE_FUNCREF:
  3593. #endif
  3594. {
  3595. arg_i32 = *argv_src++;
  3596. if (signature) {
  3597. if (signature[i + 1] == '*') {
  3598. /* param is a pointer */
  3599. if (signature[i + 2] == '~')
  3600. /* pointer with length followed */
  3601. ptr_len = *argv_src;
  3602. else
  3603. /* pointer without length followed */
  3604. ptr_len = 1;
  3605. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3606. ptr_len))
  3607. goto fail;
  3608. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3609. module, arg_i32);
  3610. }
  3611. else if (signature[i + 1] == '$') {
  3612. /* param is a string */
  3613. if (!wasm_runtime_validate_app_str_addr(module,
  3614. arg_i32))
  3615. goto fail;
  3616. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3617. module, arg_i32);
  3618. }
  3619. }
  3620. if (n_ints < MAX_REG_INTS)
  3621. ints[n_ints++] = arg_i32;
  3622. else
  3623. stacks[n_stacks++] = arg_i32;
  3624. break;
  3625. }
  3626. case VALUE_TYPE_I64:
  3627. {
  3628. if (n_ints < MAX_REG_INTS - 1) {
  3629. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3630. /* 64-bit data must be 8 bytes aligned in arm */
  3631. if (n_ints & 1)
  3632. n_ints++;
  3633. #endif
  3634. ints[n_ints++] = *argv_src++;
  3635. ints[n_ints++] = *argv_src++;
  3636. }
  3637. #if defined(BUILD_TARGET_RISCV32_ILP32) \
  3638. || defined(BUILD_TARGET_RISCV32_ILP32D) || defined(BUILD_TARGET_ARC)
  3639. else if (n_ints == MAX_REG_INTS - 1) {
  3640. ints[n_ints++] = *argv_src++;
  3641. stacks[n_stacks++] = *argv_src++;
  3642. }
  3643. #endif
  3644. else {
  3645. /* 64-bit data in stack must be 8 bytes aligned
  3646. in arm and riscv32 */
  3647. #if !defined(BUILD_TARGET_ARC)
  3648. if (n_stacks & 1)
  3649. n_stacks++;
  3650. #endif
  3651. stacks[n_stacks++] = *argv_src++;
  3652. stacks[n_stacks++] = *argv_src++;
  3653. }
  3654. break;
  3655. }
  3656. #if !defined(BUILD_TARGET_RISCV32_ILP32D)
  3657. case VALUE_TYPE_F32:
  3658. {
  3659. if (n_fps < MAX_REG_FLOATS)
  3660. *(float32 *)&fps[n_fps++] = *(float32 *)argv_src++;
  3661. else
  3662. *(float32 *)&stacks[n_stacks++] = *(float32 *)argv_src++;
  3663. break;
  3664. }
  3665. case VALUE_TYPE_F64:
  3666. {
  3667. if (n_fps < MAX_REG_FLOATS - 1) {
  3668. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3669. /* 64-bit data must be 8 bytes aligned in arm */
  3670. if (n_fps & 1)
  3671. n_fps++;
  3672. #endif
  3673. fps[n_fps++] = *argv_src++;
  3674. fps[n_fps++] = *argv_src++;
  3675. }
  3676. #if defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3677. else if (n_fps == MAX_REG_FLOATS - 1) {
  3678. fps[n_fps++] = *argv_src++;
  3679. stacks[n_stacks++] = *argv_src++;
  3680. }
  3681. #endif
  3682. else {
  3683. /* 64-bit data in stack must be 8 bytes aligned
  3684. in arm and riscv32 */
  3685. #if !defined(BUILD_TARGET_ARC)
  3686. if (n_stacks & 1)
  3687. n_stacks++;
  3688. #endif
  3689. stacks[n_stacks++] = *argv_src++;
  3690. stacks[n_stacks++] = *argv_src++;
  3691. }
  3692. break;
  3693. }
  3694. #else /* BUILD_TARGET_RISCV32_ILP32D */
  3695. case VALUE_TYPE_F32:
  3696. case VALUE_TYPE_F64:
  3697. {
  3698. if (n_fps < MAX_REG_FLOATS) {
  3699. if (func_type->types[i] == VALUE_TYPE_F32) {
  3700. *(float32 *)&fps[n_fps * 2] = *(float32 *)argv_src++;
  3701. /* NaN boxing, the upper bits of a valid NaN-boxed
  3702. value must be all 1s. */
  3703. fps[n_fps * 2 + 1] = 0xFFFFFFFF;
  3704. }
  3705. else {
  3706. *(float64 *)&fps[n_fps * 2] = *(float64 *)argv_src;
  3707. argv_src += 2;
  3708. }
  3709. n_fps++;
  3710. }
  3711. else if (func_type->types[i] == VALUE_TYPE_F32
  3712. && n_ints < MAX_REG_INTS) {
  3713. /* use int reg firstly if available */
  3714. *(float32 *)&ints[n_ints++] = *(float32 *)argv_src++;
  3715. }
  3716. else if (func_type->types[i] == VALUE_TYPE_F64
  3717. && n_ints < MAX_REG_INTS - 1) {
  3718. /* use int regs firstly if available */
  3719. if (n_ints & 1)
  3720. n_ints++;
  3721. *(float64 *)&ints[n_ints] = *(float64 *)argv_src;
  3722. n_ints += 2;
  3723. argv_src += 2;
  3724. }
  3725. else {
  3726. /* 64-bit data in stack must be 8 bytes aligned in riscv32
  3727. */
  3728. if (n_stacks & 1)
  3729. n_stacks++;
  3730. if (func_type->types[i] == VALUE_TYPE_F32) {
  3731. *(float32 *)&stacks[n_stacks++] =
  3732. *(float32 *)argv_src++;
  3733. }
  3734. else {
  3735. *(float64 *)&stacks[n_stacks] = *(float64 *)argv_src;
  3736. argv_src += 2;
  3737. n_stacks += 2;
  3738. }
  3739. }
  3740. break;
  3741. }
  3742. #endif /* BUILD_TARGET_RISCV32_ILP32D */
  3743. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3744. case VALUE_TYPE_EXTERNREF:
  3745. {
  3746. uint32 externref_idx = *argv_src++;
  3747. if (is_aot_func) {
  3748. if (n_ints < MAX_REG_INTS)
  3749. ints[n_ints++] = externref_idx;
  3750. else
  3751. stacks[n_stacks++] = externref_idx;
  3752. }
  3753. else {
  3754. void *externref_obj;
  3755. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3756. goto fail;
  3757. if (n_ints < MAX_REG_INTS)
  3758. ints[n_ints++] = (uintptr_t)externref_obj;
  3759. else
  3760. stacks[n_stacks++] = (uintptr_t)externref_obj;
  3761. }
  3762. break;
  3763. }
  3764. #endif
  3765. default:
  3766. bh_assert(0);
  3767. break;
  3768. }
  3769. }
  3770. /* Save extra result values' address to argv1 */
  3771. for (i = 0; i < ext_ret_count; i++) {
  3772. if (n_ints < MAX_REG_INTS)
  3773. ints[n_ints++] = *(uint32 *)argv_src++;
  3774. else
  3775. stacks[n_stacks++] = *(uint32 *)argv_src++;
  3776. }
  3777. exec_env->attachment = attachment;
  3778. if (func_type->result_count == 0) {
  3779. invokeNative_Void(func_ptr, argv1, n_stacks);
  3780. }
  3781. else {
  3782. switch (func_type->types[func_type->param_count]) {
  3783. case VALUE_TYPE_I32:
  3784. #if WASM_ENABLE_GC != 0
  3785. case REF_TYPE_FUNCREF:
  3786. case REF_TYPE_EXTERNREF:
  3787. case REF_TYPE_ANYREF:
  3788. case REF_TYPE_EQREF:
  3789. case REF_TYPE_HT_NULLABLE:
  3790. case REF_TYPE_HT_NON_NULLABLE:
  3791. case REF_TYPE_I31REF:
  3792. case REF_TYPE_NULLFUNCREF:
  3793. case REF_TYPE_NULLEXTERNREF:
  3794. case REF_TYPE_STRUCTREF:
  3795. case REF_TYPE_ARRAYREF:
  3796. case REF_TYPE_NULLREF:
  3797. #if WASM_ENABLE_STRINGREF != 0
  3798. case REF_TYPE_STRINGREF:
  3799. case REF_TYPE_STRINGVIEWWTF8:
  3800. case REF_TYPE_STRINGVIEWWTF16:
  3801. case REF_TYPE_STRINGVIEWITER:
  3802. #endif
  3803. #endif
  3804. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3805. case VALUE_TYPE_FUNCREF:
  3806. #endif
  3807. argv_ret[0] =
  3808. (uint32)invokeNative_Int32(func_ptr, argv1, n_stacks);
  3809. break;
  3810. case VALUE_TYPE_I64:
  3811. PUT_I64_TO_ADDR(argv_ret,
  3812. invokeNative_Int64(func_ptr, argv1, n_stacks));
  3813. break;
  3814. case VALUE_TYPE_F32:
  3815. *(float32 *)argv_ret =
  3816. invokeNative_Float32(func_ptr, argv1, n_stacks);
  3817. break;
  3818. case VALUE_TYPE_F64:
  3819. PUT_F64_TO_ADDR(
  3820. argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks));
  3821. break;
  3822. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3823. case VALUE_TYPE_EXTERNREF:
  3824. {
  3825. if (is_aot_func) {
  3826. uint32 externref_idx =
  3827. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  3828. argv_ret[0] = externref_idx;
  3829. }
  3830. else {
  3831. uint32 externref_idx;
  3832. void *externref_obj;
  3833. externref_obj = (void *)(uintptr_t)invokeNative_Int32(
  3834. func_ptr, argv1, argc1);
  3835. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3836. externref_obj, &externref_idx))
  3837. goto fail;
  3838. argv_ret[0] = externref_idx;
  3839. }
  3840. break;
  3841. }
  3842. #endif
  3843. default:
  3844. bh_assert(0);
  3845. break;
  3846. }
  3847. }
  3848. exec_env->attachment = NULL;
  3849. ret = !wasm_runtime_copy_exception(module, NULL);
  3850. fail:
  3851. if (argv1 != argv_buf)
  3852. wasm_runtime_free(argv1);
  3853. return ret;
  3854. }
  3855. #endif /* end of defined(BUILD_TARGET_ARM_VFP) \
  3856. || defined(BUILD_TARGET_THUMB_VFP) \
  3857. || defined(BUILD_TARGET_RISCV32_ILP32D) \
  3858. || defined(BUILD_TARGET_RISCV32_ILP32) \
  3859. || defined(BUILD_TARGET_ARC) */
  3860. #if defined(BUILD_TARGET_X86_32) || defined(BUILD_TARGET_ARM) \
  3861. || defined(BUILD_TARGET_THUMB) || defined(BUILD_TARGET_MIPS) \
  3862. || defined(BUILD_TARGET_XTENSA)
  3863. typedef void (*GenericFunctionPointer)();
  3864. void
  3865. invokeNative(GenericFunctionPointer f, uint32 *args, uint32 sz);
  3866. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3867. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3868. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3869. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3870. typedef void (*VoidFuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3871. static volatile Int64FuncPtr invokeNative_Int64 =
  3872. (Int64FuncPtr)(uintptr_t)invokeNative;
  3873. static volatile Int32FuncPtr invokeNative_Int32 =
  3874. (Int32FuncPtr)(uintptr_t)invokeNative;
  3875. static volatile Float64FuncPtr invokeNative_Float64 =
  3876. (Float64FuncPtr)(uintptr_t)invokeNative;
  3877. static volatile Float32FuncPtr invokeNative_Float32 =
  3878. (Float32FuncPtr)(uintptr_t)invokeNative;
  3879. static volatile VoidFuncPtr invokeNative_Void =
  3880. (VoidFuncPtr)(uintptr_t)invokeNative;
  3881. static inline void
  3882. word_copy(uint32 *dest, uint32 *src, unsigned num)
  3883. {
  3884. for (; num > 0; num--)
  3885. *dest++ = *src++;
  3886. }
  3887. bool
  3888. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  3889. const WASMFuncType *func_type, const char *signature,
  3890. void *attachment, uint32 *argv, uint32 argc,
  3891. uint32 *argv_ret)
  3892. {
  3893. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3894. uint32 argv_buf[32], *argv1 = argv_buf, argc1, i, j = 0;
  3895. uint32 arg_i32, ptr_len;
  3896. uint32 result_count = func_type->result_count;
  3897. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  3898. uint64 size;
  3899. bool ret = false;
  3900. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3901. bool is_aot_func = (NULL == signature);
  3902. #endif
  3903. #if defined(BUILD_TARGET_X86_32)
  3904. argc1 = argc + ext_ret_count + 2;
  3905. #else
  3906. /* arm/thumb/mips/xtensa, 64-bit data must be 8 bytes aligned,
  3907. so we need to allocate more memory. */
  3908. argc1 = func_type->param_count * 2 + ext_ret_count + 2;
  3909. #endif
  3910. if (argc1 > sizeof(argv_buf) / sizeof(uint32)) {
  3911. size = sizeof(uint32) * (uint64)argc1;
  3912. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3913. 0))) {
  3914. return false;
  3915. }
  3916. }
  3917. for (i = 0; i < sizeof(WASMExecEnv *) / sizeof(uint32); i++)
  3918. argv1[j++] = ((uint32 *)&exec_env)[i];
  3919. for (i = 0; i < func_type->param_count; i++) {
  3920. switch (func_type->types[i]) {
  3921. case VALUE_TYPE_I32:
  3922. #if WASM_ENABLE_GC != 0
  3923. case REF_TYPE_FUNCREF:
  3924. case REF_TYPE_EXTERNREF:
  3925. case REF_TYPE_ANYREF:
  3926. case REF_TYPE_EQREF:
  3927. case REF_TYPE_HT_NULLABLE:
  3928. case REF_TYPE_HT_NON_NULLABLE:
  3929. case REF_TYPE_I31REF:
  3930. case REF_TYPE_NULLFUNCREF:
  3931. case REF_TYPE_NULLEXTERNREF:
  3932. case REF_TYPE_STRUCTREF:
  3933. case REF_TYPE_ARRAYREF:
  3934. case REF_TYPE_NULLREF:
  3935. #if WASM_ENABLE_STRINGREF != 0
  3936. case REF_TYPE_STRINGREF:
  3937. case REF_TYPE_STRINGVIEWWTF8:
  3938. case REF_TYPE_STRINGVIEWWTF16:
  3939. case REF_TYPE_STRINGVIEWITER:
  3940. #endif
  3941. #endif
  3942. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3943. case VALUE_TYPE_FUNCREF:
  3944. #endif
  3945. {
  3946. arg_i32 = *argv++;
  3947. if (signature) {
  3948. if (signature[i + 1] == '*') {
  3949. /* param is a pointer */
  3950. if (signature[i + 2] == '~')
  3951. /* pointer with length followed */
  3952. ptr_len = *argv;
  3953. else
  3954. /* pointer without length followed */
  3955. ptr_len = 1;
  3956. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3957. ptr_len))
  3958. goto fail;
  3959. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3960. module, arg_i32);
  3961. }
  3962. else if (signature[i + 1] == '$') {
  3963. /* param is a string */
  3964. if (!wasm_runtime_validate_app_str_addr(module,
  3965. arg_i32))
  3966. goto fail;
  3967. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3968. module, arg_i32);
  3969. }
  3970. }
  3971. argv1[j++] = arg_i32;
  3972. break;
  3973. }
  3974. case VALUE_TYPE_I64:
  3975. case VALUE_TYPE_F64:
  3976. #if !defined(BUILD_TARGET_X86_32)
  3977. /* 64-bit data must be 8 bytes aligned in arm, thumb, mips
  3978. and xtensa */
  3979. if (j & 1)
  3980. j++;
  3981. #endif
  3982. argv1[j++] = *argv++;
  3983. argv1[j++] = *argv++;
  3984. break;
  3985. case VALUE_TYPE_F32:
  3986. argv1[j++] = *argv++;
  3987. break;
  3988. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3989. case VALUE_TYPE_EXTERNREF:
  3990. {
  3991. uint32 externref_idx = *argv++;
  3992. if (is_aot_func) {
  3993. argv1[j++] = externref_idx;
  3994. }
  3995. else {
  3996. void *externref_obj;
  3997. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3998. goto fail;
  3999. argv1[j++] = (uintptr_t)externref_obj;
  4000. }
  4001. break;
  4002. }
  4003. #endif
  4004. default:
  4005. bh_assert(0);
  4006. break;
  4007. }
  4008. }
  4009. /* Save extra result values' address to argv1 */
  4010. word_copy(argv1 + j, argv, ext_ret_count);
  4011. argc1 = j + ext_ret_count;
  4012. exec_env->attachment = attachment;
  4013. if (func_type->result_count == 0) {
  4014. invokeNative_Void(func_ptr, argv1, argc1);
  4015. }
  4016. else {
  4017. switch (func_type->types[func_type->param_count]) {
  4018. case VALUE_TYPE_I32:
  4019. #if WASM_ENABLE_GC != 0
  4020. case REF_TYPE_FUNCREF:
  4021. case REF_TYPE_EXTERNREF:
  4022. case REF_TYPE_ANYREF:
  4023. case REF_TYPE_EQREF:
  4024. case REF_TYPE_HT_NULLABLE:
  4025. case REF_TYPE_HT_NON_NULLABLE:
  4026. case REF_TYPE_I31REF:
  4027. case REF_TYPE_NULLFUNCREF:
  4028. case REF_TYPE_NULLEXTERNREF:
  4029. case REF_TYPE_STRUCTREF:
  4030. case REF_TYPE_ARRAYREF:
  4031. case REF_TYPE_NULLREF:
  4032. #if WASM_ENABLE_STRINGREF != 0
  4033. case REF_TYPE_STRINGREF:
  4034. case REF_TYPE_STRINGVIEWWTF8:
  4035. case REF_TYPE_STRINGVIEWWTF16:
  4036. case REF_TYPE_STRINGVIEWITER:
  4037. #endif
  4038. #endif
  4039. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4040. case VALUE_TYPE_FUNCREF:
  4041. #endif
  4042. argv_ret[0] =
  4043. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  4044. break;
  4045. case VALUE_TYPE_I64:
  4046. PUT_I64_TO_ADDR(argv_ret,
  4047. invokeNative_Int64(func_ptr, argv1, argc1));
  4048. break;
  4049. case VALUE_TYPE_F32:
  4050. *(float32 *)argv_ret =
  4051. invokeNative_Float32(func_ptr, argv1, argc1);
  4052. break;
  4053. case VALUE_TYPE_F64:
  4054. PUT_F64_TO_ADDR(argv_ret,
  4055. invokeNative_Float64(func_ptr, argv1, argc1));
  4056. break;
  4057. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4058. case VALUE_TYPE_EXTERNREF:
  4059. {
  4060. if (is_aot_func) {
  4061. uint32 externref_idx =
  4062. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  4063. argv_ret[0] = externref_idx;
  4064. }
  4065. else {
  4066. void *externref_obj = (void *)(uintptr_t)invokeNative_Int32(
  4067. func_ptr, argv1, argc1);
  4068. uint32 externref_idx;
  4069. if (!wasm_externref_obj2ref(exec_env->module_inst,
  4070. externref_obj, &externref_idx))
  4071. goto fail;
  4072. argv_ret[0] = externref_idx;
  4073. }
  4074. break;
  4075. }
  4076. #endif
  4077. default:
  4078. bh_assert(0);
  4079. break;
  4080. }
  4081. }
  4082. exec_env->attachment = NULL;
  4083. ret = !wasm_runtime_copy_exception(module, NULL);
  4084. fail:
  4085. if (argv1 != argv_buf)
  4086. wasm_runtime_free(argv1);
  4087. return ret;
  4088. }
  4089. #endif /* end of defined(BUILD_TARGET_X86_32) \
  4090. || defined(BUILD_TARGET_ARM) \
  4091. || defined(BUILD_TARGET_THUMB) \
  4092. || defined(BUILD_TARGET_MIPS) \
  4093. || defined(BUILD_TARGET_XTENSA) */
  4094. #if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \
  4095. || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \
  4096. || defined(BUILD_TARGET_RISCV64_LP64)
  4097. #if WASM_ENABLE_SIMD != 0
  4098. #ifdef v128
  4099. #undef v128
  4100. #endif
  4101. #if defined(_WIN32) || defined(_WIN32_)
  4102. typedef union __declspec(intrin_type) __declspec(align(8)) v128 {
  4103. __int8 m128i_i8[16];
  4104. __int16 m128i_i16[8];
  4105. __int32 m128i_i32[4];
  4106. __int64 m128i_i64[2];
  4107. unsigned __int8 m128i_u8[16];
  4108. unsigned __int16 m128i_u16[8];
  4109. unsigned __int32 m128i_u32[4];
  4110. unsigned __int64 m128i_u64[2];
  4111. } v128;
  4112. #elif defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \
  4113. || defined(BUILD_TARGET_RISCV64_LP64D) \
  4114. || defined(BUILD_TARGET_RISCV64_LP64)
  4115. typedef long long v128
  4116. __attribute__((__vector_size__(16), __may_alias__, __aligned__(1)));
  4117. #elif defined(BUILD_TARGET_AARCH64)
  4118. #include <arm_neon.h>
  4119. typedef uint32x4_t __m128i;
  4120. #define v128 __m128i
  4121. #endif
  4122. #endif /* end of WASM_ENABLE_SIMD != 0 */
  4123. typedef void (*GenericFunctionPointer)();
  4124. void
  4125. invokeNative(GenericFunctionPointer f, uint64 *args, uint64 n_stacks);
  4126. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4127. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4128. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4129. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4130. typedef void (*VoidFuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4131. static volatile Float64FuncPtr invokeNative_Float64 =
  4132. (Float64FuncPtr)(uintptr_t)invokeNative;
  4133. static volatile Float32FuncPtr invokeNative_Float32 =
  4134. (Float32FuncPtr)(uintptr_t)invokeNative;
  4135. static volatile Int64FuncPtr invokeNative_Int64 =
  4136. (Int64FuncPtr)(uintptr_t)invokeNative;
  4137. static volatile Int32FuncPtr invokeNative_Int32 =
  4138. (Int32FuncPtr)(uintptr_t)invokeNative;
  4139. static volatile VoidFuncPtr invokeNative_Void =
  4140. (VoidFuncPtr)(uintptr_t)invokeNative;
  4141. #if WASM_ENABLE_SIMD != 0
  4142. typedef v128 (*V128FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  4143. static V128FuncPtr invokeNative_V128 = (V128FuncPtr)(uintptr_t)invokeNative;
  4144. #endif
  4145. #if defined(_WIN32) || defined(_WIN32_)
  4146. #define MAX_REG_FLOATS 4
  4147. #define MAX_REG_INTS 4
  4148. #else /* else of defined(_WIN32) || defined(_WIN32_) */
  4149. #define MAX_REG_FLOATS 8
  4150. #if defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \
  4151. || defined(BUILD_TARGET_RISCV64_LP64)
  4152. #define MAX_REG_INTS 8
  4153. #else
  4154. #define MAX_REG_INTS 6
  4155. #endif /* end of defined(BUILD_TARGET_AARCH64) \
  4156. || defined(BUILD_TARGET_RISCV64_LP64D) \
  4157. || defined(BUILD_TARGET_RISCV64_LP64) */
  4158. #endif /* end of defined(_WIN32) || defined(_WIN32_) */
  4159. /*
  4160. * ASAN is not designed to work with custom stack unwind or other low-level
  4161. * things. Ignore a function that does some low-level magic. (e.g. walking
  4162. * through the thread's stack bypassing the frame boundaries)
  4163. */
  4164. #if defined(__GNUC__) || defined(__clang__)
  4165. __attribute__((no_sanitize_address))
  4166. #endif
  4167. bool
  4168. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  4169. const WASMFuncType *func_type, const char *signature,
  4170. void *attachment, uint32 *argv, uint32 argc,
  4171. uint32 *argv_ret)
  4172. {
  4173. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  4174. uint64 argv_buf[32] = { 0 }, *argv1 = argv_buf, *ints, *stacks, size,
  4175. arg_i64;
  4176. uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0;
  4177. uint32 arg_i32, ptr_len;
  4178. uint32 result_count = func_type->result_count;
  4179. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  4180. bool ret = false;
  4181. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4182. bool is_aot_func = (NULL == signature);
  4183. #endif
  4184. #ifndef BUILD_TARGET_RISCV64_LP64
  4185. #if WASM_ENABLE_SIMD == 0
  4186. uint64 *fps;
  4187. #else
  4188. v128 *fps;
  4189. #endif
  4190. #else /* else of BUILD_TARGET_RISCV64_LP64 */
  4191. #define fps ints
  4192. #endif /* end of BUILD_TARGET_RISCV64_LP64 */
  4193. #if defined(_WIN32) || defined(_WIN32_) || defined(BUILD_TARGET_RISCV64_LP64)
  4194. /* important difference in calling conventions */
  4195. #define n_fps n_ints
  4196. #else
  4197. int n_fps = 0;
  4198. #endif
  4199. #if WASM_ENABLE_SIMD == 0
  4200. argc1 = 1 + MAX_REG_FLOATS + (uint32)func_type->param_count + ext_ret_count;
  4201. #else
  4202. argc1 = 1 + MAX_REG_FLOATS * 2 + (uint32)func_type->param_count * 2
  4203. + ext_ret_count;
  4204. #endif
  4205. if (argc1 > sizeof(argv_buf) / sizeof(uint64)) {
  4206. size = sizeof(uint64) * (uint64)argc1;
  4207. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  4208. 0))) {
  4209. return false;
  4210. }
  4211. }
  4212. #ifndef BUILD_TARGET_RISCV64_LP64
  4213. #if WASM_ENABLE_SIMD == 0
  4214. fps = argv1;
  4215. ints = fps + MAX_REG_FLOATS;
  4216. #else
  4217. fps = (v128 *)argv1;
  4218. ints = (uint64 *)(fps + MAX_REG_FLOATS);
  4219. #endif
  4220. #else /* else of BUILD_TARGET_RISCV64_LP64 */
  4221. ints = argv1;
  4222. #endif /* end of BUILD_TARGET_RISCV64_LP64 */
  4223. stacks = ints + MAX_REG_INTS;
  4224. ints[n_ints++] = (uint64)(uintptr_t)exec_env;
  4225. for (i = 0; i < func_type->param_count; i++) {
  4226. switch (func_type->types[i]) {
  4227. case VALUE_TYPE_I32:
  4228. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4229. case VALUE_TYPE_FUNCREF:
  4230. #endif
  4231. {
  4232. arg_i32 = *argv_src++;
  4233. arg_i64 = arg_i32;
  4234. if (signature) {
  4235. if (signature[i + 1] == '*') {
  4236. /* param is a pointer */
  4237. if (signature[i + 2] == '~')
  4238. /* pointer with length followed */
  4239. ptr_len = *argv_src;
  4240. else
  4241. /* pointer without length followed */
  4242. ptr_len = 1;
  4243. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  4244. ptr_len))
  4245. goto fail;
  4246. arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native(
  4247. module, arg_i32);
  4248. }
  4249. else if (signature[i + 1] == '$') {
  4250. /* param is a string */
  4251. if (!wasm_runtime_validate_app_str_addr(module,
  4252. arg_i32))
  4253. goto fail;
  4254. arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native(
  4255. module, arg_i32);
  4256. }
  4257. }
  4258. if (n_ints < MAX_REG_INTS)
  4259. ints[n_ints++] = arg_i64;
  4260. else
  4261. stacks[n_stacks++] = arg_i64;
  4262. break;
  4263. }
  4264. case VALUE_TYPE_I64:
  4265. #if WASM_ENABLE_GC != 0
  4266. case REF_TYPE_FUNCREF:
  4267. case REF_TYPE_EXTERNREF:
  4268. case REF_TYPE_ANYREF:
  4269. case REF_TYPE_EQREF:
  4270. case REF_TYPE_HT_NULLABLE:
  4271. case REF_TYPE_HT_NON_NULLABLE:
  4272. case REF_TYPE_I31REF:
  4273. case REF_TYPE_NULLFUNCREF:
  4274. case REF_TYPE_NULLEXTERNREF:
  4275. case REF_TYPE_STRUCTREF:
  4276. case REF_TYPE_ARRAYREF:
  4277. case REF_TYPE_NULLREF:
  4278. #if WASM_ENABLE_STRINGREF != 0
  4279. case REF_TYPE_STRINGREF:
  4280. case REF_TYPE_STRINGVIEWWTF8:
  4281. case REF_TYPE_STRINGVIEWWTF16:
  4282. case REF_TYPE_STRINGVIEWITER:
  4283. #endif
  4284. #endif
  4285. if (n_ints < MAX_REG_INTS)
  4286. ints[n_ints++] = *(uint64 *)argv_src;
  4287. else
  4288. stacks[n_stacks++] = *(uint64 *)argv_src;
  4289. argv_src += 2;
  4290. break;
  4291. case VALUE_TYPE_F32:
  4292. if (n_fps < MAX_REG_FLOATS) {
  4293. *(float32 *)&fps[n_fps++] = *(float32 *)argv_src++;
  4294. }
  4295. else {
  4296. *(float32 *)&stacks[n_stacks++] = *(float32 *)argv_src++;
  4297. }
  4298. break;
  4299. case VALUE_TYPE_F64:
  4300. if (n_fps < MAX_REG_FLOATS) {
  4301. *(float64 *)&fps[n_fps++] = *(float64 *)argv_src;
  4302. }
  4303. else {
  4304. *(float64 *)&stacks[n_stacks++] = *(float64 *)argv_src;
  4305. }
  4306. argv_src += 2;
  4307. break;
  4308. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4309. case VALUE_TYPE_EXTERNREF:
  4310. {
  4311. uint32 externref_idx = *argv_src++;
  4312. if (is_aot_func) {
  4313. if (n_ints < MAX_REG_INTS)
  4314. ints[n_ints++] = externref_idx;
  4315. else
  4316. stacks[n_stacks++] = externref_idx;
  4317. }
  4318. else {
  4319. void *externref_obj;
  4320. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  4321. goto fail;
  4322. if (n_ints < MAX_REG_INTS)
  4323. ints[n_ints++] = (uintptr_t)externref_obj;
  4324. else
  4325. stacks[n_stacks++] = (uintptr_t)externref_obj;
  4326. }
  4327. break;
  4328. }
  4329. #endif
  4330. #if WASM_ENABLE_SIMD != 0
  4331. case VALUE_TYPE_V128:
  4332. if (n_fps < MAX_REG_FLOATS) {
  4333. *(v128 *)&fps[n_fps++] = *(v128 *)argv_src;
  4334. }
  4335. else {
  4336. *(v128 *)&stacks[n_stacks++] = *(v128 *)argv_src;
  4337. n_stacks++;
  4338. }
  4339. argv_src += 4;
  4340. break;
  4341. #endif
  4342. default:
  4343. bh_assert(0);
  4344. break;
  4345. }
  4346. }
  4347. /* Save extra result values' address to argv1 */
  4348. for (i = 0; i < ext_ret_count; i++) {
  4349. if (n_ints < MAX_REG_INTS)
  4350. ints[n_ints++] = *(uint64 *)argv_src;
  4351. else
  4352. stacks[n_stacks++] = *(uint64 *)argv_src;
  4353. argv_src += 2;
  4354. }
  4355. exec_env->attachment = attachment;
  4356. if (result_count == 0) {
  4357. invokeNative_Void(func_ptr, argv1, n_stacks);
  4358. }
  4359. else {
  4360. /* Invoke the native function and get the first result value */
  4361. switch (func_type->types[func_type->param_count]) {
  4362. case VALUE_TYPE_I32:
  4363. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4364. case VALUE_TYPE_FUNCREF:
  4365. #endif
  4366. argv_ret[0] =
  4367. (uint32)invokeNative_Int32(func_ptr, argv1, n_stacks);
  4368. break;
  4369. case VALUE_TYPE_I64:
  4370. #if WASM_ENABLE_GC != 0
  4371. case REF_TYPE_FUNCREF:
  4372. case REF_TYPE_EXTERNREF:
  4373. case REF_TYPE_ANYREF:
  4374. case REF_TYPE_EQREF:
  4375. case REF_TYPE_HT_NULLABLE:
  4376. case REF_TYPE_HT_NON_NULLABLE:
  4377. case REF_TYPE_I31REF:
  4378. case REF_TYPE_NULLFUNCREF:
  4379. case REF_TYPE_NULLEXTERNREF:
  4380. case REF_TYPE_STRUCTREF:
  4381. case REF_TYPE_ARRAYREF:
  4382. case REF_TYPE_NULLREF:
  4383. #if WASM_ENABLE_STRINGREF != 0
  4384. case REF_TYPE_STRINGREF:
  4385. case REF_TYPE_STRINGVIEWWTF8:
  4386. case REF_TYPE_STRINGVIEWWTF16:
  4387. case REF_TYPE_STRINGVIEWITER:
  4388. #endif
  4389. #endif
  4390. PUT_I64_TO_ADDR(argv_ret,
  4391. invokeNative_Int64(func_ptr, argv1, n_stacks));
  4392. break;
  4393. case VALUE_TYPE_F32:
  4394. *(float32 *)argv_ret =
  4395. invokeNative_Float32(func_ptr, argv1, n_stacks);
  4396. break;
  4397. case VALUE_TYPE_F64:
  4398. PUT_F64_TO_ADDR(
  4399. argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks));
  4400. break;
  4401. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4402. case VALUE_TYPE_EXTERNREF:
  4403. {
  4404. if (is_aot_func) {
  4405. argv_ret[0] = invokeNative_Int32(func_ptr, argv1, n_stacks);
  4406. }
  4407. else {
  4408. uint32 externref_idx;
  4409. void *externref_obj = (void *)(uintptr_t)invokeNative_Int64(
  4410. func_ptr, argv1, n_stacks);
  4411. if (!wasm_externref_obj2ref(exec_env->module_inst,
  4412. externref_obj, &externref_idx))
  4413. goto fail;
  4414. argv_ret[0] = externref_idx;
  4415. }
  4416. break;
  4417. }
  4418. #endif
  4419. #if WASM_ENABLE_SIMD != 0
  4420. case VALUE_TYPE_V128:
  4421. *(v128 *)argv_ret =
  4422. invokeNative_V128(func_ptr, argv1, n_stacks);
  4423. break;
  4424. #endif
  4425. default:
  4426. bh_assert(0);
  4427. break;
  4428. }
  4429. }
  4430. exec_env->attachment = NULL;
  4431. ret = !wasm_runtime_copy_exception(module, NULL);
  4432. fail:
  4433. if (argv1 != argv_buf)
  4434. wasm_runtime_free(argv1);
  4435. return ret;
  4436. }
  4437. #endif /* end of defined(BUILD_TARGET_X86_64) \
  4438. || defined(BUILD_TARGET_AMD_64) \
  4439. || defined(BUILD_TARGET_AARCH64) \
  4440. || defined(BUILD_TARGET_RISCV64_LP64D) \
  4441. || defined(BUILD_TARGET_RISCV64_LP64) */
  4442. bool
  4443. wasm_runtime_call_indirect(WASMExecEnv *exec_env, uint32 element_index,
  4444. uint32 argc, uint32 argv[])
  4445. {
  4446. bool ret = false;
  4447. if (!wasm_runtime_exec_env_check(exec_env)) {
  4448. LOG_ERROR("Invalid exec env stack info.");
  4449. return false;
  4450. }
  4451. /* this function is called from native code, so exec_env->handle and
  4452. exec_env->native_stack_boundary must have been set, we don't set
  4453. it again */
  4454. #if WASM_ENABLE_INTERP != 0
  4455. if (exec_env->module_inst->module_type == Wasm_Module_Bytecode)
  4456. ret = wasm_call_indirect(exec_env, 0, element_index, argc, argv);
  4457. #endif
  4458. #if WASM_ENABLE_AOT != 0
  4459. if (exec_env->module_inst->module_type == Wasm_Module_AoT)
  4460. ret = aot_call_indirect(exec_env, 0, element_index, argc, argv);
  4461. #endif
  4462. return ret;
  4463. }
  4464. static void
  4465. exchange_uint32(uint8 *p_data)
  4466. {
  4467. uint8 value = *p_data;
  4468. *p_data = *(p_data + 3);
  4469. *(p_data + 3) = value;
  4470. value = *(p_data + 1);
  4471. *(p_data + 1) = *(p_data + 2);
  4472. *(p_data + 2) = value;
  4473. }
  4474. static void
  4475. exchange_uint64(uint8 *p_data)
  4476. {
  4477. uint32 value;
  4478. value = *(uint32 *)p_data;
  4479. *(uint32 *)p_data = *(uint32 *)(p_data + 4);
  4480. *(uint32 *)(p_data + 4) = value;
  4481. exchange_uint32(p_data);
  4482. exchange_uint32(p_data + 4);
  4483. }
  4484. void
  4485. wasm_runtime_read_v128(const uint8 *bytes, uint64 *ret1, uint64 *ret2)
  4486. {
  4487. uint64 u1, u2;
  4488. bh_memcpy_s(&u1, 8, bytes, 8);
  4489. bh_memcpy_s(&u2, 8, bytes + 8, 8);
  4490. if (!is_little_endian()) {
  4491. exchange_uint64((uint8 *)&u1);
  4492. exchange_uint64((uint8 *)&u2);
  4493. *ret1 = u2;
  4494. *ret2 = u1;
  4495. }
  4496. else {
  4497. *ret1 = u1;
  4498. *ret2 = u2;
  4499. }
  4500. }
  4501. #if WASM_ENABLE_THREAD_MGR != 0
  4502. typedef struct WASMThreadArg {
  4503. WASMExecEnv *new_exec_env;
  4504. wasm_thread_callback_t callback;
  4505. void *arg;
  4506. } WASMThreadArg;
  4507. WASMExecEnv *
  4508. wasm_runtime_spawn_exec_env(WASMExecEnv *exec_env)
  4509. {
  4510. return wasm_cluster_spawn_exec_env(exec_env);
  4511. }
  4512. void
  4513. wasm_runtime_destroy_spawned_exec_env(WASMExecEnv *exec_env)
  4514. {
  4515. wasm_cluster_destroy_spawned_exec_env(exec_env);
  4516. }
  4517. static void *
  4518. wasm_runtime_thread_routine(void *arg)
  4519. {
  4520. WASMThreadArg *thread_arg = (WASMThreadArg *)arg;
  4521. void *ret;
  4522. bh_assert(thread_arg->new_exec_env);
  4523. ret = thread_arg->callback(thread_arg->new_exec_env, thread_arg->arg);
  4524. wasm_runtime_destroy_spawned_exec_env(thread_arg->new_exec_env);
  4525. wasm_runtime_free(thread_arg);
  4526. os_thread_exit(ret);
  4527. return ret;
  4528. }
  4529. int32
  4530. wasm_runtime_spawn_thread(WASMExecEnv *exec_env, wasm_thread_t *tid,
  4531. wasm_thread_callback_t callback, void *arg)
  4532. {
  4533. WASMExecEnv *new_exec_env = wasm_runtime_spawn_exec_env(exec_env);
  4534. WASMThreadArg *thread_arg;
  4535. int32 ret;
  4536. if (!new_exec_env)
  4537. return -1;
  4538. if (!(thread_arg = wasm_runtime_malloc(sizeof(WASMThreadArg)))) {
  4539. wasm_runtime_destroy_spawned_exec_env(new_exec_env);
  4540. return -1;
  4541. }
  4542. thread_arg->new_exec_env = new_exec_env;
  4543. thread_arg->callback = callback;
  4544. thread_arg->arg = arg;
  4545. ret = os_thread_create((korp_tid *)tid, wasm_runtime_thread_routine,
  4546. thread_arg, APP_THREAD_STACK_SIZE_DEFAULT);
  4547. if (ret != 0) {
  4548. wasm_runtime_destroy_spawned_exec_env(new_exec_env);
  4549. wasm_runtime_free(thread_arg);
  4550. }
  4551. return ret;
  4552. }
  4553. int32
  4554. wasm_runtime_join_thread(wasm_thread_t tid, void **retval)
  4555. {
  4556. return os_thread_join((korp_tid)tid, retval);
  4557. }
  4558. #endif /* end of WASM_ENABLE_THREAD_MGR */
  4559. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  4560. static korp_mutex externref_lock;
  4561. static uint32 externref_global_id = 1;
  4562. static HashMap *externref_map;
  4563. typedef struct ExternRefMapNode {
  4564. /* The extern object from runtime embedder */
  4565. void *extern_obj;
  4566. /* The module instance it belongs to */
  4567. WASMModuleInstanceCommon *module_inst;
  4568. /* Whether it is retained */
  4569. bool retained;
  4570. /* Whether it is marked by runtime */
  4571. bool marked;
  4572. /* cleanup function called when the externref is freed */
  4573. void (*cleanup)(void *);
  4574. } ExternRefMapNode;
  4575. static uint32
  4576. wasm_externref_hash(const void *key)
  4577. {
  4578. uint32 externref_idx = (uint32)(uintptr_t)key;
  4579. return externref_idx;
  4580. }
  4581. static bool
  4582. wasm_externref_equal(void *key1, void *key2)
  4583. {
  4584. uint32 externref_idx1 = (uint32)(uintptr_t)key1;
  4585. uint32 externref_idx2 = (uint32)(uintptr_t)key2;
  4586. return externref_idx1 == externref_idx2 ? true : false;
  4587. }
  4588. static bool
  4589. wasm_externref_map_init()
  4590. {
  4591. if (os_mutex_init(&externref_lock) != 0)
  4592. return false;
  4593. if (!(externref_map = bh_hash_map_create(32, false, wasm_externref_hash,
  4594. wasm_externref_equal, NULL,
  4595. wasm_runtime_free))) {
  4596. os_mutex_destroy(&externref_lock);
  4597. return false;
  4598. }
  4599. externref_global_id = 1;
  4600. return true;
  4601. }
  4602. static void
  4603. wasm_externref_map_destroy()
  4604. {
  4605. bh_hash_map_destroy(externref_map);
  4606. os_mutex_destroy(&externref_lock);
  4607. }
  4608. typedef struct LookupExtObj_UserData {
  4609. ExternRefMapNode node;
  4610. bool found;
  4611. uint32 externref_idx;
  4612. } LookupExtObj_UserData;
  4613. static void
  4614. lookup_extobj_callback(void *key, void *value, void *user_data)
  4615. {
  4616. uint32 externref_idx = (uint32)(uintptr_t)key;
  4617. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4618. LookupExtObj_UserData *user_data_lookup =
  4619. (LookupExtObj_UserData *)user_data;
  4620. if (node->extern_obj == user_data_lookup->node.extern_obj
  4621. && node->module_inst == user_data_lookup->node.module_inst) {
  4622. user_data_lookup->found = true;
  4623. user_data_lookup->externref_idx = externref_idx;
  4624. }
  4625. }
  4626. static void
  4627. delete_externref(void *key, ExternRefMapNode *node)
  4628. {
  4629. bh_hash_map_remove(externref_map, key, NULL, NULL);
  4630. if (node->cleanup) {
  4631. (*node->cleanup)(node->extern_obj);
  4632. }
  4633. wasm_runtime_free(node);
  4634. }
  4635. static void
  4636. delete_extobj_callback(void *key, void *value, void *user_data)
  4637. {
  4638. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4639. LookupExtObj_UserData *lookup_user_data =
  4640. (LookupExtObj_UserData *)user_data;
  4641. if (node->extern_obj == lookup_user_data->node.extern_obj
  4642. && node->module_inst == lookup_user_data->node.module_inst) {
  4643. lookup_user_data->found = true;
  4644. delete_externref(key, node);
  4645. }
  4646. }
  4647. bool
  4648. wasm_externref_objdel(WASMModuleInstanceCommon *module_inst, void *extern_obj)
  4649. {
  4650. LookupExtObj_UserData lookup_user_data = { 0 };
  4651. bool ok = false;
  4652. /* in a wrapper, extern_obj could be any value */
  4653. lookup_user_data.node.extern_obj = extern_obj;
  4654. lookup_user_data.node.module_inst = module_inst;
  4655. lookup_user_data.found = false;
  4656. os_mutex_lock(&externref_lock);
  4657. /* Lookup hashmap firstly */
  4658. bh_hash_map_traverse(externref_map, delete_extobj_callback,
  4659. (void *)&lookup_user_data);
  4660. if (lookup_user_data.found) {
  4661. ok = true;
  4662. }
  4663. os_mutex_unlock(&externref_lock);
  4664. return ok;
  4665. }
  4666. bool
  4667. wasm_externref_set_cleanup(WASMModuleInstanceCommon *module_inst,
  4668. void *extern_obj, void (*extern_obj_cleanup)(void *))
  4669. {
  4670. LookupExtObj_UserData lookup_user_data = { 0 };
  4671. bool ok = false;
  4672. /* in a wrapper, extern_obj could be any value */
  4673. lookup_user_data.node.extern_obj = extern_obj;
  4674. lookup_user_data.node.module_inst = module_inst;
  4675. lookup_user_data.found = false;
  4676. os_mutex_lock(&externref_lock);
  4677. /* Lookup hashmap firstly */
  4678. bh_hash_map_traverse(externref_map, lookup_extobj_callback,
  4679. (void *)&lookup_user_data);
  4680. if (lookup_user_data.found) {
  4681. void *key = (void *)(uintptr_t)lookup_user_data.externref_idx;
  4682. ExternRefMapNode *node = bh_hash_map_find(externref_map, key);
  4683. node->cleanup = extern_obj_cleanup;
  4684. ok = true;
  4685. }
  4686. os_mutex_unlock(&externref_lock);
  4687. return ok;
  4688. }
  4689. bool
  4690. wasm_externref_obj2ref(WASMModuleInstanceCommon *module_inst, void *extern_obj,
  4691. uint32 *p_externref_idx)
  4692. {
  4693. LookupExtObj_UserData lookup_user_data = { 0 };
  4694. ExternRefMapNode *node;
  4695. uint32 externref_idx;
  4696. /*
  4697. * to catch a parameter from `wasm_application_execute_func`,
  4698. * which represents a string 'null'
  4699. */
  4700. #if UINTPTR_MAX == UINT32_MAX
  4701. if ((uint32)-1 == (uintptr_t)extern_obj) {
  4702. #else
  4703. if ((uint64)-1LL == (uintptr_t)extern_obj) {
  4704. #endif
  4705. *p_externref_idx = NULL_REF;
  4706. return true;
  4707. }
  4708. /* in a wrapper, extern_obj could be any value */
  4709. lookup_user_data.node.extern_obj = extern_obj;
  4710. lookup_user_data.node.module_inst = module_inst;
  4711. lookup_user_data.found = false;
  4712. os_mutex_lock(&externref_lock);
  4713. /* Lookup hashmap firstly */
  4714. bh_hash_map_traverse(externref_map, lookup_extobj_callback,
  4715. (void *)&lookup_user_data);
  4716. if (lookup_user_data.found) {
  4717. *p_externref_idx = lookup_user_data.externref_idx;
  4718. os_mutex_unlock(&externref_lock);
  4719. return true;
  4720. }
  4721. /* Not found in hashmap */
  4722. if (externref_global_id == NULL_REF || externref_global_id == 0) {
  4723. goto fail1;
  4724. }
  4725. if (!(node = wasm_runtime_malloc(sizeof(ExternRefMapNode)))) {
  4726. goto fail1;
  4727. }
  4728. memset(node, 0, sizeof(ExternRefMapNode));
  4729. node->extern_obj = extern_obj;
  4730. node->module_inst = module_inst;
  4731. node->cleanup = NULL;
  4732. externref_idx = externref_global_id;
  4733. if (!bh_hash_map_insert(externref_map, (void *)(uintptr_t)externref_idx,
  4734. (void *)node)) {
  4735. goto fail2;
  4736. }
  4737. externref_global_id++;
  4738. *p_externref_idx = externref_idx;
  4739. os_mutex_unlock(&externref_lock);
  4740. return true;
  4741. fail2:
  4742. wasm_runtime_free(node);
  4743. fail1:
  4744. os_mutex_unlock(&externref_lock);
  4745. return false;
  4746. }
  4747. bool
  4748. wasm_externref_ref2obj(uint32 externref_idx, void **p_extern_obj)
  4749. {
  4750. ExternRefMapNode *node;
  4751. /* catch a `ref.null` vairable */
  4752. if (externref_idx == NULL_REF) {
  4753. *p_extern_obj = NULL;
  4754. return true;
  4755. }
  4756. os_mutex_lock(&externref_lock);
  4757. node = bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4758. os_mutex_unlock(&externref_lock);
  4759. if (!node)
  4760. return false;
  4761. *p_extern_obj = node->extern_obj;
  4762. return true;
  4763. }
  4764. static void
  4765. reclaim_extobj_callback(void *key, void *value, void *user_data)
  4766. {
  4767. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4768. WASMModuleInstanceCommon *module_inst =
  4769. (WASMModuleInstanceCommon *)user_data;
  4770. if (node->module_inst == module_inst) {
  4771. if (!node->marked && !node->retained) {
  4772. delete_externref(key, node);
  4773. }
  4774. else {
  4775. node->marked = false;
  4776. }
  4777. }
  4778. }
  4779. static void
  4780. mark_externref(uint32 externref_idx)
  4781. {
  4782. ExternRefMapNode *node;
  4783. if (externref_idx != NULL_REF) {
  4784. node =
  4785. bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4786. if (node) {
  4787. node->marked = true;
  4788. }
  4789. }
  4790. }
  4791. #if WASM_ENABLE_INTERP != 0
  4792. static void
  4793. interp_mark_all_externrefs(WASMModuleInstance *module_inst)
  4794. {
  4795. uint32 i, j, externref_idx;
  4796. table_elem_type_t *table_data;
  4797. uint8 *global_data = module_inst->global_data;
  4798. WASMGlobalInstance *global;
  4799. WASMTableInstance *table;
  4800. global = module_inst->e->globals;
  4801. for (i = 0; i < module_inst->e->global_count; i++, global++) {
  4802. if (global->type == VALUE_TYPE_EXTERNREF) {
  4803. externref_idx = *(uint32 *)(global_data + global->data_offset);
  4804. mark_externref(externref_idx);
  4805. }
  4806. }
  4807. for (i = 0; i < module_inst->table_count; i++) {
  4808. uint8 elem_type = 0;
  4809. uint32 init_size, max_size;
  4810. table = wasm_get_table_inst(module_inst, i);
  4811. (void)wasm_runtime_get_table_inst_elem_type(
  4812. (WASMModuleInstanceCommon *)module_inst, i, &elem_type, &init_size,
  4813. &max_size);
  4814. if (elem_type == VALUE_TYPE_EXTERNREF) {
  4815. table_data = table->elems;
  4816. for (j = 0; j < table->cur_size; j++) {
  4817. externref_idx = table_data[j];
  4818. mark_externref(externref_idx);
  4819. }
  4820. }
  4821. (void)init_size;
  4822. (void)max_size;
  4823. }
  4824. }
  4825. #endif
  4826. #if WASM_ENABLE_AOT != 0
  4827. static void
  4828. aot_mark_all_externrefs(AOTModuleInstance *module_inst)
  4829. {
  4830. uint32 i = 0, j = 0;
  4831. const AOTModule *module = (AOTModule *)module_inst->module;
  4832. const AOTTable *table = module->tables;
  4833. const AOTGlobal *global = module->globals;
  4834. const AOTTableInstance *table_inst;
  4835. for (i = 0; i < module->global_count; i++, global++) {
  4836. if (global->type == VALUE_TYPE_EXTERNREF) {
  4837. mark_externref(
  4838. *(uint32 *)(module_inst->global_data + global->data_offset));
  4839. }
  4840. }
  4841. for (i = 0; i < module->table_count; i++) {
  4842. table_inst = module_inst->tables[i];
  4843. if ((table + i)->elem_type == VALUE_TYPE_EXTERNREF) {
  4844. while (j < table_inst->cur_size) {
  4845. mark_externref(table_inst->elems[j++]);
  4846. }
  4847. }
  4848. }
  4849. }
  4850. #endif
  4851. void
  4852. wasm_externref_reclaim(WASMModuleInstanceCommon *module_inst)
  4853. {
  4854. os_mutex_lock(&externref_lock);
  4855. #if WASM_ENABLE_INTERP != 0
  4856. if (module_inst->module_type == Wasm_Module_Bytecode)
  4857. interp_mark_all_externrefs((WASMModuleInstance *)module_inst);
  4858. #endif
  4859. #if WASM_ENABLE_AOT != 0
  4860. if (module_inst->module_type == Wasm_Module_AoT)
  4861. aot_mark_all_externrefs((AOTModuleInstance *)module_inst);
  4862. #endif
  4863. bh_hash_map_traverse(externref_map, reclaim_extobj_callback,
  4864. (void *)module_inst);
  4865. os_mutex_unlock(&externref_lock);
  4866. }
  4867. static void
  4868. cleanup_extobj_callback(void *key, void *value, void *user_data)
  4869. {
  4870. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4871. WASMModuleInstanceCommon *module_inst =
  4872. (WASMModuleInstanceCommon *)user_data;
  4873. if (node->module_inst == module_inst) {
  4874. delete_externref(key, node);
  4875. }
  4876. }
  4877. void
  4878. wasm_externref_cleanup(WASMModuleInstanceCommon *module_inst)
  4879. {
  4880. os_mutex_lock(&externref_lock);
  4881. bh_hash_map_traverse(externref_map, cleanup_extobj_callback,
  4882. (void *)module_inst);
  4883. os_mutex_unlock(&externref_lock);
  4884. }
  4885. bool
  4886. wasm_externref_retain(uint32 externref_idx)
  4887. {
  4888. ExternRefMapNode *node;
  4889. os_mutex_lock(&externref_lock);
  4890. if (externref_idx != NULL_REF) {
  4891. node =
  4892. bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4893. if (node) {
  4894. node->retained = true;
  4895. os_mutex_unlock(&externref_lock);
  4896. return true;
  4897. }
  4898. }
  4899. os_mutex_unlock(&externref_lock);
  4900. return false;
  4901. }
  4902. #endif /* end of WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0 */
  4903. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  4904. uint32
  4905. wasm_runtime_dump_line_buf_impl(const char *line_buf, bool dump_or_print,
  4906. char **buf, uint32 *len)
  4907. {
  4908. if (dump_or_print) {
  4909. return (uint32)os_printf("%s", line_buf);
  4910. }
  4911. else if (*buf) {
  4912. uint32 dump_len;
  4913. dump_len = snprintf(*buf, *len, "%s", line_buf);
  4914. if (dump_len >= *len) {
  4915. dump_len = *len;
  4916. }
  4917. *len = *len - dump_len;
  4918. *buf = *buf + dump_len;
  4919. return dump_len;
  4920. }
  4921. else {
  4922. return (uint32)strlen(line_buf);
  4923. }
  4924. }
  4925. void
  4926. wasm_runtime_dump_call_stack(WASMExecEnv *exec_env)
  4927. {
  4928. WASMModuleInstanceCommon *module_inst =
  4929. wasm_exec_env_get_module_inst(exec_env);
  4930. #if WASM_ENABLE_INTERP != 0
  4931. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4932. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  4933. }
  4934. #endif
  4935. #if WASM_ENABLE_AOT != 0
  4936. if (module_inst->module_type == Wasm_Module_AoT) {
  4937. aot_dump_call_stack(exec_env, true, NULL, 0);
  4938. }
  4939. #endif
  4940. }
  4941. uint32
  4942. wasm_runtime_get_call_stack_buf_size(wasm_exec_env_t exec_env)
  4943. {
  4944. WASMModuleInstanceCommon *module_inst =
  4945. wasm_exec_env_get_module_inst(exec_env);
  4946. #if WASM_ENABLE_INTERP != 0
  4947. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4948. return wasm_interp_dump_call_stack(exec_env, false, NULL, 0);
  4949. }
  4950. #endif
  4951. #if WASM_ENABLE_AOT != 0
  4952. if (module_inst->module_type == Wasm_Module_AoT) {
  4953. return aot_dump_call_stack(exec_env, false, NULL, 0);
  4954. }
  4955. #endif
  4956. return 0;
  4957. }
  4958. uint32
  4959. wasm_runtime_dump_call_stack_to_buf(wasm_exec_env_t exec_env, char *buf,
  4960. uint32 len)
  4961. {
  4962. WASMModuleInstanceCommon *module_inst =
  4963. wasm_exec_env_get_module_inst(exec_env);
  4964. #if WASM_ENABLE_INTERP != 0
  4965. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4966. return wasm_interp_dump_call_stack(exec_env, false, buf, len);
  4967. }
  4968. #endif
  4969. #if WASM_ENABLE_AOT != 0
  4970. if (module_inst->module_type == Wasm_Module_AoT) {
  4971. return aot_dump_call_stack(exec_env, false, buf, len);
  4972. }
  4973. #endif
  4974. return 0;
  4975. }
  4976. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  4977. #if WASM_ENABLE_STATIC_PGO != 0
  4978. uint32
  4979. wasm_runtime_get_pgo_prof_data_size(WASMModuleInstanceCommon *module_inst)
  4980. {
  4981. #if WASM_ENABLE_AOT != 0
  4982. if (module_inst->module_type == Wasm_Module_AoT) {
  4983. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  4984. return aot_get_pgo_prof_data_size(aot_inst);
  4985. }
  4986. #endif
  4987. return 0;
  4988. }
  4989. uint32
  4990. wasm_runtime_dump_pgo_prof_data_to_buf(WASMModuleInstanceCommon *module_inst,
  4991. char *buf, uint32 len)
  4992. {
  4993. #if WASM_ENABLE_AOT != 0
  4994. if (module_inst->module_type == Wasm_Module_AoT) {
  4995. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  4996. return aot_dump_pgo_prof_data_to_buf(aot_inst, buf, len);
  4997. }
  4998. #endif
  4999. return 0;
  5000. }
  5001. #endif /* end of WASM_ENABLE_STATIC_PGO != 0 */
  5002. bool
  5003. wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm,
  5004. uint32 table_idx, uint8 *out_elem_type,
  5005. #if WASM_ENABLE_GC != 0
  5006. WASMRefType **out_ref_type,
  5007. #endif
  5008. uint32 *out_min_size, uint32 *out_max_size)
  5009. {
  5010. #if WASM_ENABLE_INTERP != 0
  5011. if (module_comm->module_type == Wasm_Module_Bytecode) {
  5012. WASMModule *module = (WASMModule *)module_comm;
  5013. if (table_idx < module->import_table_count) {
  5014. WASMTableImport *import_table =
  5015. &((module->import_tables + table_idx)->u.table);
  5016. *out_elem_type = import_table->elem_type;
  5017. #if WASM_ENABLE_GC != 0
  5018. *out_ref_type = import_table->elem_ref_type;
  5019. #endif
  5020. *out_min_size = import_table->init_size;
  5021. *out_max_size = import_table->max_size;
  5022. }
  5023. else {
  5024. WASMTable *table =
  5025. module->tables + (table_idx - module->import_table_count);
  5026. *out_elem_type = table->elem_type;
  5027. #if WASM_ENABLE_GC != 0
  5028. *out_ref_type = table->elem_ref_type;
  5029. #endif
  5030. *out_min_size = table->init_size;
  5031. *out_max_size = table->max_size;
  5032. }
  5033. return true;
  5034. }
  5035. #endif
  5036. #if WASM_ENABLE_AOT != 0
  5037. if (module_comm->module_type == Wasm_Module_AoT) {
  5038. AOTModule *module = (AOTModule *)module_comm;
  5039. if (table_idx < module->import_table_count) {
  5040. AOTImportTable *import_table = module->import_tables + table_idx;
  5041. *out_elem_type = import_table->elem_type;
  5042. #if WASM_ENABLE_GC != 0
  5043. *out_ref_type = NULL; /* TODO */
  5044. #endif
  5045. *out_min_size = import_table->table_init_size;
  5046. *out_max_size = import_table->table_max_size;
  5047. }
  5048. else {
  5049. AOTTable *table =
  5050. module->tables + (table_idx - module->import_table_count);
  5051. *out_elem_type = table->elem_type;
  5052. #if WASM_ENABLE_GC != 0
  5053. *out_ref_type = NULL; /* TODO */
  5054. #endif
  5055. *out_min_size = table->table_init_size;
  5056. *out_max_size = table->table_max_size;
  5057. }
  5058. return true;
  5059. }
  5060. #endif
  5061. return false;
  5062. }
  5063. bool
  5064. wasm_runtime_get_table_inst_elem_type(
  5065. const WASMModuleInstanceCommon *module_inst_comm, uint32 table_idx,
  5066. uint8 *out_elem_type,
  5067. #if WASM_ENABLE_GC != 0
  5068. WASMRefType **out_ref_type,
  5069. #endif
  5070. uint32 *out_min_size, uint32 *out_max_size)
  5071. {
  5072. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  5073. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  5074. || module_inst_comm->module_type == Wasm_Module_AoT);
  5075. return wasm_runtime_get_table_elem_type(
  5076. (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type,
  5077. #if WASM_ENABLE_GC != 0
  5078. out_ref_type,
  5079. #endif
  5080. out_min_size, out_max_size);
  5081. }
  5082. bool
  5083. wasm_runtime_get_export_func_type(const WASMModuleCommon *module_comm,
  5084. const WASMExport *export, WASMFuncType **out)
  5085. {
  5086. #if WASM_ENABLE_INTERP != 0
  5087. if (module_comm->module_type == Wasm_Module_Bytecode) {
  5088. WASMModule *module = (WASMModule *)module_comm;
  5089. if (export->index < module->import_function_count) {
  5090. *out = module->import_functions[export->index].u.function.func_type;
  5091. }
  5092. else {
  5093. *out =
  5094. module->functions[export->index - module->import_function_count]
  5095. ->func_type;
  5096. }
  5097. return true;
  5098. }
  5099. #endif
  5100. #if WASM_ENABLE_AOT != 0
  5101. if (module_comm->module_type == Wasm_Module_AoT) {
  5102. AOTModule *module = (AOTModule *)module_comm;
  5103. if (export->index < module->import_func_count) {
  5104. *out = (WASMFuncType *)
  5105. module->types[module->import_funcs[export->index]
  5106. .func_type_index];
  5107. }
  5108. else {
  5109. *out = (WASMFuncType *)module
  5110. ->types[module->func_type_indexes
  5111. [export->index - module->import_func_count]];
  5112. }
  5113. return true;
  5114. }
  5115. #endif
  5116. return false;
  5117. }
  5118. bool
  5119. wasm_runtime_get_export_global_type(const WASMModuleCommon *module_comm,
  5120. const WASMExport *export,
  5121. uint8 *out_val_type, bool *out_mutability)
  5122. {
  5123. #if WASM_ENABLE_INTERP != 0
  5124. if (module_comm->module_type == Wasm_Module_Bytecode) {
  5125. WASMModule *module = (WASMModule *)module_comm;
  5126. if (export->index < module->import_global_count) {
  5127. WASMGlobalImport *import_global =
  5128. &((module->import_globals + export->index)->u.global);
  5129. *out_val_type = import_global->type;
  5130. *out_mutability = import_global->is_mutable;
  5131. }
  5132. else {
  5133. WASMGlobal *global =
  5134. module->globals + (export->index - module->import_global_count);
  5135. *out_val_type = global->type;
  5136. *out_mutability = global->is_mutable;
  5137. }
  5138. return true;
  5139. }
  5140. #endif
  5141. #if WASM_ENABLE_AOT != 0
  5142. if (module_comm->module_type == Wasm_Module_AoT) {
  5143. AOTModule *module = (AOTModule *)module_comm;
  5144. if (export->index < module->import_global_count) {
  5145. AOTImportGlobal *import_global =
  5146. module->import_globals + export->index;
  5147. *out_val_type = import_global->type;
  5148. *out_mutability = import_global->is_mutable;
  5149. }
  5150. else {
  5151. AOTGlobal *global =
  5152. module->globals + (export->index - module->import_global_count);
  5153. *out_val_type = global->type;
  5154. *out_mutability = global->is_mutable;
  5155. }
  5156. return true;
  5157. }
  5158. #endif
  5159. return false;
  5160. }
  5161. bool
  5162. wasm_runtime_get_export_memory_type(const WASMModuleCommon *module_comm,
  5163. const WASMExport *export,
  5164. uint32 *out_min_page, uint32 *out_max_page)
  5165. {
  5166. #if WASM_ENABLE_INTERP != 0
  5167. if (module_comm->module_type == Wasm_Module_Bytecode) {
  5168. WASMModule *module = (WASMModule *)module_comm;
  5169. if (export->index < module->import_memory_count) {
  5170. WASMMemoryImport *import_memory =
  5171. &((module->import_memories + export->index)->u.memory);
  5172. *out_min_page = import_memory->init_page_count;
  5173. *out_max_page = import_memory->max_page_count;
  5174. }
  5175. else {
  5176. WASMMemory *memory =
  5177. module->memories
  5178. + (export->index - module->import_memory_count);
  5179. *out_min_page = memory->init_page_count;
  5180. *out_max_page = memory->max_page_count;
  5181. }
  5182. return true;
  5183. }
  5184. #endif
  5185. #if WASM_ENABLE_AOT != 0
  5186. if (module_comm->module_type == Wasm_Module_AoT) {
  5187. AOTModule *module = (AOTModule *)module_comm;
  5188. if (export->index < module->import_memory_count) {
  5189. AOTImportMemory *import_memory =
  5190. module->import_memories + export->index;
  5191. *out_min_page = import_memory->mem_init_page_count;
  5192. *out_max_page = import_memory->mem_max_page_count;
  5193. }
  5194. else {
  5195. AOTMemory *memory = module->memories
  5196. + (export->index - module->import_memory_count);
  5197. *out_min_page = memory->mem_init_page_count;
  5198. *out_max_page = memory->mem_max_page_count;
  5199. }
  5200. return true;
  5201. }
  5202. #endif
  5203. return false;
  5204. }
  5205. bool
  5206. wasm_runtime_get_export_table_type(const WASMModuleCommon *module_comm,
  5207. const WASMExport *export,
  5208. uint8 *out_elem_type,
  5209. #if WASM_ENABLE_GC != 0
  5210. WASMRefType **out_ref_type,
  5211. #endif
  5212. uint32 *out_min_size, uint32 *out_max_size)
  5213. {
  5214. return wasm_runtime_get_table_elem_type(module_comm, export->index,
  5215. out_elem_type,
  5216. #if WASM_ENABLE_GC != 0
  5217. out_ref_type,
  5218. #endif
  5219. out_min_size, out_max_size);
  5220. }
  5221. static inline bool
  5222. argv_to_params(wasm_val_t *out_params, const uint32 *argv,
  5223. WASMFuncType *func_type)
  5224. {
  5225. wasm_val_t *param = out_params;
  5226. uint32 i = 0, *u32;
  5227. for (i = 0; i < func_type->param_count; i++, param++) {
  5228. switch (func_type->types[i]) {
  5229. case VALUE_TYPE_I32:
  5230. param->kind = WASM_I32;
  5231. param->of.i32 = *argv++;
  5232. break;
  5233. case VALUE_TYPE_I64:
  5234. param->kind = WASM_I64;
  5235. u32 = (uint32 *)&param->of.i64;
  5236. u32[0] = *argv++;
  5237. u32[1] = *argv++;
  5238. break;
  5239. case VALUE_TYPE_F32:
  5240. param->kind = WASM_F32;
  5241. param->of.f32 = *(float32 *)argv++;
  5242. break;
  5243. case VALUE_TYPE_F64:
  5244. param->kind = WASM_F64;
  5245. u32 = (uint32 *)&param->of.i64;
  5246. u32[0] = *argv++;
  5247. u32[1] = *argv++;
  5248. break;
  5249. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  5250. case VALUE_TYPE_EXTERNREF:
  5251. param->kind = WASM_ANYREF;
  5252. if (!wasm_externref_ref2obj(*argv,
  5253. (void **)&param->of.foreign)) {
  5254. return false;
  5255. }
  5256. argv++;
  5257. break;
  5258. #endif
  5259. default:
  5260. return false;
  5261. }
  5262. }
  5263. return true;
  5264. }
  5265. static inline bool
  5266. results_to_argv(WASMModuleInstanceCommon *module_inst, uint32 *out_argv,
  5267. const wasm_val_t *results, WASMFuncType *func_type)
  5268. {
  5269. const wasm_val_t *result = results;
  5270. uint32 *argv = out_argv, *u32, i;
  5271. uint8 *result_types = func_type->types + func_type->param_count;
  5272. for (i = 0; i < func_type->result_count; i++, result++) {
  5273. switch (result_types[i]) {
  5274. case VALUE_TYPE_I32:
  5275. case VALUE_TYPE_F32:
  5276. *(int32 *)argv++ = result->of.i32;
  5277. break;
  5278. case VALUE_TYPE_I64:
  5279. case VALUE_TYPE_F64:
  5280. u32 = (uint32 *)&result->of.i64;
  5281. *argv++ = u32[0];
  5282. *argv++ = u32[1];
  5283. break;
  5284. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  5285. case VALUE_TYPE_EXTERNREF:
  5286. if (!wasm_externref_obj2ref(module_inst,
  5287. (void *)result->of.foreign,
  5288. (uint32 *)argv)) {
  5289. return false;
  5290. }
  5291. argv++;
  5292. break;
  5293. #endif
  5294. default:
  5295. return false;
  5296. }
  5297. }
  5298. return true;
  5299. }
  5300. bool
  5301. wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst,
  5302. void *func_ptr, WASMFuncType *func_type,
  5303. uint32 argc, uint32 *argv, bool with_env,
  5304. void *wasm_c_api_env)
  5305. {
  5306. wasm_val_t params_buf[16] = { 0 }, results_buf[4] = { 0 };
  5307. wasm_val_t *params = params_buf, *results = results_buf;
  5308. wasm_trap_t *trap = NULL;
  5309. bool ret = false;
  5310. wasm_val_vec_t params_vec = { 0 }, results_vec = { 0 };
  5311. if (func_type->param_count > 16) {
  5312. if (!(params =
  5313. runtime_malloc(sizeof(wasm_val_t) * func_type->param_count,
  5314. module_inst, NULL, 0))) {
  5315. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  5316. return false;
  5317. }
  5318. }
  5319. if (!argv_to_params(params, argv, func_type)) {
  5320. wasm_runtime_set_exception(module_inst, "unsupported param type");
  5321. goto fail;
  5322. }
  5323. if (func_type->result_count > 4) {
  5324. if (!(results =
  5325. runtime_malloc(sizeof(wasm_val_t) * func_type->result_count,
  5326. module_inst, NULL, 0))) {
  5327. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  5328. goto fail;
  5329. }
  5330. }
  5331. params_vec.data = params;
  5332. params_vec.num_elems = func_type->param_count;
  5333. params_vec.size = func_type->param_count;
  5334. results_vec.data = results;
  5335. results_vec.num_elems = 0;
  5336. results_vec.size = func_type->result_count;
  5337. if (!with_env) {
  5338. wasm_func_callback_t callback = (wasm_func_callback_t)func_ptr;
  5339. trap = callback(&params_vec, &results_vec);
  5340. }
  5341. else {
  5342. wasm_func_callback_with_env_t callback =
  5343. (wasm_func_callback_with_env_t)func_ptr;
  5344. trap = callback(wasm_c_api_env, &params_vec, &results_vec);
  5345. }
  5346. if (trap) {
  5347. if (trap->message->data) {
  5348. /* since trap->message->data does not end with '\0' */
  5349. char trap_message[108] = { 0 };
  5350. uint32 max_size_to_copy = (uint32)sizeof(trap_message) - 1;
  5351. uint32 size_to_copy = (trap->message->size < max_size_to_copy)
  5352. ? (uint32)trap->message->size
  5353. : max_size_to_copy;
  5354. bh_memcpy_s(trap_message, (uint32)sizeof(trap_message),
  5355. trap->message->data, size_to_copy);
  5356. wasm_runtime_set_exception(module_inst, trap_message);
  5357. }
  5358. else {
  5359. wasm_runtime_set_exception(
  5360. module_inst, "native function throw unknown exception");
  5361. }
  5362. wasm_trap_delete(trap);
  5363. goto fail;
  5364. }
  5365. if (!results_to_argv(module_inst, argv, results, func_type)) {
  5366. wasm_runtime_set_exception(module_inst, "unsupported result type");
  5367. goto fail;
  5368. }
  5369. ret = true;
  5370. fail:
  5371. if (params != params_buf)
  5372. wasm_runtime_free(params);
  5373. if (results != results_buf)
  5374. wasm_runtime_free(results);
  5375. return ret;
  5376. }
  5377. bool
  5378. wasm_runtime_quick_invoke_c_api_native(WASMModuleInstanceCommon *inst_comm,
  5379. CApiFuncImport *c_api_import,
  5380. wasm_val_t *params, uint32 param_count,
  5381. wasm_val_t *results, uint32 result_count)
  5382. {
  5383. WASMModuleInstance *module_inst = (WASMModuleInstance *)inst_comm;
  5384. void *func_ptr = c_api_import->func_ptr_linked;
  5385. bool with_env_arg = c_api_import->with_env_arg, ret = true;
  5386. wasm_val_vec_t params_vec = { 0 }, results_vec = { 0 };
  5387. wasm_trap_t *trap = NULL;
  5388. params_vec.data = params;
  5389. params_vec.num_elems = param_count;
  5390. params_vec.size = param_count;
  5391. results_vec.data = results;
  5392. results_vec.num_elems = 0;
  5393. results_vec.size = result_count;
  5394. if (!func_ptr) {
  5395. wasm_set_exception_with_id(module_inst, EXCE_CALL_UNLINKED_IMPORT_FUNC);
  5396. ret = false;
  5397. goto fail;
  5398. }
  5399. if (!with_env_arg) {
  5400. wasm_func_callback_t callback = (wasm_func_callback_t)func_ptr;
  5401. trap = callback(&params_vec, &results_vec);
  5402. }
  5403. else {
  5404. void *wasm_c_api_env = c_api_import->env_arg;
  5405. wasm_func_callback_with_env_t callback =
  5406. (wasm_func_callback_with_env_t)func_ptr;
  5407. trap = callback(wasm_c_api_env, &params_vec, &results_vec);
  5408. }
  5409. if (trap) {
  5410. if (trap->message->data) {
  5411. /* since trap->message->data does not end with '\0' */
  5412. char trap_message[108] = { 0 };
  5413. uint32 max_size_to_copy = (uint32)sizeof(trap_message) - 1;
  5414. uint32 size_to_copy = (trap->message->size < max_size_to_copy)
  5415. ? (uint32)trap->message->size
  5416. : max_size_to_copy;
  5417. bh_memcpy_s(trap_message, (uint32)sizeof(trap_message),
  5418. trap->message->data, size_to_copy);
  5419. wasm_set_exception(module_inst, trap_message);
  5420. }
  5421. else {
  5422. wasm_set_exception(module_inst,
  5423. "native function throw unknown exception");
  5424. }
  5425. wasm_trap_delete(trap);
  5426. ret = false;
  5427. }
  5428. fail:
  5429. #ifdef OS_ENABLE_HW_BOUND_CHECK
  5430. if (!ret)
  5431. wasm_runtime_access_exce_check_guard_page();
  5432. #endif
  5433. return ret;
  5434. }
  5435. void
  5436. wasm_runtime_show_app_heap_corrupted_prompt()
  5437. {
  5438. LOG_ERROR("Error: app heap is corrupted, if the wasm file "
  5439. "is compiled by wasi-sdk-12.0 or higher version, "
  5440. "please add -Wl,--export=malloc -Wl,--export=free "
  5441. "to export malloc and free functions. If it is "
  5442. "compiled by asc, please add --exportRuntime to "
  5443. "export the runtime helpers.");
  5444. }
  5445. #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0
  5446. void
  5447. wasm_runtime_destroy_custom_sections(WASMCustomSection *section_list)
  5448. {
  5449. WASMCustomSection *section = section_list, *next;
  5450. while (section) {
  5451. next = section->next;
  5452. wasm_runtime_free(section);
  5453. section = next;
  5454. }
  5455. }
  5456. #endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION */
  5457. void
  5458. wasm_runtime_get_version(uint32_t *major, uint32_t *minor, uint32_t *patch)
  5459. {
  5460. *major = WAMR_VERSION_MAJOR;
  5461. *minor = WAMR_VERSION_MINOR;
  5462. *patch = WAMR_VERSION_PATCH;
  5463. }
  5464. bool
  5465. wasm_runtime_is_import_func_linked(const char *module_name,
  5466. const char *func_name)
  5467. {
  5468. return wasm_native_resolve_symbol(module_name, func_name, NULL, NULL, NULL,
  5469. NULL);
  5470. }
  5471. bool
  5472. wasm_runtime_is_import_global_linked(const char *module_name,
  5473. const char *global_name)
  5474. {
  5475. #if WASM_ENABLE_LIBC_BUILTIN != 0
  5476. WASMGlobalImport global = { 0 };
  5477. return wasm_native_lookup_libc_builtin_global(module_name, global_name,
  5478. &global);
  5479. #else
  5480. return false;
  5481. #endif
  5482. }
  5483. #if WASM_ENABLE_LIBC_WASI != 0 || WASM_ENABLE_MULTI_MODULE != 0
  5484. WASMExport *
  5485. loader_find_export(const WASMModuleCommon *module, const char *module_name,
  5486. const char *field_name, uint8 export_kind, char *error_buf,
  5487. uint32 error_buf_size)
  5488. {
  5489. WASMExport *exports = NULL, *result = NULL, *export;
  5490. uint32 export_count = 0, i;
  5491. #if WASM_ENABLE_AOT != 0
  5492. if (module->module_type == Wasm_Module_AoT) {
  5493. AOTModule *aot_module = (AOTModule *)module;
  5494. exports = (WASMExport *)aot_module->exports;
  5495. export_count = aot_module->export_count;
  5496. }
  5497. #endif
  5498. #if WASM_ENABLE_INTERP != 0
  5499. if (module->module_type == Wasm_Module_Bytecode) {
  5500. WASMModule *wasm_module = (WASMModule *)module;
  5501. exports = wasm_module->exports;
  5502. export_count = wasm_module->export_count;
  5503. }
  5504. #endif
  5505. for (i = 0, export = exports; i < export_count; ++i, ++export) {
  5506. if (export->kind == export_kind && !strcmp(field_name, export->name)) {
  5507. result = export;
  5508. goto exit;
  5509. }
  5510. }
  5511. if (i == export_count) {
  5512. LOG_DEBUG("can not find an export %d named %s in the module %s",
  5513. export_kind, field_name, module_name);
  5514. set_error_buf(error_buf, error_buf_size,
  5515. "unknown import or incompatible import type");
  5516. }
  5517. exit:
  5518. return result;
  5519. }
  5520. #endif
  5521. #if WASM_ENABLE_MULTI_MODULE != 0
  5522. WASMModuleCommon *
  5523. wasm_runtime_search_sub_module(const WASMModuleCommon *parent_module,
  5524. const char *sub_module_name)
  5525. {
  5526. WASMRegisteredModule *node = NULL;
  5527. #if WASM_ENABLE_AOT != 0
  5528. if (parent_module->module_type == Wasm_Module_AoT) {
  5529. node = bh_list_first_elem(
  5530. ((AOTModule *)parent_module)->import_module_list);
  5531. }
  5532. #endif
  5533. #if WASM_ENABLE_INTERP != 0
  5534. if (parent_module->module_type == Wasm_Module_Bytecode) {
  5535. node = bh_list_first_elem(
  5536. ((WASMModule *)parent_module)->import_module_list);
  5537. }
  5538. #endif
  5539. while (node && strcmp(sub_module_name, node->module_name)) {
  5540. node = bh_list_elem_next(node);
  5541. }
  5542. return node ? node->module : NULL;
  5543. }
  5544. bool
  5545. wasm_runtime_register_sub_module(const WASMModuleCommon *parent_module,
  5546. const char *sub_module_name,
  5547. WASMModuleCommon *sub_module)
  5548. {
  5549. /* register sub_module into its parent sub module list */
  5550. WASMRegisteredModule *node = NULL;
  5551. bh_list_status ret = BH_LIST_ERROR;
  5552. if (wasm_runtime_search_sub_module(parent_module, sub_module_name)) {
  5553. LOG_DEBUG("%s has been registered in its parent", sub_module_name);
  5554. return true;
  5555. }
  5556. node = loader_malloc(sizeof(WASMRegisteredModule), NULL, 0);
  5557. if (!node) {
  5558. return false;
  5559. }
  5560. node->module_name = sub_module_name;
  5561. node->module = sub_module;
  5562. #if WASM_ENABLE_AOT != 0
  5563. if (parent_module->module_type == Wasm_Module_AoT) {
  5564. ret = bh_list_insert(((AOTModule *)parent_module)->import_module_list,
  5565. node);
  5566. }
  5567. #endif
  5568. #if WASM_ENABLE_INTERP != 0
  5569. if (parent_module->module_type == Wasm_Module_Bytecode) {
  5570. ret = bh_list_insert(((WASMModule *)parent_module)->import_module_list,
  5571. node);
  5572. }
  5573. #endif
  5574. bh_assert(BH_LIST_SUCCESS == ret);
  5575. (void)ret;
  5576. return true;
  5577. }
  5578. WASMModuleCommon *
  5579. wasm_runtime_load_depended_module(const WASMModuleCommon *parent_module,
  5580. const char *sub_module_name, char *error_buf,
  5581. uint32 error_buf_size)
  5582. {
  5583. WASMModuleCommon *sub_module = NULL;
  5584. bool ret = false;
  5585. uint8 *buffer = NULL;
  5586. uint32 buffer_size = 0;
  5587. /* check the registered module list of the parent */
  5588. sub_module = wasm_runtime_search_sub_module(parent_module, sub_module_name);
  5589. if (sub_module) {
  5590. LOG_DEBUG("%s has been loaded before", sub_module_name);
  5591. return sub_module;
  5592. }
  5593. /* check the global registered module list */
  5594. sub_module = wasm_runtime_find_module_registered(sub_module_name);
  5595. if (sub_module) {
  5596. LOG_DEBUG("%s has been loaded", sub_module_name);
  5597. goto wasm_runtime_register_sub_module;
  5598. }
  5599. LOG_VERBOSE("loading %s", sub_module_name);
  5600. if (!reader) {
  5601. set_error_buf_v(parent_module, error_buf, error_buf_size,
  5602. "no sub module reader to load %s", sub_module_name);
  5603. return NULL;
  5604. }
  5605. /* start to maintain a loading module list */
  5606. ret = wasm_runtime_is_loading_module(sub_module_name);
  5607. if (ret) {
  5608. set_error_buf_v(parent_module, error_buf, error_buf_size,
  5609. "found circular dependency on %s", sub_module_name);
  5610. return NULL;
  5611. }
  5612. ret = wasm_runtime_add_loading_module(sub_module_name, error_buf,
  5613. error_buf_size);
  5614. if (!ret) {
  5615. LOG_DEBUG("can not add %s into loading module list\n", sub_module_name);
  5616. return NULL;
  5617. }
  5618. ret = reader(parent_module->module_type, sub_module_name, &buffer,
  5619. &buffer_size);
  5620. if (!ret) {
  5621. LOG_DEBUG("read the file of %s failed", sub_module_name);
  5622. set_error_buf_v(parent_module, error_buf, error_buf_size,
  5623. "unknown import", sub_module_name);
  5624. goto delete_loading_module;
  5625. }
  5626. if (get_package_type(buffer, buffer_size) != parent_module->module_type) {
  5627. LOG_DEBUG("moudle %s type error", sub_module_name);
  5628. goto delete_loading_module;
  5629. }
  5630. if (get_package_type(buffer, buffer_size) == Wasm_Module_Bytecode) {
  5631. #if WASM_ENABLE_INTERP != 0
  5632. sub_module = (WASMModuleCommon *)wasm_load(buffer, buffer_size, false,
  5633. error_buf, error_buf_size);
  5634. #endif
  5635. }
  5636. else if (get_package_type(buffer, buffer_size) == Wasm_Module_AoT) {
  5637. #if WASM_ENABLE_AOT != 0
  5638. sub_module = (WASMModuleCommon *)aot_load_from_aot_file(
  5639. buffer, buffer_size, error_buf, error_buf_size);
  5640. #endif
  5641. }
  5642. if (!sub_module) {
  5643. LOG_DEBUG("error: can not load the sub_module %s", sub_module_name);
  5644. /* others will be destroyed in runtime_destroy() */
  5645. goto destroy_file_buffer;
  5646. }
  5647. wasm_runtime_delete_loading_module(sub_module_name);
  5648. /* register on a global list */
  5649. ret = wasm_runtime_register_module_internal(
  5650. sub_module_name, (WASMModuleCommon *)sub_module, buffer, buffer_size,
  5651. error_buf, error_buf_size);
  5652. if (!ret) {
  5653. LOG_DEBUG("error: can not register module %s globally\n",
  5654. sub_module_name);
  5655. /* others will be unloaded in runtime_destroy() */
  5656. goto unload_module;
  5657. }
  5658. /* register into its parent list */
  5659. wasm_runtime_register_sub_module:
  5660. ret = wasm_runtime_register_sub_module(parent_module, sub_module_name,
  5661. sub_module);
  5662. if (!ret) {
  5663. set_error_buf_v(parent_module, error_buf, error_buf_size,
  5664. "failed to register sub module %s", sub_module_name);
  5665. /* since it is in the global module list, no need to
  5666. * unload the module. the runtime_destroy() will do it
  5667. */
  5668. return NULL;
  5669. }
  5670. return sub_module;
  5671. unload_module:
  5672. wasm_runtime_unload(sub_module);
  5673. destroy_file_buffer:
  5674. if (destroyer) {
  5675. destroyer(buffer, buffer_size);
  5676. }
  5677. else {
  5678. LOG_WARNING("need to release the reading buffer of %s manually",
  5679. sub_module_name);
  5680. }
  5681. delete_loading_module:
  5682. wasm_runtime_delete_loading_module(sub_module_name);
  5683. return NULL;
  5684. }
  5685. bool
  5686. wasm_runtime_sub_module_instantiate(WASMModuleCommon *module,
  5687. WASMModuleInstanceCommon *module_inst,
  5688. uint32 stack_size, uint32 heap_size,
  5689. char *error_buf, uint32 error_buf_size)
  5690. {
  5691. bh_list *sub_module_inst_list = NULL;
  5692. WASMRegisteredModule *sub_module_list_node = NULL;
  5693. #if WASM_ENABLE_AOT != 0
  5694. if (module->module_type == Wasm_Module_AoT) {
  5695. sub_module_inst_list =
  5696. ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e)
  5697. ->sub_module_inst_list;
  5698. sub_module_list_node =
  5699. bh_list_first_elem(((AOTModule *)module)->import_module_list);
  5700. }
  5701. #endif
  5702. #if WASM_ENABLE_INTERP != 0
  5703. if (module->module_type == Wasm_Module_Bytecode) {
  5704. sub_module_inst_list =
  5705. ((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)->e)
  5706. ->sub_module_inst_list;
  5707. sub_module_list_node =
  5708. bh_list_first_elem(((WASMModule *)module)->import_module_list);
  5709. }
  5710. #endif
  5711. while (sub_module_list_node) {
  5712. WASMSubModInstNode *sub_module_inst_list_node = NULL;
  5713. WASMModuleCommon *sub_module = sub_module_list_node->module;
  5714. WASMModuleInstanceCommon *sub_module_inst = NULL;
  5715. sub_module_inst = wasm_runtime_instantiate_internal(
  5716. sub_module, NULL, NULL, stack_size, heap_size, error_buf,
  5717. error_buf_size);
  5718. if (!sub_module_inst) {
  5719. LOG_DEBUG("instantiate %s failed",
  5720. sub_module_list_node->module_name);
  5721. return false;
  5722. }
  5723. sub_module_inst_list_node = loader_malloc(sizeof(WASMSubModInstNode),
  5724. error_buf, error_buf_size);
  5725. if (!sub_module_inst_list_node) {
  5726. LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d",
  5727. sizeof(WASMSubModInstNode));
  5728. if (sub_module_inst)
  5729. wasm_runtime_deinstantiate_internal(sub_module_inst, false);
  5730. return false;
  5731. }
  5732. sub_module_inst_list_node->module_inst =
  5733. (WASMModuleInstance *)sub_module_inst;
  5734. sub_module_inst_list_node->module_name =
  5735. sub_module_list_node->module_name;
  5736. bh_list_status ret =
  5737. bh_list_insert(sub_module_inst_list, sub_module_inst_list_node);
  5738. bh_assert(BH_LIST_SUCCESS == ret);
  5739. (void)ret;
  5740. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  5741. }
  5742. return true;
  5743. }
  5744. void
  5745. wasm_runtime_sub_module_deinstantiate(WASMModuleInstanceCommon *module_inst)
  5746. {
  5747. bh_list *list = NULL;
  5748. #if WASM_ENABLE_AOT != 0
  5749. if (module_inst->module_type == Wasm_Module_AoT) {
  5750. list = ((AOTModuleInstanceExtra *)((AOTModuleInstance *)module_inst)->e)
  5751. ->sub_module_inst_list;
  5752. }
  5753. #endif
  5754. #if WASM_ENABLE_INTERP != 0
  5755. if (module_inst->module_type == Wasm_Module_Bytecode) {
  5756. list =
  5757. ((WASMModuleInstanceExtra *)((WASMModuleInstance *)module_inst)->e)
  5758. ->sub_module_inst_list;
  5759. }
  5760. #endif
  5761. WASMSubModInstNode *node = bh_list_first_elem(list);
  5762. while (node) {
  5763. WASMSubModInstNode *next_node = bh_list_elem_next(node);
  5764. bh_list_remove(list, node);
  5765. wasm_runtime_deinstantiate_internal(
  5766. (WASMModuleInstanceCommon *)node->module_inst, false);
  5767. wasm_runtime_free(node);
  5768. node = next_node;
  5769. }
  5770. }
  5771. #endif /* end of WASM_ENABLE_MULTI_MODULE */
  5772. #if WASM_ENABLE_MODULE_INST_CONTEXT != 0
  5773. void *
  5774. wasm_runtime_create_context_key(void (*dtor)(WASMModuleInstanceCommon *inst,
  5775. void *ctx))
  5776. {
  5777. return wasm_native_create_context_key(dtor);
  5778. }
  5779. void
  5780. wasm_runtime_destroy_context_key(void *key)
  5781. {
  5782. wasm_native_destroy_context_key(key);
  5783. }
  5784. void
  5785. wasm_runtime_set_context(WASMModuleInstanceCommon *inst, void *key, void *ctx)
  5786. {
  5787. wasm_native_set_context(inst, key, ctx);
  5788. }
  5789. void
  5790. wasm_runtime_set_context_spread(WASMModuleInstanceCommon *inst, void *key,
  5791. void *ctx)
  5792. {
  5793. wasm_native_set_context_spread(inst, key, ctx);
  5794. }
  5795. void *
  5796. wasm_runtime_get_context(WASMModuleInstanceCommon *inst, void *key)
  5797. {
  5798. return wasm_native_get_context(inst, key);
  5799. }
  5800. #endif /* WASM_ENABLE_MODULE_INST_CONTEXT != 0 */
  5801. #if WASM_ENABLE_LINUX_PERF != 0
  5802. static bool enable_linux_perf = false;
  5803. bool
  5804. wasm_runtime_get_linux_perf(void)
  5805. {
  5806. return enable_linux_perf;
  5807. }
  5808. void
  5809. wasm_runtime_set_linux_perf(bool flag)
  5810. {
  5811. enable_linux_perf = flag;
  5812. }
  5813. #endif