wasm_runtime_common.c 170 KB

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