wasm_runtime_common.c 195 KB

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