wasm_runtime_common.c 193 KB

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