wasm_runtime_common.c 232 KB

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