wasm_runtime_common.c 193 KB

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