wasm_runtime_common.c 198 KB

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