wasm_runtime_common.c 196 KB

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