wasm_runtime.c 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "wasm_runtime.h"
  6. #include "wasm.h"
  7. #include "wasm_loader.h"
  8. #include "wasm_interp.h"
  9. #include "bh_common.h"
  10. #include "bh_log.h"
  11. #include "mem_alloc.h"
  12. #include "../common/wasm_runtime_common.h"
  13. #include "../common/wasm_memory.h"
  14. #if WASM_ENABLE_GC != 0
  15. #include "../common/gc/gc_object.h"
  16. #endif
  17. #if WASM_ENABLE_SHARED_MEMORY != 0
  18. #include "../common/wasm_shared_memory.h"
  19. #endif
  20. #if WASM_ENABLE_THREAD_MGR != 0
  21. #include "../libraries/thread-mgr/thread_manager.h"
  22. #endif
  23. #if WASM_ENABLE_DEBUG_INTERP != 0
  24. #include "../libraries/debug-engine/debug_engine.h"
  25. #endif
  26. #if WASM_ENABLE_FAST_JIT != 0
  27. #include "../fast-jit/jit_compiler.h"
  28. #endif
  29. #if WASM_ENABLE_JIT != 0
  30. #include "../aot/aot_runtime.h"
  31. #endif
  32. static void
  33. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  34. {
  35. if (error_buf != NULL) {
  36. snprintf(error_buf, error_buf_size,
  37. "WASM module instantiate failed: %s", string);
  38. }
  39. }
  40. static void
  41. set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...)
  42. {
  43. va_list args;
  44. char buf[128];
  45. if (error_buf != NULL) {
  46. va_start(args, format);
  47. vsnprintf(buf, sizeof(buf), format, args);
  48. va_end(args);
  49. snprintf(error_buf, error_buf_size,
  50. "WASM module instantiate failed: %s", buf);
  51. }
  52. }
  53. WASMModule *
  54. wasm_load(uint8 *buf, uint32 size,
  55. #if WASM_ENABLE_MULTI_MODULE != 0
  56. bool main_module,
  57. #endif
  58. const LoadArgs *name, char *error_buf, uint32 error_buf_size)
  59. {
  60. return wasm_loader_load(buf, size,
  61. #if WASM_ENABLE_MULTI_MODULE != 0
  62. main_module,
  63. #endif
  64. name, error_buf, error_buf_size);
  65. }
  66. WASMModule *
  67. wasm_load_from_sections(WASMSection *section_list, char *error_buf,
  68. uint32 error_buf_size)
  69. {
  70. return wasm_loader_load_from_sections(section_list, error_buf,
  71. error_buf_size);
  72. }
  73. void
  74. wasm_unload(WASMModule *module)
  75. {
  76. wasm_loader_unload(module);
  77. }
  78. bool
  79. wasm_resolve_symbols(WASMModule *module)
  80. {
  81. bool ret = true;
  82. uint32 idx;
  83. for (idx = 0; idx < module->import_function_count; ++idx) {
  84. WASMFunctionImport *import = &module->import_functions[idx].u.function;
  85. bool linked = import->func_ptr_linked;
  86. #if WASM_ENABLE_MULTI_MODULE != 0
  87. if (import->import_func_linked) {
  88. linked = true;
  89. }
  90. #endif
  91. if (!linked && !wasm_resolve_import_func(module, import)) {
  92. ret = false;
  93. }
  94. }
  95. return ret;
  96. }
  97. #if WASM_ENABLE_MULTI_MODULE != 0
  98. static WASMFunction *
  99. wasm_resolve_function(const char *module_name, const char *function_name,
  100. const WASMFuncType *expected_function_type,
  101. char *error_buf, uint32 error_buf_size)
  102. {
  103. WASMModuleCommon *module_reg;
  104. WASMFunction *function = NULL;
  105. WASMExport *export = NULL;
  106. WASMModule *module = NULL;
  107. WASMFuncType *target_function_type = NULL;
  108. module_reg = wasm_runtime_find_module_registered(module_name);
  109. if (!module_reg || module_reg->module_type != Wasm_Module_Bytecode) {
  110. LOG_DEBUG("can not find a module named %s for function %s", module_name,
  111. function_name);
  112. set_error_buf(error_buf, error_buf_size, "unknown import");
  113. return NULL;
  114. }
  115. module = (WASMModule *)module_reg;
  116. export = loader_find_export((WASMModuleCommon *)module, module_name,
  117. function_name, EXPORT_KIND_FUNC, error_buf,
  118. error_buf_size);
  119. if (!export) {
  120. return NULL;
  121. }
  122. /* resolve function type and function */
  123. if (export->index < module->import_function_count) {
  124. target_function_type =
  125. module->import_functions[export->index].u.function.func_type;
  126. function = module->import_functions[export->index]
  127. .u.function.import_func_linked;
  128. }
  129. else {
  130. target_function_type =
  131. module->functions[export->index - module->import_function_count]
  132. ->func_type;
  133. function =
  134. module->functions[export->index - module->import_function_count];
  135. }
  136. /* check function type */
  137. if (!wasm_type_equal((WASMType *)expected_function_type,
  138. (WASMType *)target_function_type, module->types,
  139. module->type_count)) {
  140. LOG_DEBUG("%s.%s failed the type check", module_name, function_name);
  141. set_error_buf(error_buf, error_buf_size, "incompatible import type");
  142. return NULL;
  143. }
  144. return function;
  145. }
  146. #endif
  147. bool
  148. wasm_resolve_import_func(const WASMModule *module, WASMFunctionImport *function)
  149. {
  150. #if WASM_ENABLE_MULTI_MODULE != 0
  151. char error_buf[128];
  152. WASMModule *sub_module = NULL;
  153. #endif
  154. function->func_ptr_linked = wasm_native_resolve_symbol(
  155. function->module_name, function->field_name, function->func_type,
  156. &function->signature, &function->attachment, &function->call_conv_raw);
  157. if (function->func_ptr_linked) {
  158. return true;
  159. }
  160. #if WASM_ENABLE_MULTI_MODULE != 0
  161. if (!wasm_runtime_is_built_in_module(function->module_name)) {
  162. sub_module = (WASMModule *)wasm_runtime_load_depended_module(
  163. (WASMModuleCommon *)module, function->module_name, error_buf,
  164. sizeof(error_buf));
  165. if (!sub_module) {
  166. LOG_WARNING("failed to load sub module: %s", error_buf);
  167. return false;
  168. }
  169. }
  170. function->import_func_linked = wasm_resolve_function(
  171. function->module_name, function->field_name, function->func_type,
  172. error_buf, sizeof(error_buf));
  173. if (function->import_func_linked) {
  174. function->import_module = sub_module;
  175. return true;
  176. }
  177. else {
  178. LOG_WARNING("failed to link function (%s, %s): %s",
  179. function->module_name, function->field_name, error_buf);
  180. }
  181. #endif
  182. return false;
  183. }
  184. static void *
  185. runtime_malloc(uint64 size, char *error_buf, uint32 error_buf_size)
  186. {
  187. void *mem;
  188. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  189. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  190. return NULL;
  191. }
  192. memset(mem, 0, (uint32)size);
  193. return mem;
  194. }
  195. #if WASM_ENABLE_MULTI_MODULE != 0
  196. static WASMModuleInstance *
  197. get_sub_module_inst(const WASMModuleInstance *parent_module_inst,
  198. const WASMModule *sub_module)
  199. {
  200. bh_list *sub_module_inst_list = parent_module_inst->e->sub_module_inst_list;
  201. WASMSubModInstNode *node = bh_list_first_elem(sub_module_inst_list);
  202. while (node && sub_module != node->module_inst->module) {
  203. node = bh_list_elem_next(node);
  204. }
  205. return node ? node->module_inst : NULL;
  206. }
  207. #endif
  208. /**
  209. * Destroy memory instances.
  210. */
  211. static void
  212. memories_deinstantiate(WASMModuleInstance *module_inst,
  213. WASMMemoryInstance **memories, uint32 count)
  214. {
  215. uint32 i;
  216. if (memories) {
  217. for (i = 0; i < count; i++) {
  218. if (memories[i]) {
  219. #if WASM_ENABLE_MULTI_MODULE != 0
  220. WASMModule *module = module_inst->module;
  221. if (i < module->import_memory_count
  222. && module->import_memories[i].u.memory.import_module) {
  223. continue;
  224. }
  225. #endif
  226. #if WASM_ENABLE_SHARED_MEMORY != 0
  227. if (shared_memory_is_shared(memories[i])) {
  228. uint32 ref_count = shared_memory_dec_reference(memories[i]);
  229. /* if the reference count is not zero,
  230. don't free the memory */
  231. if (ref_count > 0)
  232. continue;
  233. }
  234. #endif
  235. if (memories[i]->heap_handle) {
  236. mem_allocator_destroy(memories[i]->heap_handle);
  237. wasm_runtime_free(memories[i]->heap_handle);
  238. memories[i]->heap_handle = NULL;
  239. }
  240. if (memories[i]->memory_data) {
  241. wasm_deallocate_linear_memory(memories[i]);
  242. }
  243. }
  244. }
  245. wasm_runtime_free(memories);
  246. }
  247. (void)module_inst;
  248. }
  249. static WASMMemoryInstance *
  250. memory_instantiate(WASMModuleInstance *module_inst, WASMModuleInstance *parent,
  251. WASMMemoryInstance *memory, uint32 memory_idx,
  252. uint32 num_bytes_per_page, uint32 init_page_count,
  253. uint32 max_page_count, uint32 heap_size, uint32 flags,
  254. char *error_buf, uint32 error_buf_size)
  255. {
  256. WASMModule *module = module_inst->module;
  257. uint32 inc_page_count, global_idx, default_max_page;
  258. uint32 bytes_of_last_page, bytes_to_page_end;
  259. uint64 aux_heap_base,
  260. heap_offset = (uint64)num_bytes_per_page * init_page_count;
  261. uint64 memory_data_size, max_memory_data_size;
  262. uint8 *global_addr;
  263. bool is_shared_memory = false;
  264. #if WASM_ENABLE_SHARED_MEMORY != 0
  265. is_shared_memory = flags & SHARED_MEMORY_FLAG ? true : false;
  266. /* shared memory */
  267. if (is_shared_memory && parent != NULL) {
  268. bh_assert(parent->memory_count > memory_idx);
  269. memory = parent->memories[memory_idx];
  270. shared_memory_inc_reference(memory);
  271. return memory;
  272. }
  273. #else
  274. (void)parent;
  275. (void)memory_idx;
  276. (void)flags;
  277. #endif /* end of WASM_ENABLE_SHARED_MEMORY */
  278. #if WASM_ENABLE_MEMORY64 != 0
  279. if (flags & MEMORY64_FLAG) {
  280. memory->is_memory64 = 1;
  281. }
  282. #endif
  283. default_max_page =
  284. memory->is_memory64 ? DEFAULT_MEM64_MAX_PAGES : DEFAULT_MAX_PAGES;
  285. /* The app heap should be in the default memory */
  286. if (memory_idx == 0) {
  287. if (heap_size > 0 && module_inst->module->malloc_function != (uint32)-1
  288. && module_inst->module->free_function != (uint32)-1) {
  289. /* Disable app heap, use malloc/free function exported
  290. by wasm app to allocate/free memory instead */
  291. heap_size = 0;
  292. }
  293. /* If initial memory is the largest size allowed, disallowing insert
  294. * host managed heap */
  295. if (heap_size > 0
  296. && heap_offset == GET_MAX_LINEAR_MEMORY_SIZE(memory->is_memory64)) {
  297. set_error_buf(error_buf, error_buf_size,
  298. "failed to insert app heap into linear memory, "
  299. "try using `--heap-size=0` option");
  300. return NULL;
  301. }
  302. if (init_page_count == max_page_count && init_page_count == 1) {
  303. /* If only one page and at most one page, we just append
  304. the app heap to the end of linear memory, enlarge the
  305. num_bytes_per_page, and don't change the page count */
  306. if (heap_size > UINT32_MAX - num_bytes_per_page) {
  307. set_error_buf(error_buf, error_buf_size,
  308. "failed to insert app heap into linear memory, "
  309. "try using `--heap-size=0` option");
  310. return NULL;
  311. }
  312. heap_offset = num_bytes_per_page;
  313. num_bytes_per_page += heap_size;
  314. }
  315. else if (heap_size > 0) {
  316. if (init_page_count == max_page_count && init_page_count == 0) {
  317. /* If the memory data size is always 0, we resize it to
  318. one page for app heap */
  319. num_bytes_per_page = heap_size;
  320. heap_offset = 0;
  321. inc_page_count = 1;
  322. }
  323. else if (module->aux_heap_base_global_index != (uint32)-1
  324. && module->aux_heap_base
  325. < (uint64)num_bytes_per_page * init_page_count) {
  326. /* Insert app heap before __heap_base */
  327. aux_heap_base = module->aux_heap_base;
  328. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  329. if (bytes_of_last_page == 0)
  330. bytes_of_last_page = num_bytes_per_page;
  331. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  332. inc_page_count =
  333. (heap_size - bytes_to_page_end + num_bytes_per_page - 1)
  334. / num_bytes_per_page;
  335. heap_offset = aux_heap_base;
  336. aux_heap_base += heap_size;
  337. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  338. if (bytes_of_last_page == 0)
  339. bytes_of_last_page = num_bytes_per_page;
  340. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  341. if (bytes_to_page_end < 1 * BH_KB) {
  342. aux_heap_base += 1 * BH_KB;
  343. inc_page_count++;
  344. }
  345. /* Adjust __heap_base global value */
  346. global_idx = module->aux_heap_base_global_index;
  347. bh_assert(module_inst->e->globals
  348. && global_idx < module_inst->e->global_count);
  349. global_addr = module_inst->global_data
  350. + module_inst->e->globals[global_idx].data_offset;
  351. #if WASM_ENABLE_MEMORY64 != 0
  352. if (memory->is_memory64) {
  353. /* For memory64, the global value should be i64 */
  354. *(uint64 *)global_addr = aux_heap_base;
  355. }
  356. else
  357. #endif
  358. {
  359. /* For memory32, the global value should be i32 */
  360. *(uint32 *)global_addr = (uint32)aux_heap_base;
  361. }
  362. LOG_VERBOSE("Reset __heap_base global to %" PRIu64,
  363. aux_heap_base);
  364. }
  365. else {
  366. /* Insert app heap before new page */
  367. inc_page_count =
  368. (heap_size + num_bytes_per_page - 1) / num_bytes_per_page;
  369. heap_offset = (uint64)num_bytes_per_page * init_page_count;
  370. heap_size = (uint64)num_bytes_per_page * inc_page_count;
  371. if (heap_size > 0)
  372. heap_size -= 1 * BH_KB;
  373. }
  374. init_page_count += inc_page_count;
  375. max_page_count += inc_page_count;
  376. if (init_page_count > default_max_page) {
  377. set_error_buf(error_buf, error_buf_size,
  378. "failed to insert app heap into linear memory, "
  379. "try using `--heap-size=0` option");
  380. return NULL;
  381. }
  382. if (max_page_count > default_max_page)
  383. max_page_count = default_max_page;
  384. }
  385. }
  386. LOG_VERBOSE("Memory instantiate:");
  387. LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u",
  388. num_bytes_per_page, init_page_count, max_page_count);
  389. if (memory_idx == 0)
  390. LOG_VERBOSE(" heap offset: %" PRIu64 ", heap size: %u\n", heap_offset,
  391. heap_size);
  392. max_memory_data_size = (uint64)num_bytes_per_page * max_page_count;
  393. bh_assert(max_memory_data_size
  394. <= GET_MAX_LINEAR_MEMORY_SIZE(memory->is_memory64));
  395. (void)max_memory_data_size;
  396. bh_assert(memory != NULL);
  397. if (wasm_allocate_linear_memory(&memory->memory_data, is_shared_memory,
  398. memory->is_memory64, num_bytes_per_page,
  399. init_page_count, max_page_count,
  400. &memory_data_size)
  401. != BHT_OK) {
  402. set_error_buf(error_buf, error_buf_size,
  403. "allocate linear memory failed");
  404. return NULL;
  405. }
  406. memory->module_type = Wasm_Module_Bytecode;
  407. memory->num_bytes_per_page = num_bytes_per_page;
  408. memory->cur_page_count = init_page_count;
  409. memory->max_page_count = max_page_count;
  410. memory->memory_data_size = memory_data_size;
  411. if (memory_idx == 0) {
  412. memory->heap_data = memory->memory_data + heap_offset;
  413. memory->heap_data_end = memory->heap_data + heap_size;
  414. memory->memory_data_end = memory->memory_data + memory_data_size;
  415. }
  416. /* Initialize heap */
  417. if (memory_idx == 0 && heap_size > 0) {
  418. uint32 heap_struct_size = mem_allocator_get_heap_struct_size();
  419. if (!(memory->heap_handle = runtime_malloc(
  420. (uint64)heap_struct_size, error_buf, error_buf_size))) {
  421. goto fail1;
  422. }
  423. if (!mem_allocator_create_with_struct_and_pool(
  424. memory->heap_handle, heap_struct_size, memory->heap_data,
  425. heap_size)) {
  426. set_error_buf(error_buf, error_buf_size, "init app heap failed");
  427. goto fail2;
  428. }
  429. }
  430. if (memory_data_size > 0) {
  431. wasm_runtime_set_mem_bound_check_bytes(memory, memory_data_size);
  432. }
  433. #if WASM_ENABLE_SHARED_MEMORY != 0
  434. if (is_shared_memory) {
  435. memory->is_shared_memory = 1;
  436. memory->ref_count = 1;
  437. }
  438. #endif
  439. LOG_VERBOSE("Memory instantiate success.");
  440. return memory;
  441. fail2:
  442. if (memory_idx == 0 && heap_size > 0)
  443. wasm_runtime_free(memory->heap_handle);
  444. fail1:
  445. if (memory->memory_data)
  446. wasm_deallocate_linear_memory(memory);
  447. return NULL;
  448. }
  449. /**
  450. * Instantiate memories in a module.
  451. */
  452. static WASMMemoryInstance **
  453. memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  454. WASMModuleInstance *parent, uint32 heap_size,
  455. uint32 max_memory_pages, char *error_buf,
  456. uint32 error_buf_size)
  457. {
  458. WASMImport *import;
  459. uint32 mem_index = 0, i,
  460. memory_count = module->import_memory_count + module->memory_count;
  461. uint64 total_size;
  462. WASMMemoryInstance **memories, *memory;
  463. total_size = sizeof(WASMMemoryInstance *) * (uint64)memory_count;
  464. if (!(memories = runtime_malloc(total_size, error_buf, error_buf_size))) {
  465. return NULL;
  466. }
  467. memory = module_inst->global_table_data.memory_instances;
  468. /* instantiate memories from import section */
  469. import = module->import_memories;
  470. for (i = 0; i < module->import_memory_count; i++, import++, memory++) {
  471. uint32 num_bytes_per_page =
  472. import->u.memory.mem_type.num_bytes_per_page;
  473. uint32 init_page_count = import->u.memory.mem_type.init_page_count;
  474. uint32 max_page_count = wasm_runtime_get_max_mem(
  475. max_memory_pages, import->u.memory.mem_type.init_page_count,
  476. import->u.memory.mem_type.max_page_count);
  477. uint32 flags = import->u.memory.mem_type.flags;
  478. uint32 actual_heap_size = heap_size;
  479. #if WASM_ENABLE_MULTI_MODULE != 0
  480. if (import->u.memory.import_module != NULL) {
  481. WASMModuleInstance *module_inst_linked;
  482. if (!(module_inst_linked = get_sub_module_inst(
  483. module_inst, import->u.memory.import_module))) {
  484. set_error_buf(error_buf, error_buf_size, "unknown memory");
  485. memories_deinstantiate(module_inst, memories, memory_count);
  486. return NULL;
  487. }
  488. if (!(memories[mem_index++] = wasm_lookup_memory(
  489. module_inst_linked, import->u.memory.field_name))) {
  490. set_error_buf(error_buf, error_buf_size, "unknown memory");
  491. memories_deinstantiate(module_inst, memories, memory_count);
  492. return NULL;
  493. }
  494. }
  495. else
  496. #endif
  497. {
  498. if (!(memories[mem_index] = memory_instantiate(
  499. module_inst, parent, memory, mem_index,
  500. num_bytes_per_page, init_page_count, max_page_count,
  501. actual_heap_size, flags, error_buf, error_buf_size))) {
  502. memories_deinstantiate(module_inst, memories, memory_count);
  503. return NULL;
  504. }
  505. mem_index++;
  506. }
  507. }
  508. /* instantiate memories from memory section */
  509. for (i = 0; i < module->memory_count; i++, memory++) {
  510. uint32 max_page_count = wasm_runtime_get_max_mem(
  511. max_memory_pages, module->memories[i].init_page_count,
  512. module->memories[i].max_page_count);
  513. if (!(memories[mem_index] = memory_instantiate(
  514. module_inst, parent, memory, mem_index,
  515. module->memories[i].num_bytes_per_page,
  516. module->memories[i].init_page_count, max_page_count,
  517. heap_size, module->memories[i].flags, error_buf,
  518. error_buf_size))) {
  519. memories_deinstantiate(module_inst, memories, memory_count);
  520. return NULL;
  521. }
  522. mem_index++;
  523. }
  524. bh_assert(mem_index == memory_count);
  525. (void)module_inst;
  526. return memories;
  527. }
  528. /**
  529. * Destroy table instances.
  530. */
  531. static void
  532. tables_deinstantiate(WASMModuleInstance *module_inst)
  533. {
  534. if (module_inst->tables) {
  535. wasm_runtime_free(module_inst->tables);
  536. }
  537. #if WASM_ENABLE_MULTI_MODULE != 0
  538. if (module_inst->e->table_insts_linked) {
  539. wasm_runtime_free(module_inst->e->table_insts_linked);
  540. }
  541. #endif
  542. }
  543. /**
  544. * Instantiate tables in a module.
  545. */
  546. static WASMTableInstance **
  547. tables_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  548. WASMTableInstance *first_table, char *error_buf,
  549. uint32 error_buf_size)
  550. {
  551. WASMImport *import;
  552. uint32 table_index = 0, i;
  553. uint32 table_count = module->import_table_count + module->table_count;
  554. uint64 total_size = (uint64)sizeof(WASMTableInstance *) * table_count;
  555. WASMTableInstance **tables, *table = first_table;
  556. #if WASM_ENABLE_MULTI_MODULE != 0
  557. uint64 total_size_of_tables_linked =
  558. (uint64)sizeof(WASMTableInstance *) * module->import_table_count;
  559. WASMTableInstance **table_linked = NULL;
  560. #endif
  561. if (!(tables = runtime_malloc(total_size, error_buf, error_buf_size))) {
  562. return NULL;
  563. }
  564. #if WASM_ENABLE_MULTI_MODULE != 0
  565. if (module->import_table_count > 0
  566. && !(module_inst->e->table_insts_linked = table_linked = runtime_malloc(
  567. total_size_of_tables_linked, error_buf, error_buf_size))) {
  568. goto fail;
  569. }
  570. #endif
  571. /* instantiate tables from import section */
  572. import = module->import_tables;
  573. for (i = 0; i < module->import_table_count; i++, import++) {
  574. uint32 max_size_fixed = 0;
  575. #if WASM_ENABLE_MULTI_MODULE != 0
  576. WASMTableInstance *table_inst_linked = NULL;
  577. WASMModuleInstance *module_inst_linked = NULL;
  578. if (import->u.table.import_module) {
  579. if (!(module_inst_linked = get_sub_module_inst(
  580. module_inst, import->u.table.import_module))) {
  581. set_error_buf(error_buf, error_buf_size, "unknown table");
  582. goto fail;
  583. }
  584. if (!(table_inst_linked = wasm_lookup_table(
  585. module_inst_linked, import->u.table.field_name))) {
  586. set_error_buf(error_buf, error_buf_size, "unknown table");
  587. goto fail;
  588. }
  589. total_size = offsetof(WASMTableInstance, elems);
  590. }
  591. else
  592. #endif
  593. {
  594. /* in order to save memory, alloc resource as few as possible */
  595. max_size_fixed = import->u.table.table_type.possible_grow
  596. ? import->u.table.table_type.max_size
  597. : import->u.table.table_type.init_size;
  598. /* it is a built-in table, every module has its own */
  599. total_size = offsetof(WASMTableInstance, elems);
  600. /* store function indexes for non-gc, object pointers for gc */
  601. total_size += (uint64)sizeof(table_elem_type_t) * max_size_fixed;
  602. }
  603. tables[table_index++] = table;
  604. #if WASM_ENABLE_GC == 0
  605. /* Set all elements to -1 to mark them as uninitialized elements */
  606. memset(table, -1, (uint32)total_size);
  607. #else
  608. /* For GC, all elements have already been set to NULL_REF (0) as
  609. uninitialized elements */
  610. #endif
  611. table->is_table64 = import->u.table.table_type.flags & TABLE64_FLAG;
  612. #if WASM_ENABLE_MULTI_MODULE != 0
  613. *table_linked = table_inst_linked;
  614. if (table_inst_linked != NULL) {
  615. table->elem_type = table_inst_linked->elem_type;
  616. #if WASM_ENABLE_GC != 0
  617. table->elem_ref_type = table_inst_linked->elem_ref_type;
  618. #endif
  619. table->cur_size = table_inst_linked->cur_size;
  620. table->max_size = table_inst_linked->max_size;
  621. }
  622. else
  623. #endif
  624. {
  625. table->elem_type = import->u.table.table_type.elem_type;
  626. #if WASM_ENABLE_GC != 0
  627. table->elem_ref_type.elem_ref_type =
  628. import->u.table.table_type.elem_ref_type;
  629. #endif
  630. table->cur_size = import->u.table.table_type.init_size;
  631. table->max_size = max_size_fixed;
  632. }
  633. table = (WASMTableInstance *)((uint8 *)table + (uint32)total_size);
  634. #if WASM_ENABLE_MULTI_MODULE != 0
  635. table_linked++;
  636. #endif
  637. }
  638. /* instantiate tables from table section */
  639. for (i = 0; i < module->table_count; i++) {
  640. uint32 max_size_fixed = 0;
  641. total_size = offsetof(WASMTableInstance, elems);
  642. #if WASM_ENABLE_MULTI_MODULE != 0
  643. /* in case, a module which imports this table will grow it */
  644. max_size_fixed = module->tables[i].table_type.max_size;
  645. #else
  646. max_size_fixed = module->tables[i].table_type.possible_grow
  647. ? module->tables[i].table_type.max_size
  648. : module->tables[i].table_type.init_size;
  649. #endif
  650. #if WASM_ENABLE_GC == 0
  651. /* Store function indexes */
  652. total_size += sizeof(uintptr_t) * (uint64)max_size_fixed;
  653. #else
  654. /* Store object pointers */
  655. total_size += sizeof(uintptr_t) * (uint64)max_size_fixed;
  656. #endif
  657. tables[table_index++] = table;
  658. #if WASM_ENABLE_GC == 0
  659. /* Set all elements to -1 to mark them as uninitialized elements */
  660. memset(table, -1, (uint32)total_size);
  661. #else
  662. /* For GC, all elements have already been set to NULL_REF (0) as
  663. uninitialized elements */
  664. #endif
  665. table->is_table64 = module->tables[i].table_type.flags & TABLE64_FLAG;
  666. table->elem_type = module->tables[i].table_type.elem_type;
  667. #if WASM_ENABLE_GC != 0
  668. table->elem_ref_type.elem_ref_type =
  669. module->tables[i].table_type.elem_ref_type;
  670. #endif
  671. table->cur_size = module->tables[i].table_type.init_size;
  672. table->max_size = max_size_fixed;
  673. table = (WASMTableInstance *)((uint8 *)table + (uint32)total_size);
  674. }
  675. bh_assert(table_index == table_count);
  676. (void)module_inst;
  677. return tables;
  678. #if WASM_ENABLE_MULTI_MODULE != 0
  679. fail:
  680. wasm_runtime_free(tables);
  681. return NULL;
  682. #endif
  683. }
  684. /**
  685. * Destroy function instances.
  686. */
  687. static void
  688. functions_deinstantiate(WASMFunctionInstance *functions)
  689. {
  690. if (functions) {
  691. wasm_runtime_free(functions);
  692. }
  693. }
  694. /**
  695. * Instantiate functions in a module.
  696. */
  697. static WASMFunctionInstance *
  698. functions_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  699. char *error_buf, uint32 error_buf_size)
  700. {
  701. WASMImport *import;
  702. uint32 i,
  703. function_count = module->import_function_count + module->function_count;
  704. uint64 total_size = sizeof(WASMFunctionInstance) * (uint64)function_count;
  705. WASMFunctionInstance *functions, *function;
  706. if (!(functions = runtime_malloc(total_size, error_buf, error_buf_size))) {
  707. return NULL;
  708. }
  709. total_size = sizeof(void *) * (uint64)module->import_function_count;
  710. if (total_size > 0
  711. && !(module_inst->import_func_ptrs =
  712. runtime_malloc(total_size, error_buf, error_buf_size))) {
  713. wasm_runtime_free(functions);
  714. return NULL;
  715. }
  716. /* instantiate functions from import section */
  717. function = functions;
  718. import = module->import_functions;
  719. for (i = 0; i < module->import_function_count; i++, import++) {
  720. function->is_import_func = true;
  721. #if WASM_ENABLE_MULTI_MODULE != 0
  722. if (import->u.function.import_module) {
  723. function->import_module_inst = get_sub_module_inst(
  724. module_inst, import->u.function.import_module);
  725. if (function->import_module_inst) {
  726. function->import_func_inst =
  727. wasm_lookup_function(function->import_module_inst,
  728. import->u.function.field_name);
  729. }
  730. }
  731. #endif /* WASM_ENABLE_MULTI_MODULE */
  732. function->u.func_import = &import->u.function;
  733. function->param_cell_num = import->u.function.func_type->param_cell_num;
  734. function->ret_cell_num = import->u.function.func_type->ret_cell_num;
  735. function->param_count =
  736. (uint16)function->u.func_import->func_type->param_count;
  737. function->param_types = function->u.func_import->func_type->types;
  738. function->local_cell_num = 0;
  739. function->local_count = 0;
  740. function->local_types = NULL;
  741. /* Copy the function pointer to current instance */
  742. module_inst->import_func_ptrs[i] =
  743. function->u.func_import->func_ptr_linked;
  744. function++;
  745. }
  746. /* instantiate functions from function section */
  747. for (i = 0; i < module->function_count; i++) {
  748. function->is_import_func = false;
  749. function->u.func = module->functions[i];
  750. function->param_cell_num = function->u.func->param_cell_num;
  751. function->ret_cell_num = function->u.func->ret_cell_num;
  752. function->local_cell_num = function->u.func->local_cell_num;
  753. function->param_count =
  754. (uint16)function->u.func->func_type->param_count;
  755. function->local_count = (uint16)function->u.func->local_count;
  756. function->param_types = function->u.func->func_type->types;
  757. function->local_types = function->u.func->local_types;
  758. function->local_offsets = function->u.func->local_offsets;
  759. #if WASM_ENABLE_FAST_INTERP != 0
  760. function->const_cell_num = function->u.func->const_cell_num;
  761. #endif
  762. function++;
  763. }
  764. bh_assert((uint32)(function - functions) == function_count);
  765. #if WASM_ENABLE_FAST_JIT != 0
  766. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  767. #endif
  768. return functions;
  769. }
  770. #if WASM_ENABLE_TAGS != 0
  771. /**
  772. * Destroy tags instances.
  773. */
  774. static void
  775. tags_deinstantiate(WASMTagInstance *tags, void **import_tag_ptrs)
  776. {
  777. if (tags) {
  778. wasm_runtime_free(tags);
  779. }
  780. if (import_tag_ptrs) {
  781. wasm_runtime_free(import_tag_ptrs);
  782. }
  783. }
  784. /**
  785. * Instantiate tags in a module.
  786. */
  787. static WASMTagInstance *
  788. tags_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  789. char *error_buf, uint32 error_buf_size)
  790. {
  791. WASMImport *import;
  792. uint32 i, tag_count = module->import_tag_count + module->tag_count;
  793. uint64 total_size = sizeof(WASMTagInstance) * (uint64)tag_count;
  794. WASMTagInstance *tags, *tag;
  795. if (!(tags = runtime_malloc(total_size, error_buf, error_buf_size))) {
  796. return NULL;
  797. }
  798. total_size = sizeof(void *) * (uint64)module->import_tag_count;
  799. if (total_size > 0
  800. && !(module_inst->e->import_tag_ptrs =
  801. runtime_malloc(total_size, error_buf, error_buf_size))) {
  802. wasm_runtime_free(tags);
  803. return NULL;
  804. }
  805. /* instantiate tags from import section */
  806. tag = tags;
  807. import = module->import_tags;
  808. for (i = 0; i < module->import_tag_count; i++, import++) {
  809. tag->is_import_tag = true;
  810. tag->u.tag_import = &import->u.tag;
  811. tag->type = import->u.tag.type;
  812. tag->attribute = import->u.tag.attribute;
  813. #if WASM_ENABLE_MULTI_MODULE != 0
  814. if (import->u.tag.import_module) {
  815. if (!(tag->import_module_inst = get_sub_module_inst(
  816. module_inst, import->u.tag.import_module))) {
  817. set_error_buf(error_buf, error_buf_size, "unknown tag");
  818. goto fail;
  819. }
  820. if (!(tag->import_tag_inst =
  821. wasm_lookup_tag(tag->import_module_inst,
  822. import->u.tag.field_name, NULL))) {
  823. set_error_buf(error_buf, error_buf_size, "unknown tag");
  824. goto fail;
  825. }
  826. /* Copy the imported tag to current instance */
  827. module_inst->e->import_tag_ptrs[i] =
  828. tag->u.tag_import->import_tag_linked;
  829. }
  830. #endif
  831. tag++;
  832. }
  833. /* instantiate tags from tag section */
  834. for (i = 0; i < module->tag_count; i++) {
  835. tag->is_import_tag = false;
  836. tag->type = module->tags[i]->type;
  837. tag->u.tag = module->tags[i];
  838. #if WASM_ENABLE_FAST_INTERP != 0
  839. /* tag->const_cell_num = function->u.func->const_cell_num; */
  840. #endif
  841. tag++;
  842. }
  843. bh_assert((uint32)(tag - tags) == tag_count);
  844. return tags;
  845. #if WASM_ENABLE_MULTI_MODULE != 0
  846. fail:
  847. tags_deinstantiate(tags, module_inst->e->import_tag_ptrs);
  848. /* clean up */
  849. module_inst->e->import_tag_ptrs = NULL;
  850. return NULL;
  851. #endif
  852. }
  853. #endif /* end of WASM_ENABLE_TAGS != 0 */
  854. /**
  855. * Destroy global instances.
  856. */
  857. static void
  858. globals_deinstantiate(WASMGlobalInstance *globals)
  859. {
  860. if (globals)
  861. wasm_runtime_free(globals);
  862. }
  863. static bool
  864. check_global_init_expr(const WASMModule *module, uint32 global_index,
  865. char *error_buf, uint32 error_buf_size)
  866. {
  867. if (global_index >= module->import_global_count + module->global_count) {
  868. set_error_buf_v(error_buf, error_buf_size, "unknown global %d",
  869. global_index);
  870. return false;
  871. }
  872. #if WASM_ENABLE_GC == 0
  873. /**
  874. * Currently, constant expressions occurring as initializers of
  875. * globals are further constrained in that contained global.get
  876. * instructions are only allowed to refer to imported globals.
  877. *
  878. * And initializer expression cannot reference a mutable global.
  879. */
  880. if (global_index >= module->import_global_count
  881. || (module->import_globals + global_index)->u.global.type.is_mutable) {
  882. set_error_buf(error_buf, error_buf_size,
  883. "constant expression required");
  884. return false;
  885. }
  886. #endif
  887. return true;
  888. }
  889. #if WASM_ENABLE_GC != 0
  890. /* Instantiate struct global variable recursively */
  891. static WASMStructObjectRef
  892. instantiate_struct_global_recursive(WASMModule *module,
  893. WASMModuleInstance *module_inst,
  894. uint32 type_idx, uint8 flag,
  895. WASMStructNewInitValues *init_values,
  896. char *error_buf, uint32 error_buf_size)
  897. {
  898. WASMRttType *rtt_type;
  899. WASMStructObjectRef struct_obj;
  900. WASMStructType *struct_type;
  901. struct_type = (WASMStructType *)module->types[type_idx];
  902. if (!(rtt_type = wasm_rtt_type_new((WASMType *)struct_type, type_idx,
  903. module->rtt_types, module->type_count,
  904. &module->rtt_type_lock))) {
  905. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  906. return NULL;
  907. }
  908. if (!(struct_obj = wasm_struct_obj_new_internal(
  909. module_inst->e->common.gc_heap_handle, rtt_type))) {
  910. set_error_buf(error_buf, error_buf_size, "create struct object failed");
  911. return NULL;
  912. }
  913. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  914. uint32 field_idx;
  915. WASMRefTypeMap *ref_type_map = struct_type->ref_type_maps;
  916. bh_assert(init_values->count == struct_type->field_count);
  917. for (field_idx = 0; field_idx < init_values->count; field_idx++) {
  918. uint8 field_type = struct_type->fields[field_idx].field_type;
  919. WASMRefType *field_ref_type = NULL;
  920. if (wasm_is_type_multi_byte_type(field_type)) {
  921. field_ref_type = ref_type_map->ref_type;
  922. }
  923. if (wasm_reftype_is_subtype_of(field_type, field_ref_type,
  924. REF_TYPE_STRUCTREF, NULL,
  925. module->types, module->type_count)
  926. || wasm_reftype_is_subtype_of(field_type, field_ref_type,
  927. REF_TYPE_ARRAYREF, NULL,
  928. module->types, module->type_count)
  929. || wasm_reftype_is_subtype_of(
  930. field_type, field_ref_type, REF_TYPE_FUNCREF, NULL,
  931. module->types, module->type_count)) {
  932. WASMType *wasm_type;
  933. int32 heap_type =
  934. ref_type_map->ref_type->ref_ht_common.heap_type;
  935. WASMValue *wasm_value = &init_values->fields[field_idx];
  936. WASMValue field_value = { 0 };
  937. bh_assert(heap_type >= 0);
  938. wasm_type = module->types[heap_type];
  939. bh_assert(wasm_type->type_flag == WASM_TYPE_STRUCT
  940. || wasm_type->type_flag == WASM_TYPE_ARRAY
  941. || wasm_type->type_flag == WASM_TYPE_FUNC);
  942. if (wasm_type->type_flag == WASM_TYPE_STRUCT) {
  943. WASMStructNewInitValues *init_values1 =
  944. (WASMStructNewInitValues *)wasm_value->data;
  945. WASMStructObjectRef field =
  946. instantiate_struct_global_recursive(
  947. module, module_inst, heap_type,
  948. init_values1 ? INIT_EXPR_TYPE_STRUCT_NEW
  949. : INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT,
  950. init_values1, error_buf, error_buf_size);
  951. field_value.gc_obj = (WASMObjectRef)field;
  952. wasm_struct_obj_set_field(struct_obj, field_idx,
  953. &field_value);
  954. }
  955. else if (wasm_type->type_flag == WASM_TYPE_ARRAY) {
  956. /* struct object's field is an array obj */
  957. set_error_buf(error_buf, error_buf_size,
  958. "array as a field in struct object is "
  959. "not supported in constant init expr");
  960. return NULL;
  961. }
  962. else if (wasm_type->type_flag == WASM_TYPE_FUNC) {
  963. WASMFuncObjectRef func_obj = NULL;
  964. /* UINT32_MAX indicates that it is a null reference */
  965. if (wasm_value->u32 != UINT32_MAX) {
  966. if (!(func_obj = wasm_create_func_obj(
  967. module_inst, wasm_value->u32, false,
  968. error_buf, error_buf_size))) {
  969. return NULL;
  970. }
  971. }
  972. field_value.gc_obj = (WASMObjectRef)func_obj;
  973. wasm_struct_obj_set_field(struct_obj, field_idx,
  974. &field_value);
  975. }
  976. }
  977. else {
  978. wasm_struct_obj_set_field(struct_obj, field_idx,
  979. &init_values->fields[field_idx]);
  980. }
  981. if (wasm_is_type_multi_byte_type(field_type)) {
  982. ref_type_map++;
  983. }
  984. }
  985. }
  986. return struct_obj;
  987. }
  988. static WASMArrayObjectRef
  989. instantiate_array_global_recursive(WASMModule *module,
  990. WASMModuleInstance *module_inst,
  991. uint32 type_idx, uint8 flag, uint32 len,
  992. WASMValue *array_init_value,
  993. WASMArrayNewInitValues *init_values,
  994. char *error_buf, uint32 error_buf_size)
  995. {
  996. WASMRttType *rtt_type;
  997. WASMArrayObjectRef array_obj;
  998. WASMArrayType *array_type;
  999. array_type = (WASMArrayType *)module->types[type_idx];
  1000. if (!(rtt_type = wasm_rtt_type_new((WASMType *)array_type, type_idx,
  1001. module->rtt_types, module->type_count,
  1002. &module->rtt_type_lock))) {
  1003. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  1004. return NULL;
  1005. }
  1006. if (!(array_obj =
  1007. wasm_array_obj_new_internal(module_inst->e->common.gc_heap_handle,
  1008. rtt_type, len, array_init_value))) {
  1009. set_error_buf(error_buf, error_buf_size, "create array object failed");
  1010. return NULL;
  1011. }
  1012. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  1013. uint32 elem_idx;
  1014. uint8 elem_type = array_type->elem_type;
  1015. WASMRefType *elem_ref_type = array_type->elem_ref_type;
  1016. bh_assert(init_values);
  1017. if (wasm_reftype_is_subtype_of(elem_type, elem_ref_type,
  1018. REF_TYPE_STRUCTREF, NULL, module->types,
  1019. module->type_count)
  1020. || wasm_reftype_is_subtype_of(elem_type, elem_ref_type,
  1021. REF_TYPE_ARRAYREF, NULL,
  1022. module->types, module->type_count)
  1023. || wasm_reftype_is_subtype_of(elem_type, elem_ref_type,
  1024. REF_TYPE_FUNCREF, NULL, module->types,
  1025. module->type_count)) {
  1026. /* TODO */
  1027. }
  1028. for (elem_idx = 0; elem_idx < len; elem_idx++) {
  1029. wasm_array_obj_set_elem(array_obj, elem_idx,
  1030. &init_values->elem_data[elem_idx]);
  1031. }
  1032. }
  1033. return array_obj;
  1034. }
  1035. #endif
  1036. static bool
  1037. get_init_value_recursive(WASMModule *module, InitializerExpression *expr,
  1038. WASMGlobalInstance *globals, WASMValue *value,
  1039. char *error_buf, uint32 error_buf_size)
  1040. {
  1041. uint8 flag = expr->init_expr_type;
  1042. switch (flag) {
  1043. case INIT_EXPR_TYPE_GET_GLOBAL:
  1044. {
  1045. if (!check_global_init_expr(module, expr->u.unary.v.global_index,
  1046. error_buf, error_buf_size)) {
  1047. goto fail;
  1048. }
  1049. *value = globals[expr->u.unary.v.global_index].initial_value;
  1050. break;
  1051. }
  1052. case INIT_EXPR_TYPE_I32_CONST:
  1053. case INIT_EXPR_TYPE_I64_CONST:
  1054. {
  1055. *value = expr->u.unary.v;
  1056. break;
  1057. }
  1058. #if WASM_ENABLE_EXTENDED_CONST_EXPR != 0
  1059. case INIT_EXPR_TYPE_I32_ADD:
  1060. case INIT_EXPR_TYPE_I32_SUB:
  1061. case INIT_EXPR_TYPE_I32_MUL:
  1062. case INIT_EXPR_TYPE_I64_ADD:
  1063. case INIT_EXPR_TYPE_I64_SUB:
  1064. case INIT_EXPR_TYPE_I64_MUL:
  1065. {
  1066. WASMValue l_value, r_value;
  1067. if (!expr->u.binary.l_expr || !expr->u.binary.r_expr) {
  1068. goto fail;
  1069. }
  1070. if (!get_init_value_recursive(module, expr->u.binary.l_expr,
  1071. globals, &l_value, error_buf,
  1072. error_buf_size)) {
  1073. goto fail;
  1074. }
  1075. if (!get_init_value_recursive(module, expr->u.binary.r_expr,
  1076. globals, &r_value, error_buf,
  1077. error_buf_size)) {
  1078. goto fail;
  1079. }
  1080. if (flag == INIT_EXPR_TYPE_I32_ADD) {
  1081. value->i32 = l_value.i32 + r_value.i32;
  1082. }
  1083. else if (flag == INIT_EXPR_TYPE_I32_SUB) {
  1084. value->i32 = l_value.i32 - r_value.i32;
  1085. }
  1086. else if (flag == INIT_EXPR_TYPE_I32_MUL) {
  1087. value->i32 = l_value.i32 * r_value.i32;
  1088. }
  1089. else if (flag == INIT_EXPR_TYPE_I64_ADD) {
  1090. value->i64 = l_value.i64 + r_value.i64;
  1091. }
  1092. else if (flag == INIT_EXPR_TYPE_I64_SUB) {
  1093. value->i64 = l_value.i64 - r_value.i64;
  1094. }
  1095. else if (flag == INIT_EXPR_TYPE_I64_MUL) {
  1096. value->i64 = l_value.i64 * r_value.i64;
  1097. }
  1098. break;
  1099. }
  1100. #endif /* end of WASM_ENABLE_EXTENDED_CONST_EXPR != 0 */
  1101. default:
  1102. goto fail;
  1103. }
  1104. return true;
  1105. fail:
  1106. return false;
  1107. }
  1108. /**
  1109. * Instantiate globals in a module.
  1110. */
  1111. static WASMGlobalInstance *
  1112. globals_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
  1113. char *error_buf, uint32 error_buf_size)
  1114. {
  1115. WASMImport *import;
  1116. uint32 global_data_offset = 0;
  1117. uint32 i, global_count = module->import_global_count + module->global_count;
  1118. uint64 total_size = sizeof(WASMGlobalInstance) * (uint64)global_count;
  1119. WASMGlobalInstance *globals, *global;
  1120. if (!(globals = runtime_malloc(total_size, error_buf, error_buf_size))) {
  1121. return NULL;
  1122. }
  1123. /* instantiate globals from import section */
  1124. global = globals;
  1125. import = module->import_globals;
  1126. for (i = 0; i < module->import_global_count; i++, import++) {
  1127. WASMGlobalImport *global_import = &import->u.global;
  1128. global->type = global_import->type.val_type;
  1129. global->is_mutable = global_import->type.is_mutable;
  1130. #if WASM_ENABLE_GC != 0
  1131. global->ref_type = global_import->ref_type;
  1132. #endif
  1133. #if WASM_ENABLE_MULTI_MODULE != 0
  1134. if (global_import->import_module) {
  1135. if (!(global->import_module_inst = get_sub_module_inst(
  1136. module_inst, global_import->import_module))) {
  1137. set_error_buf(error_buf, error_buf_size, "unknown global");
  1138. goto fail;
  1139. }
  1140. if (!(global->import_global_inst = wasm_lookup_global(
  1141. global->import_module_inst, global_import->field_name))) {
  1142. set_error_buf(error_buf, error_buf_size, "unknown global");
  1143. goto fail;
  1144. }
  1145. /* The linked global instance has been initialized, we
  1146. just need to copy the value. */
  1147. global->initial_value =
  1148. global_import->import_global_linked->init_expr.u.unary.v;
  1149. }
  1150. else
  1151. #endif
  1152. {
  1153. /* native globals share their initial_values in one module */
  1154. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  1155. &(global_import->global_data_linked),
  1156. sizeof(WASMValue));
  1157. }
  1158. #if WASM_ENABLE_FAST_JIT != 0
  1159. bh_assert(global_data_offset == global_import->data_offset);
  1160. #endif
  1161. global->data_offset = global_data_offset;
  1162. global_data_offset += wasm_value_type_size(global->type);
  1163. global++;
  1164. }
  1165. /* instantiate globals from global section */
  1166. for (i = 0; i < module->global_count; i++) {
  1167. InitializerExpression *init_expr = &(module->globals[i].init_expr);
  1168. uint8 flag = init_expr->init_expr_type;
  1169. global->type = module->globals[i].type.val_type;
  1170. global->is_mutable = module->globals[i].type.is_mutable;
  1171. #if WASM_ENABLE_FAST_JIT != 0
  1172. bh_assert(global_data_offset == module->globals[i].data_offset);
  1173. #endif
  1174. global->data_offset = global_data_offset;
  1175. global_data_offset += wasm_value_type_size(global->type);
  1176. #if WASM_ENABLE_GC != 0
  1177. global->ref_type = module->globals[i].ref_type;
  1178. #endif
  1179. switch (flag) {
  1180. case INIT_EXPR_TYPE_I32_CONST:
  1181. case INIT_EXPR_TYPE_I64_CONST:
  1182. case INIT_EXPR_TYPE_GET_GLOBAL:
  1183. #if WASM_ENABLE_EXTENDED_CONST_EXPR != 0
  1184. case INIT_EXPR_TYPE_I32_ADD:
  1185. case INIT_EXPR_TYPE_I32_SUB:
  1186. case INIT_EXPR_TYPE_I32_MUL:
  1187. case INIT_EXPR_TYPE_I64_ADD:
  1188. case INIT_EXPR_TYPE_I64_SUB:
  1189. case INIT_EXPR_TYPE_I64_MUL:
  1190. #endif
  1191. {
  1192. if (!get_init_value_recursive(module, init_expr, globals,
  1193. &global->initial_value, error_buf,
  1194. error_buf_size)) {
  1195. goto fail;
  1196. }
  1197. break;
  1198. }
  1199. #if WASM_ENABLE_GC != 0
  1200. case INIT_EXPR_TYPE_STRUCT_NEW:
  1201. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  1202. {
  1203. WASMStructObjectRef struct_obj;
  1204. WASMStructNewInitValues *init_values = NULL;
  1205. uint32 type_idx;
  1206. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  1207. init_values =
  1208. (WASMStructNewInitValues *)init_expr->u.unary.v.data;
  1209. type_idx = init_values->type_idx;
  1210. }
  1211. else {
  1212. type_idx = init_expr->u.unary.v.type_index;
  1213. }
  1214. struct_obj = instantiate_struct_global_recursive(
  1215. module, module_inst, type_idx, flag, init_values, error_buf,
  1216. error_buf_size);
  1217. if (!struct_obj) {
  1218. goto fail;
  1219. }
  1220. global->initial_value.gc_obj = (void *)struct_obj;
  1221. break;
  1222. }
  1223. case INIT_EXPR_TYPE_ARRAY_NEW:
  1224. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  1225. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  1226. {
  1227. WASMArrayObjectRef array_obj;
  1228. WASMArrayNewInitValues *init_values = NULL;
  1229. WASMValue *array_init_value = NULL, empty_value = { 0 };
  1230. uint32 type_idx, len;
  1231. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  1232. type_idx =
  1233. init_expr->u.unary.v.array_new_default.type_index;
  1234. len = init_expr->u.unary.v.array_new_default.length;
  1235. array_init_value = &empty_value;
  1236. }
  1237. else {
  1238. init_values =
  1239. (WASMArrayNewInitValues *)init_expr->u.unary.v.data;
  1240. type_idx = init_values->type_idx;
  1241. len = init_values->length;
  1242. if (flag == INIT_EXPR_TYPE_ARRAY_NEW) {
  1243. array_init_value = init_values->elem_data;
  1244. }
  1245. }
  1246. array_obj = instantiate_array_global_recursive(
  1247. module, module_inst, type_idx, flag, len, array_init_value,
  1248. init_values, error_buf, error_buf_size);
  1249. global->initial_value.gc_obj = (void *)array_obj;
  1250. break;
  1251. }
  1252. case INIT_EXPR_TYPE_I31_NEW:
  1253. {
  1254. global->initial_value.gc_obj =
  1255. (wasm_obj_t)wasm_i31_obj_new(init_expr->u.unary.v.i32);
  1256. break;
  1257. }
  1258. #endif /* end of WASM_ENABLE_GC != 0 */
  1259. default:
  1260. global->initial_value = init_expr->u.unary.v;
  1261. break;
  1262. }
  1263. global++;
  1264. }
  1265. bh_assert((uint32)(global - globals) == global_count);
  1266. bh_assert(global_data_offset == module->global_data_size);
  1267. (void)module_inst;
  1268. return globals;
  1269. fail:
  1270. wasm_runtime_free(globals);
  1271. return NULL;
  1272. }
  1273. /**
  1274. * Return export function count in module export section.
  1275. */
  1276. static uint32
  1277. get_export_count(const WASMModule *module, uint8 kind)
  1278. {
  1279. WASMExport *export = module->exports;
  1280. uint32 count = 0, i;
  1281. for (i = 0; i < module->export_count; i++, export ++)
  1282. if (export->kind == kind)
  1283. count++;
  1284. return count;
  1285. }
  1286. /**
  1287. * Destroy export function instances.
  1288. */
  1289. static void
  1290. export_functions_deinstantiate(WASMExportFuncInstance *functions)
  1291. {
  1292. if (functions)
  1293. wasm_runtime_free(functions);
  1294. }
  1295. static int
  1296. cmp_export_func_inst(const void *a, const void *b)
  1297. {
  1298. const WASMExportFuncInstance *export_func1 =
  1299. (const WASMExportFuncInstance *)a;
  1300. const WASMExportFuncInstance *export_func2 =
  1301. (const WASMExportFuncInstance *)b;
  1302. return strcmp(export_func1->name, export_func2->name);
  1303. }
  1304. /**
  1305. * Instantiate export functions in a module.
  1306. */
  1307. static WASMExportFuncInstance *
  1308. export_functions_instantiate(const WASMModule *module,
  1309. WASMModuleInstance *module_inst,
  1310. uint32 export_func_count, char *error_buf,
  1311. uint32 error_buf_size)
  1312. {
  1313. WASMExportFuncInstance *export_funcs, *export_func;
  1314. WASMExport *export = module->exports;
  1315. uint32 i;
  1316. uint64 total_size =
  1317. sizeof(WASMExportFuncInstance) * (uint64)export_func_count;
  1318. if (!(export_func = export_funcs =
  1319. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1320. return NULL;
  1321. }
  1322. for (i = 0; i < module->export_count; i++, export ++)
  1323. if (export->kind == EXPORT_KIND_FUNC) {
  1324. export_func->name = export->name;
  1325. export_func->function = &module_inst->e->functions[export->index];
  1326. export_func++;
  1327. }
  1328. bh_assert((uint32)(export_func - export_funcs) == export_func_count);
  1329. qsort(export_funcs, export_func_count, sizeof(WASMExportFuncInstance),
  1330. cmp_export_func_inst);
  1331. return export_funcs;
  1332. }
  1333. #if WASM_ENABLE_TAGS != 0
  1334. /**
  1335. * Destroy export function instances.
  1336. */
  1337. static void
  1338. export_tags_deinstantiate(WASMExportTagInstance *tags)
  1339. {
  1340. if (tags)
  1341. wasm_runtime_free(tags);
  1342. }
  1343. /**
  1344. * Instantiate export functions in a module.
  1345. */
  1346. static WASMExportTagInstance *
  1347. export_tags_instantiate(const WASMModule *module,
  1348. WASMModuleInstance *module_inst,
  1349. uint32 export_tag_count, char *error_buf,
  1350. uint32 error_buf_size)
  1351. {
  1352. WASMExportTagInstance *export_tags, *export_tag;
  1353. WASMExport *export = module->exports;
  1354. uint32 i;
  1355. uint64 total_size =
  1356. sizeof(WASMExportTagInstance) * (uint64)export_tag_count;
  1357. if (!(export_tag = export_tags =
  1358. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1359. return NULL;
  1360. }
  1361. for (i = 0; i < module->export_count; i++, export ++)
  1362. if (export->kind == EXPORT_KIND_TAG) {
  1363. export_tag->name = export->name;
  1364. bh_assert(module_inst->e->tags);
  1365. export_tag->tag = &module_inst->e->tags[export->index];
  1366. export_tag++;
  1367. }
  1368. bh_assert((uint32)(export_tag - export_tags) == export_tag_count);
  1369. return export_tags;
  1370. }
  1371. #endif /* end of WASM_ENABLE_TAGS != 0 */
  1372. #if WASM_ENABLE_MULTI_MEMORY != 0
  1373. static void
  1374. export_memories_deinstantiate(WASMExportMemInstance *memories)
  1375. {
  1376. if (memories)
  1377. wasm_runtime_free(memories);
  1378. }
  1379. static WASMExportMemInstance *
  1380. export_memories_instantiate(const WASMModule *module,
  1381. WASMModuleInstance *module_inst,
  1382. uint32 export_mem_count, char *error_buf,
  1383. uint32 error_buf_size)
  1384. {
  1385. WASMExportMemInstance *export_memories, *export_memory;
  1386. WASMExport *export = module->exports;
  1387. uint32 i;
  1388. uint64 total_size =
  1389. sizeof(WASMExportMemInstance) * (uint64)export_mem_count;
  1390. if (!(export_memory = export_memories =
  1391. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1392. return NULL;
  1393. }
  1394. for (i = 0; i < module->export_count; i++, export ++)
  1395. if (export->kind == EXPORT_KIND_MEMORY) {
  1396. export_memory->name = export->name;
  1397. export_memory->memory = module_inst->memories[export->index];
  1398. export_memory++;
  1399. }
  1400. bh_assert((uint32)(export_memory - export_memories) == export_mem_count);
  1401. return export_memories;
  1402. }
  1403. #endif /* end of if WASM_ENABLE_MULTI_MEMORY != 0 */
  1404. #if WASM_ENABLE_MULTI_MODULE != 0
  1405. static void
  1406. export_globals_deinstantiate(WASMExportGlobInstance *globals)
  1407. {
  1408. if (globals)
  1409. wasm_runtime_free(globals);
  1410. }
  1411. static WASMExportGlobInstance *
  1412. export_globals_instantiate(const WASMModule *module,
  1413. WASMModuleInstance *module_inst,
  1414. uint32 export_glob_count, char *error_buf,
  1415. uint32 error_buf_size)
  1416. {
  1417. WASMExportGlobInstance *export_globals, *export_global;
  1418. WASMExport *export = module->exports;
  1419. uint32 i;
  1420. uint64 total_size =
  1421. sizeof(WASMExportGlobInstance) * (uint64)export_glob_count;
  1422. if (!(export_global = export_globals =
  1423. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1424. return NULL;
  1425. }
  1426. for (i = 0; i < module->export_count; i++, export ++)
  1427. if (export->kind == EXPORT_KIND_GLOBAL) {
  1428. export_global->name = export->name;
  1429. export_global->global = &module_inst->e->globals[export->index];
  1430. export_global++;
  1431. }
  1432. bh_assert((uint32)(export_global - export_globals) == export_glob_count);
  1433. return export_globals;
  1434. }
  1435. #endif /* end of if WASM_ENABLE_MULTI_MODULE != 0 */
  1436. static WASMFunctionInstance *
  1437. lookup_post_instantiate_func(WASMModuleInstance *module_inst,
  1438. const char *func_name)
  1439. {
  1440. WASMFunctionInstance *func;
  1441. WASMFuncType *func_type;
  1442. if (!(func = wasm_lookup_function(module_inst, func_name)))
  1443. /* Not found */
  1444. return NULL;
  1445. func_type = func->u.func->func_type;
  1446. if (!(func_type->param_count == 0 && func_type->result_count == 0))
  1447. /* Not a valid function type, ignore it */
  1448. return NULL;
  1449. return func;
  1450. }
  1451. static bool
  1452. execute_post_instantiate_functions(WASMModuleInstance *module_inst,
  1453. bool is_sub_inst, WASMExecEnv *exec_env_main)
  1454. {
  1455. WASMFunctionInstance *start_func = module_inst->e->start_function;
  1456. WASMFunctionInstance *initialize_func = NULL;
  1457. WASMFunctionInstance *post_inst_func = NULL;
  1458. WASMFunctionInstance *call_ctors_func = NULL;
  1459. #if WASM_ENABLE_LIBC_WASI != 0
  1460. WASMModule *module = module_inst->module;
  1461. #endif
  1462. WASMModuleInstanceCommon *module_inst_main = NULL;
  1463. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1464. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1465. #endif
  1466. WASMExecEnv *exec_env = NULL, *exec_env_created = NULL;
  1467. bool ret = false;
  1468. #if WASM_ENABLE_LIBC_WASI != 0
  1469. /*
  1470. * WASI reactor instances may assume that _initialize will be called by
  1471. * the environment at most once, and that none of their other exports
  1472. * are accessed before that call.
  1473. */
  1474. if (!is_sub_inst && module->import_wasi_api) {
  1475. initialize_func =
  1476. lookup_post_instantiate_func(module_inst, "_initialize");
  1477. }
  1478. #endif
  1479. /* Execute possible "__post_instantiate" function if wasm app is
  1480. compiled by emsdk's early version */
  1481. if (!is_sub_inst) {
  1482. post_inst_func =
  1483. lookup_post_instantiate_func(module_inst, "__post_instantiate");
  1484. }
  1485. #if WASM_ENABLE_BULK_MEMORY != 0
  1486. /* Only execute the memory init function for main instance since
  1487. the data segments will be dropped once initialized */
  1488. if (!is_sub_inst
  1489. #if WASM_ENABLE_LIBC_WASI != 0
  1490. && !module->import_wasi_api
  1491. #endif
  1492. ) {
  1493. call_ctors_func =
  1494. lookup_post_instantiate_func(module_inst, "__wasm_call_ctors");
  1495. }
  1496. #endif
  1497. if (!start_func && !initialize_func && !post_inst_func
  1498. && !call_ctors_func) {
  1499. /* No post instantiation functions to call */
  1500. return true;
  1501. }
  1502. if (is_sub_inst) {
  1503. bh_assert(exec_env_main);
  1504. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1505. /* May come from pthread_create_wrapper, thread_spawn_wrapper and
  1506. wasm_cluster_spawn_exec_env. If it comes from the former two,
  1507. the exec_env_tls must be not NULL and equal to exec_env_main,
  1508. else if it comes from the last one, it may be NULL. */
  1509. if (exec_env_tls)
  1510. bh_assert(exec_env_tls == exec_env_main);
  1511. #endif
  1512. exec_env = exec_env_main;
  1513. /* Temporarily replace parent exec_env's module inst to current
  1514. module inst to avoid checking failure when calling the
  1515. wasm functions, and ensure that the exec_env's module inst
  1516. is the correct one. */
  1517. module_inst_main = exec_env_main->module_inst;
  1518. wasm_exec_env_set_module_inst(exec_env,
  1519. (WASMModuleInstanceCommon *)module_inst);
  1520. }
  1521. else {
  1522. /* Try using the existing exec_env */
  1523. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1524. exec_env = exec_env_tls;
  1525. #endif
  1526. #if WASM_ENABLE_THREAD_MGR != 0
  1527. if (!exec_env)
  1528. exec_env = wasm_clusters_search_exec_env(
  1529. (WASMModuleInstanceCommon *)module_inst);
  1530. #endif
  1531. if (!exec_env) {
  1532. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1533. (WASMModuleInstanceCommon *)module_inst,
  1534. module_inst->default_wasm_stack_size))) {
  1535. wasm_set_exception(module_inst, "allocate memory failed");
  1536. return false;
  1537. }
  1538. }
  1539. else {
  1540. /* Temporarily replace exec_env's module inst with current
  1541. module inst to ensure that the exec_env's module inst
  1542. is the correct one. */
  1543. module_inst_main = exec_env->module_inst;
  1544. wasm_exec_env_set_module_inst(
  1545. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1546. }
  1547. }
  1548. /* Execute start function for both main instance and sub instance */
  1549. if (start_func && !wasm_call_function(exec_env, start_func, 0, NULL)) {
  1550. goto fail;
  1551. }
  1552. #if WASM_ENABLE_LIBC_WASI != 0
  1553. if (initialize_func
  1554. && !wasm_call_function(exec_env, initialize_func, 0, NULL)) {
  1555. goto fail;
  1556. }
  1557. #else
  1558. (void)initialize_func;
  1559. #endif
  1560. if (post_inst_func
  1561. && !wasm_call_function(exec_env, post_inst_func, 0, NULL)) {
  1562. goto fail;
  1563. }
  1564. if (call_ctors_func
  1565. && !wasm_call_function(exec_env, call_ctors_func, 0, NULL)) {
  1566. goto fail;
  1567. }
  1568. ret = true;
  1569. fail:
  1570. if (is_sub_inst) {
  1571. /* Restore the parent exec_env's module inst */
  1572. wasm_exec_env_restore_module_inst(exec_env_main, module_inst_main);
  1573. }
  1574. else {
  1575. if (module_inst_main)
  1576. /* Restore the existing exec_env's module inst */
  1577. wasm_exec_env_restore_module_inst(exec_env, module_inst_main);
  1578. if (exec_env_created)
  1579. wasm_exec_env_destroy(exec_env_created);
  1580. }
  1581. return ret;
  1582. }
  1583. static bool
  1584. execute_malloc_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1585. WASMFunctionInstance *malloc_func,
  1586. WASMFunctionInstance *retain_func, uint64 size,
  1587. uint64 *p_result)
  1588. {
  1589. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1590. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1591. #endif
  1592. WASMExecEnv *exec_env_created = NULL;
  1593. WASMModuleInstanceCommon *module_inst_old = NULL;
  1594. union {
  1595. uint32 u32[3];
  1596. uint64 u64;
  1597. } argv;
  1598. uint32 argc;
  1599. bool ret;
  1600. #if WASM_ENABLE_MEMORY64 != 0
  1601. bool is_memory64 = module_inst->memories[0]->is_memory64;
  1602. if (is_memory64) {
  1603. argc = 2;
  1604. PUT_I64_TO_ADDR(&argv.u64, size);
  1605. }
  1606. else
  1607. #endif
  1608. {
  1609. argc = 1;
  1610. argv.u32[0] = (uint32)size;
  1611. }
  1612. /* if __retain is exported, then this module is compiled by
  1613. assemblyscript, the memory should be managed by as's runtime,
  1614. in this case we need to call the retain function after malloc
  1615. the memory */
  1616. if (retain_func) {
  1617. /* the malloc function from assemblyscript is:
  1618. function __new(size: usize, id: u32)
  1619. id = 0 means this is an ArrayBuffer object */
  1620. argv.u32[argc] = 0;
  1621. argc++;
  1622. }
  1623. if (exec_env) {
  1624. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1625. if (exec_env_tls) {
  1626. bh_assert(exec_env_tls == exec_env);
  1627. }
  1628. #endif
  1629. bh_assert(exec_env->module_inst
  1630. == (WASMModuleInstanceCommon *)module_inst);
  1631. }
  1632. else {
  1633. /* Try using the existing exec_env */
  1634. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1635. exec_env = exec_env_tls;
  1636. #endif
  1637. #if WASM_ENABLE_THREAD_MGR != 0
  1638. if (!exec_env)
  1639. exec_env = wasm_clusters_search_exec_env(
  1640. (WASMModuleInstanceCommon *)module_inst);
  1641. #endif
  1642. if (!exec_env) {
  1643. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1644. (WASMModuleInstanceCommon *)module_inst,
  1645. module_inst->default_wasm_stack_size))) {
  1646. wasm_set_exception(module_inst, "allocate memory failed");
  1647. return false;
  1648. }
  1649. }
  1650. else {
  1651. /* Temporarily replace exec_env's module inst with current
  1652. module inst to ensure that the exec_env's module inst
  1653. is the correct one. */
  1654. module_inst_old = exec_env->module_inst;
  1655. wasm_exec_env_set_module_inst(
  1656. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1657. }
  1658. }
  1659. ret = wasm_call_function(exec_env, malloc_func, argc, argv.u32);
  1660. if (retain_func && ret)
  1661. ret = wasm_call_function(exec_env, retain_func, 1, argv.u32);
  1662. if (module_inst_old)
  1663. /* Restore the existing exec_env's module inst */
  1664. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  1665. if (exec_env_created)
  1666. wasm_exec_env_destroy(exec_env_created);
  1667. if (ret) {
  1668. #if WASM_ENABLE_MEMORY64 != 0
  1669. if (is_memory64)
  1670. *p_result = argv.u64;
  1671. else
  1672. #endif
  1673. {
  1674. *p_result = argv.u32[0];
  1675. }
  1676. }
  1677. return ret;
  1678. }
  1679. static bool
  1680. execute_free_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1681. WASMFunctionInstance *free_func, uint64 offset)
  1682. {
  1683. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1684. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1685. #endif
  1686. WASMExecEnv *exec_env_created = NULL;
  1687. WASMModuleInstanceCommon *module_inst_old = NULL;
  1688. union {
  1689. uint32 u32[2];
  1690. uint64 u64;
  1691. } argv;
  1692. uint32 argc;
  1693. bool ret;
  1694. #if WASM_ENABLE_MEMORY64 != 0
  1695. if (module_inst->memories[0]->is_memory64) {
  1696. PUT_I64_TO_ADDR(&argv.u64, offset);
  1697. argc = 2;
  1698. }
  1699. else
  1700. #endif
  1701. {
  1702. argv.u32[0] = (uint32)offset;
  1703. argc = 1;
  1704. }
  1705. if (exec_env) {
  1706. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1707. if (exec_env_tls) {
  1708. bh_assert(exec_env_tls == exec_env);
  1709. }
  1710. #endif
  1711. bh_assert(exec_env->module_inst
  1712. == (WASMModuleInstanceCommon *)module_inst);
  1713. }
  1714. else {
  1715. /* Try using the existing exec_env */
  1716. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1717. exec_env = exec_env_tls;
  1718. #endif
  1719. #if WASM_ENABLE_THREAD_MGR != 0
  1720. if (!exec_env)
  1721. exec_env = wasm_clusters_search_exec_env(
  1722. (WASMModuleInstanceCommon *)module_inst);
  1723. #endif
  1724. if (!exec_env) {
  1725. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1726. (WASMModuleInstanceCommon *)module_inst,
  1727. module_inst->default_wasm_stack_size))) {
  1728. wasm_set_exception(module_inst, "allocate memory failed");
  1729. return false;
  1730. }
  1731. }
  1732. else {
  1733. /* Temporarily replace exec_env's module inst with current
  1734. module inst to ensure that the exec_env's module inst
  1735. is the correct one. */
  1736. module_inst_old = exec_env->module_inst;
  1737. wasm_exec_env_set_module_inst(
  1738. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1739. }
  1740. }
  1741. ret = wasm_call_function(exec_env, free_func, argc, argv.u32);
  1742. if (module_inst_old)
  1743. /* Restore the existing exec_env's module inst */
  1744. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  1745. if (exec_env_created)
  1746. wasm_exec_env_destroy(exec_env_created);
  1747. return ret;
  1748. }
  1749. static bool
  1750. check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf,
  1751. uint32 error_buf_size)
  1752. {
  1753. WASMModule *module = module_inst->module;
  1754. uint32 i;
  1755. for (i = 0; i < module->import_function_count; i++) {
  1756. WASMFunctionImport *func =
  1757. &((module->import_functions + i)->u.function);
  1758. if (!func->func_ptr_linked
  1759. #if WASM_ENABLE_MULTI_MODULE != 0
  1760. && !func->import_func_linked
  1761. #endif
  1762. ) {
  1763. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1764. func->module_name, func->field_name);
  1765. }
  1766. }
  1767. for (i = 0; i < module->import_global_count; i++) {
  1768. WASMGlobalImport *global = &((module->import_globals + i)->u.global);
  1769. if (!global->is_linked) {
  1770. #if WASM_ENABLE_SPEC_TEST != 0
  1771. set_error_buf(error_buf, error_buf_size,
  1772. "unknown import or incompatible import type");
  1773. return false;
  1774. #else
  1775. set_error_buf_v(error_buf, error_buf_size,
  1776. "failed to link import global (%s, %s)",
  1777. global->module_name, global->field_name);
  1778. return false;
  1779. #endif /* WASM_ENABLE_SPEC_TEST != 0 */
  1780. }
  1781. }
  1782. for (i = 0; i < module->import_table_count; i++) {
  1783. WASMTableImport *table = &((module->import_tables + i)->u.table);
  1784. if (!wasm_runtime_is_built_in_module(table->module_name)
  1785. #if WASM_ENABLE_MULTI_MODULE != 0
  1786. && !table->import_table_linked
  1787. #endif
  1788. ) {
  1789. set_error_buf_v(error_buf, error_buf_size,
  1790. "failed to link import table (%s, %s)",
  1791. table->module_name, table->field_name);
  1792. return false;
  1793. }
  1794. }
  1795. for (i = 0; i < module->import_memory_count; i++) {
  1796. WASMMemoryImport *memory = &((module->import_memories + i)->u.memory);
  1797. if (!wasm_runtime_is_built_in_module(memory->module_name)
  1798. #if WASM_ENABLE_MULTI_MODULE != 0
  1799. && !memory->import_memory_linked
  1800. #endif
  1801. ) {
  1802. set_error_buf_v(error_buf, error_buf_size,
  1803. "failed to link import memory (%s, %s)",
  1804. memory->module_name, memory->field_name);
  1805. return false;
  1806. }
  1807. }
  1808. #if WASM_ENABLE_MULTI_MODULE != 0
  1809. #if WASM_ENABLE_TAGS != 0
  1810. for (i = 0; i < module->import_tag_count; i++) {
  1811. WASMTagImport *tag = &((module->import_tags + i)->u.tag);
  1812. if (!tag->import_tag_linked) {
  1813. set_error_buf_v(error_buf, error_buf_size,
  1814. "failed to link import tag (%s, %s)",
  1815. tag->module_name, tag->field_name);
  1816. return false;
  1817. }
  1818. }
  1819. #endif /* WASM_ENABLE_TAGS != 0 */
  1820. #endif
  1821. return true;
  1822. }
  1823. #if WASM_ENABLE_JIT != 0
  1824. static bool
  1825. init_func_ptrs(WASMModuleInstance *module_inst, WASMModule *module,
  1826. char *error_buf, uint32 error_buf_size)
  1827. {
  1828. uint32 i;
  1829. void **func_ptrs;
  1830. uint64 total_size = (uint64)sizeof(void *) * module_inst->e->function_count;
  1831. /* Allocate memory */
  1832. if (!(func_ptrs = module_inst->func_ptrs =
  1833. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1834. return false;
  1835. }
  1836. /* Set import function pointers */
  1837. for (i = 0; i < module->import_function_count; i++, func_ptrs++) {
  1838. WASMFunctionImport *import_func =
  1839. &module->import_functions[i].u.function;
  1840. /* TODO: handle multi module */
  1841. *func_ptrs = import_func->func_ptr_linked;
  1842. }
  1843. /* The defined function pointers will be set in
  1844. wasm_runtime_set_running_mode, no need to set them here */
  1845. return true;
  1846. }
  1847. #endif /* end of WASM_ENABLE_JIT != 0 */
  1848. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1849. static uint32
  1850. get_smallest_type_idx(WASMModule *module, WASMFuncType *func_type)
  1851. {
  1852. uint32 i;
  1853. for (i = 0; i < module->type_count; i++) {
  1854. if (func_type == (WASMFuncType *)module->types[i])
  1855. return i;
  1856. }
  1857. bh_assert(0);
  1858. return -1;
  1859. }
  1860. static bool
  1861. init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf,
  1862. uint32 error_buf_size)
  1863. {
  1864. uint32 i;
  1865. uint64 total_size = (uint64)sizeof(uint32) * module_inst->e->function_count;
  1866. /* Allocate memory */
  1867. if (!(module_inst->func_type_indexes =
  1868. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1869. return false;
  1870. }
  1871. for (i = 0; i < module_inst->e->function_count; i++) {
  1872. WASMFunctionInstance *func_inst = module_inst->e->functions + i;
  1873. WASMFuncType *func_type = func_inst->is_import_func
  1874. ? func_inst->u.func_import->func_type
  1875. : func_inst->u.func->func_type;
  1876. module_inst->func_type_indexes[i] =
  1877. get_smallest_type_idx(module_inst->module, func_type);
  1878. }
  1879. return true;
  1880. }
  1881. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 */
  1882. #if WASM_ENABLE_GC != 0
  1883. void *
  1884. wasm_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx,
  1885. bool throw_exce, char *error_buf, uint32 error_buf_size)
  1886. {
  1887. WASMModule *module = module_inst->module;
  1888. WASMRttTypeRef rtt_type;
  1889. WASMFuncObjectRef func_obj;
  1890. WASMFuncType *func_type;
  1891. uint32 type_idx;
  1892. if (throw_exce) {
  1893. error_buf = module_inst->cur_exception;
  1894. error_buf_size = sizeof(module_inst->cur_exception);
  1895. }
  1896. if (func_idx >= module->import_function_count + module->function_count) {
  1897. set_error_buf_v(error_buf, error_buf_size, "unknown function %d",
  1898. func_idx);
  1899. return NULL;
  1900. }
  1901. if (func_idx < module->import_function_count) {
  1902. func_type = module->import_functions[func_idx].u.function.func_type;
  1903. type_idx = module->import_functions[func_idx].u.function.type_idx;
  1904. }
  1905. else {
  1906. func_type = module->functions[func_idx - module->import_function_count]
  1907. ->func_type;
  1908. type_idx = module->functions[func_idx - module->import_function_count]
  1909. ->type_idx;
  1910. }
  1911. if (!(rtt_type = wasm_rtt_type_new((WASMType *)func_type, type_idx,
  1912. module->rtt_types, module->type_count,
  1913. &module->rtt_type_lock))) {
  1914. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  1915. return NULL;
  1916. }
  1917. if (!(func_obj = wasm_func_obj_new_internal(
  1918. module_inst->e->common.gc_heap_handle, rtt_type, func_idx))) {
  1919. set_error_buf(error_buf, error_buf_size, "create func object failed");
  1920. return NULL;
  1921. }
  1922. return func_obj;
  1923. }
  1924. static bool
  1925. wasm_global_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1926. {
  1927. WASMGlobalInstance *global = module_inst->e->globals;
  1928. WASMGlobalInstance *global_end = global + module_inst->e->global_count;
  1929. uint8 *global_data = module_inst->global_data;
  1930. WASMObjectRef gc_obj;
  1931. while (global < global_end) {
  1932. if (wasm_is_type_reftype(global->type)) {
  1933. gc_obj = GET_REF_FROM_ADDR(
  1934. (uint32 *)(global_data + global->data_offset));
  1935. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1936. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1937. return false;
  1938. }
  1939. }
  1940. global++;
  1941. }
  1942. return true;
  1943. }
  1944. static bool
  1945. wasm_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1946. {
  1947. WASMTableInstance **tables = module_inst->tables, *table;
  1948. uint32 table_count = module_inst->table_count, i, j;
  1949. WASMObjectRef gc_obj, *table_elems;
  1950. for (i = 0; i < table_count; i++) {
  1951. table = tables[i];
  1952. table_elems = (WASMObjectRef *)table->elems;
  1953. for (j = 0; j < table->cur_size; j++) {
  1954. gc_obj = table_elems[j];
  1955. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1956. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1957. return false;
  1958. }
  1959. }
  1960. }
  1961. return true;
  1962. }
  1963. static bool
  1964. local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1965. {
  1966. WASMLocalObjectRef *r;
  1967. WASMObjectRef gc_obj;
  1968. for (r = exec_env->cur_local_object_ref; r; r = r->prev) {
  1969. gc_obj = r->val;
  1970. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1971. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1972. return false;
  1973. }
  1974. }
  1975. return true;
  1976. }
  1977. bool
  1978. wasm_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1979. {
  1980. WASMModuleInstance *module_inst =
  1981. (WASMModuleInstance *)exec_env->module_inst;
  1982. bool ret;
  1983. ret = wasm_global_traverse_gc_rootset(module_inst, heap);
  1984. if (!ret)
  1985. return ret;
  1986. ret = wasm_table_traverse_gc_rootset(module_inst, heap);
  1987. if (!ret)
  1988. return ret;
  1989. ret = local_object_refs_traverse_gc_rootset(exec_env, heap);
  1990. if (!ret)
  1991. return ret;
  1992. return wasm_interp_traverse_gc_rootset(exec_env, heap);
  1993. }
  1994. #endif /* end of WASM_ENABLE_GC != 0 */
  1995. static bool
  1996. set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode,
  1997. bool first_time_set)
  1998. {
  1999. WASMModule *module = module_inst->module;
  2000. if (running_mode == Mode_Default) {
  2001. #if WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT == 0
  2002. running_mode = Mode_Interp;
  2003. #elif WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT == 0
  2004. running_mode = Mode_Fast_JIT;
  2005. #elif WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT != 0
  2006. running_mode = Mode_LLVM_JIT;
  2007. #else /* WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 */
  2008. #if WASM_ENABLE_LAZY_JIT == 0
  2009. running_mode = Mode_LLVM_JIT;
  2010. #else
  2011. running_mode = Mode_Multi_Tier_JIT;
  2012. #endif
  2013. #endif
  2014. }
  2015. if (!wasm_runtime_is_running_mode_supported(running_mode))
  2016. return false;
  2017. #if !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2018. && WASM_ENABLE_LAZY_JIT != 0) /* No possible multi-tier JIT */
  2019. (void)first_time_set;
  2020. module_inst->e->running_mode = running_mode;
  2021. if (running_mode == Mode_Interp) {
  2022. /* Do nothing for Mode_Interp */
  2023. }
  2024. else if (running_mode == Mode_Fast_JIT) {
  2025. /* Do nothing for Mode_Fast_JIT since
  2026. module_inst->fast_jit_func_ptrs is same as
  2027. module->fast_jit_func_ptrs */
  2028. }
  2029. #if WASM_ENABLE_JIT != 0
  2030. else if (running_mode == Mode_LLVM_JIT) {
  2031. /* Set defined function pointers */
  2032. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  2033. sizeof(void *) * module->function_count, module->func_ptrs,
  2034. sizeof(void *) * module->function_count);
  2035. }
  2036. #endif
  2037. else {
  2038. bh_assert(0);
  2039. }
  2040. #else /* Possible multi-tier JIT */
  2041. os_mutex_lock(&module->instance_list_lock);
  2042. module_inst->e->running_mode = running_mode;
  2043. if (running_mode == Mode_Interp) {
  2044. /* Do nothing for Mode_Interp */
  2045. }
  2046. #if WASM_ENABLE_FAST_JIT != 0
  2047. else if (running_mode == Mode_Fast_JIT) {
  2048. JitGlobals *jit_globals = jit_compiler_get_jit_globals();
  2049. uint32 i;
  2050. /* Allocate memory for fast_jit_func_ptrs if needed */
  2051. if (!module_inst->fast_jit_func_ptrs
  2052. || module_inst->fast_jit_func_ptrs == module->fast_jit_func_ptrs) {
  2053. uint64 total_size = (uint64)sizeof(void *) * module->function_count;
  2054. if (!(module_inst->fast_jit_func_ptrs =
  2055. runtime_malloc(total_size, NULL, 0))) {
  2056. os_mutex_unlock(&module->instance_list_lock);
  2057. return false;
  2058. }
  2059. }
  2060. for (i = 0; i < module->function_count; i++) {
  2061. if (module->functions[i]->fast_jit_jitted_code) {
  2062. /* current fast jit function has been compiled */
  2063. module_inst->fast_jit_func_ptrs[i] =
  2064. module->functions[i]->fast_jit_jitted_code;
  2065. }
  2066. else {
  2067. module_inst->fast_jit_func_ptrs[i] =
  2068. jit_globals->compile_fast_jit_and_then_call;
  2069. }
  2070. }
  2071. }
  2072. #endif
  2073. #if WASM_ENABLE_JIT != 0
  2074. else if (running_mode == Mode_LLVM_JIT) {
  2075. void **llvm_jit_func_ptrs;
  2076. uint32 i;
  2077. /* Notify backend threads to start llvm jit compilation */
  2078. module->enable_llvm_jit_compilation = true;
  2079. /* Wait until llvm jit finishes initialization */
  2080. os_mutex_lock(&module->tierup_wait_lock);
  2081. while (!module->llvm_jit_inited) {
  2082. os_cond_reltimedwait(&module->tierup_wait_cond,
  2083. &module->tierup_wait_lock, 10000);
  2084. if (module->orcjit_stop_compiling) {
  2085. /* init_llvm_jit_functions_stage2 failed */
  2086. os_mutex_unlock(&module->tierup_wait_lock);
  2087. os_mutex_unlock(&module->instance_list_lock);
  2088. return false;
  2089. }
  2090. }
  2091. os_mutex_unlock(&module->tierup_wait_lock);
  2092. llvm_jit_func_ptrs =
  2093. module_inst->func_ptrs + module->import_function_count;
  2094. for (i = 0; i < module->function_count; i++) {
  2095. llvm_jit_func_ptrs[i] = module->functions[i]->llvm_jit_func_ptr;
  2096. }
  2097. }
  2098. #endif
  2099. else if (running_mode == Mode_Multi_Tier_JIT) {
  2100. /* Notify backend threads to start llvm jit compilation */
  2101. module->enable_llvm_jit_compilation = true;
  2102. /* Free fast_jit_func_ptrs if it is allocated before */
  2103. if (module_inst->fast_jit_func_ptrs
  2104. && module_inst->fast_jit_func_ptrs != module->fast_jit_func_ptrs) {
  2105. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  2106. }
  2107. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  2108. /* Copy all llvm jit func ptrs from the module */
  2109. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  2110. sizeof(void *) * module->function_count, module->func_ptrs,
  2111. sizeof(void *) * module->function_count);
  2112. }
  2113. else {
  2114. bh_assert(0);
  2115. }
  2116. /* Add module instance into module's instance list if not added */
  2117. if (first_time_set) {
  2118. bool found = false;
  2119. WASMModuleInstance *node = module->instance_list;
  2120. while (node) {
  2121. if (node == module_inst) {
  2122. found = true;
  2123. break;
  2124. }
  2125. node = node->e->next;
  2126. }
  2127. if (!found) {
  2128. module_inst->e->next = module->instance_list;
  2129. module->instance_list = module_inst;
  2130. }
  2131. }
  2132. os_mutex_unlock(&module->instance_list_lock);
  2133. #endif /* end of !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2134. && WASM_ENABLE_LAZY_JIT != 0) */
  2135. (void)module;
  2136. return true;
  2137. }
  2138. bool
  2139. wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode)
  2140. {
  2141. return set_running_mode(module_inst, running_mode, false);
  2142. }
  2143. /**
  2144. * Instantiate module
  2145. */
  2146. WASMModuleInstance *
  2147. wasm_instantiate(WASMModule *module, WASMModuleInstance *parent,
  2148. WASMExecEnv *exec_env_main, uint32 stack_size,
  2149. uint32 heap_size, uint32 max_memory_pages, char *error_buf,
  2150. uint32 error_buf_size)
  2151. {
  2152. WASMModuleInstance *module_inst;
  2153. WASMGlobalInstance *globals = NULL, *global;
  2154. WASMTableInstance *first_table;
  2155. uint32 global_count, i;
  2156. uint32 length, extra_info_offset;
  2157. mem_offset_t base_offset;
  2158. uint32 module_inst_struct_size =
  2159. offsetof(WASMModuleInstance, global_table_data.bytes);
  2160. uint64 module_inst_mem_inst_size;
  2161. uint64 total_size, table_size = 0;
  2162. uint8 *global_data, *global_data_end;
  2163. #if WASM_ENABLE_MULTI_MODULE != 0
  2164. bool ret = false;
  2165. #endif
  2166. const bool is_sub_inst = parent != NULL;
  2167. if (!module)
  2168. return NULL;
  2169. /* Check the heap size */
  2170. heap_size = align_uint(heap_size, 8);
  2171. if (heap_size > APP_HEAP_SIZE_MAX)
  2172. heap_size = APP_HEAP_SIZE_MAX;
  2173. module_inst_mem_inst_size =
  2174. sizeof(WASMMemoryInstance)
  2175. * ((uint64)module->import_memory_count + module->memory_count);
  2176. #if WASM_ENABLE_JIT != 0
  2177. /* If the module doesn't have memory, reserve one mem_info space
  2178. with empty content to align with llvm jit compiler */
  2179. if (module_inst_mem_inst_size == 0)
  2180. module_inst_mem_inst_size = (uint64)sizeof(WASMMemoryInstance);
  2181. #endif
  2182. /* Size of module inst, memory instances and global data */
  2183. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  2184. + module->global_data_size;
  2185. /* Calculate the size of table data */
  2186. for (i = 0; i < module->import_table_count; i++) {
  2187. WASMTableImport *import_table = &module->import_tables[i].u.table;
  2188. table_size += offsetof(WASMTableInstance, elems);
  2189. #if WASM_ENABLE_MULTI_MODULE != 0
  2190. table_size += (uint64)sizeof(table_elem_type_t)
  2191. * import_table->table_type.max_size;
  2192. #else
  2193. table_size += (uint64)sizeof(table_elem_type_t)
  2194. * (import_table->table_type.possible_grow
  2195. ? import_table->table_type.max_size
  2196. : import_table->table_type.init_size);
  2197. #endif
  2198. }
  2199. for (i = 0; i < module->table_count; i++) {
  2200. WASMTable *table = module->tables + i;
  2201. table_size += offsetof(WASMTableInstance, elems);
  2202. #if WASM_ENABLE_MULTI_MODULE != 0
  2203. table_size +=
  2204. (uint64)sizeof(table_elem_type_t) * table->table_type.max_size;
  2205. #else
  2206. table_size +=
  2207. (uint64)sizeof(table_elem_type_t)
  2208. * (table->table_type.possible_grow ? table->table_type.max_size
  2209. : table->table_type.init_size);
  2210. #endif
  2211. }
  2212. total_size += table_size;
  2213. /* The offset of WASMModuleInstanceExtra, make it 8-byte aligned */
  2214. total_size = (total_size + 7LL) & ~7LL;
  2215. extra_info_offset = (uint32)total_size;
  2216. total_size += sizeof(WASMModuleInstanceExtra);
  2217. /* Allocate the memory for module instance with memory instances,
  2218. global data, table data appended at the end */
  2219. if (!(module_inst =
  2220. runtime_malloc(total_size, error_buf, error_buf_size))) {
  2221. return NULL;
  2222. }
  2223. module_inst->module_type = Wasm_Module_Bytecode;
  2224. module_inst->module = module;
  2225. module_inst->e =
  2226. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  2227. #if WASM_ENABLE_MULTI_MODULE != 0
  2228. module_inst->e->sub_module_inst_list =
  2229. &module_inst->e->sub_module_inst_list_head;
  2230. ret = wasm_runtime_sub_module_instantiate(
  2231. (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst,
  2232. stack_size, heap_size, max_memory_pages, error_buf, error_buf_size);
  2233. if (!ret) {
  2234. LOG_DEBUG("build a sub module list failed");
  2235. goto fail;
  2236. }
  2237. #endif
  2238. #if WASM_ENABLE_BULK_MEMORY != 0
  2239. if (module->data_seg_count > 0) {
  2240. module_inst->e->common.data_dropped =
  2241. bh_bitmap_new(0, module->data_seg_count);
  2242. if (module_inst->e->common.data_dropped == NULL) {
  2243. LOG_DEBUG("failed to allocate bitmaps");
  2244. set_error_buf(error_buf, error_buf_size,
  2245. "failed to allocate bitmaps");
  2246. goto fail;
  2247. }
  2248. for (i = 0; i < module->data_seg_count; i++) {
  2249. if (!module->data_segments[i]->is_passive)
  2250. bh_bitmap_set_bit(module_inst->e->common.data_dropped, i);
  2251. }
  2252. }
  2253. #endif
  2254. #if WASM_ENABLE_REF_TYPES != 0
  2255. if (module->table_seg_count > 0) {
  2256. module_inst->e->common.elem_dropped =
  2257. bh_bitmap_new(0, module->table_seg_count);
  2258. if (module_inst->e->common.elem_dropped == NULL) {
  2259. LOG_DEBUG("failed to allocate bitmaps");
  2260. set_error_buf(error_buf, error_buf_size,
  2261. "failed to allocate bitmaps");
  2262. goto fail;
  2263. }
  2264. for (i = 0; i < module->table_seg_count; i++) {
  2265. if (wasm_elem_is_active(module->table_segments[i].mode)
  2266. || wasm_elem_is_declarative(module->table_segments[i].mode))
  2267. bh_bitmap_set_bit(module_inst->e->common.elem_dropped, i);
  2268. }
  2269. }
  2270. #endif
  2271. #if WASM_ENABLE_GC != 0
  2272. if (!is_sub_inst) {
  2273. uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default();
  2274. if (gc_heap_size < GC_HEAP_SIZE_MIN)
  2275. gc_heap_size = GC_HEAP_SIZE_MIN;
  2276. if (gc_heap_size > GC_HEAP_SIZE_MAX)
  2277. gc_heap_size = GC_HEAP_SIZE_MAX;
  2278. module_inst->e->common.gc_heap_pool =
  2279. runtime_malloc(gc_heap_size, error_buf, error_buf_size);
  2280. if (!module_inst->e->common.gc_heap_pool)
  2281. goto fail;
  2282. module_inst->e->common.gc_heap_handle = mem_allocator_create(
  2283. module_inst->e->common.gc_heap_pool, gc_heap_size);
  2284. if (!module_inst->e->common.gc_heap_handle)
  2285. goto fail;
  2286. }
  2287. #endif
  2288. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2289. if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector),
  2290. error_buf, error_buf_size))) {
  2291. goto fail;
  2292. }
  2293. #endif
  2294. /* Instantiate global firstly to get the mutable data size */
  2295. global_count = module->import_global_count + module->global_count;
  2296. if (global_count
  2297. && !(globals = globals_instantiate(module, module_inst, error_buf,
  2298. error_buf_size))) {
  2299. goto fail;
  2300. }
  2301. module_inst->e->global_count = global_count;
  2302. module_inst->e->globals = globals;
  2303. module_inst->global_data = (uint8 *)module_inst + module_inst_struct_size
  2304. + module_inst_mem_inst_size;
  2305. module_inst->global_data_size = module->global_data_size;
  2306. first_table = (WASMTableInstance *)(module_inst->global_data
  2307. + module->global_data_size);
  2308. module_inst->memory_count =
  2309. module->import_memory_count + module->memory_count;
  2310. module_inst->table_count = module->import_table_count + module->table_count;
  2311. module_inst->e->function_count =
  2312. module->import_function_count + module->function_count;
  2313. #if WASM_ENABLE_TAGS != 0
  2314. module_inst->e->tag_count = module->import_tag_count + module->tag_count;
  2315. #endif
  2316. /* export */
  2317. module_inst->export_func_count = get_export_count(module, EXPORT_KIND_FUNC);
  2318. #if WASM_ENABLE_MULTI_MEMORY != 0
  2319. module_inst->export_memory_count =
  2320. get_export_count(module, EXPORT_KIND_MEMORY);
  2321. #endif
  2322. #if WASM_ENABLE_MULTI_MODULE != 0
  2323. module_inst->export_table_count =
  2324. get_export_count(module, EXPORT_KIND_TABLE);
  2325. #if WASM_ENABLE_TAGS != 0
  2326. module_inst->e->export_tag_count =
  2327. get_export_count(module, EXPORT_KIND_TAG);
  2328. #endif
  2329. module_inst->export_global_count =
  2330. get_export_count(module, EXPORT_KIND_GLOBAL);
  2331. #endif
  2332. /* Instantiate memories/tables/functions/tags */
  2333. if ((module_inst->memory_count > 0
  2334. && !(module_inst->memories = memories_instantiate(
  2335. module, module_inst, parent, heap_size, max_memory_pages,
  2336. error_buf, error_buf_size)))
  2337. || (module_inst->table_count > 0
  2338. && !(module_inst->tables =
  2339. tables_instantiate(module, module_inst, first_table,
  2340. error_buf, error_buf_size)))
  2341. || (module_inst->e->function_count > 0
  2342. && !(module_inst->e->functions = functions_instantiate(
  2343. module, module_inst, error_buf, error_buf_size)))
  2344. || (module_inst->export_func_count > 0
  2345. && !(module_inst->export_functions = export_functions_instantiate(
  2346. module, module_inst, module_inst->export_func_count,
  2347. error_buf, error_buf_size)))
  2348. #if WASM_ENABLE_TAGS != 0
  2349. || (module_inst->e->tag_count > 0
  2350. && !(module_inst->e->tags = tags_instantiate(
  2351. module, module_inst, error_buf, error_buf_size)))
  2352. || (module_inst->e->export_tag_count > 0
  2353. && !(module_inst->e->export_tags = export_tags_instantiate(
  2354. module, module_inst, module_inst->e->export_tag_count,
  2355. error_buf, error_buf_size)))
  2356. #endif
  2357. #if WASM_ENABLE_MULTI_MODULE != 0
  2358. || (module_inst->export_global_count > 0
  2359. && !(module_inst->export_globals = export_globals_instantiate(
  2360. module, module_inst, module_inst->export_global_count,
  2361. error_buf, error_buf_size)))
  2362. #endif
  2363. #if WASM_ENABLE_MULTI_MEMORY != 0
  2364. || (module_inst->export_memory_count > 0
  2365. && !(module_inst->export_memories = export_memories_instantiate(
  2366. module, module_inst, module_inst->export_memory_count,
  2367. error_buf, error_buf_size)))
  2368. #endif
  2369. #if WASM_ENABLE_JIT != 0
  2370. || (module_inst->e->function_count > 0
  2371. && !init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  2372. #endif
  2373. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  2374. || (module_inst->e->function_count > 0
  2375. && !init_func_type_indexes(module_inst, error_buf, error_buf_size))
  2376. #endif
  2377. ) {
  2378. goto fail;
  2379. }
  2380. if (global_count > 0) {
  2381. /* Initialize the global data */
  2382. global_data = module_inst->global_data;
  2383. global_data_end = global_data + module->global_data_size;
  2384. global = globals;
  2385. for (i = 0; i < global_count; i++, global++) {
  2386. switch (global->type) {
  2387. case VALUE_TYPE_I32:
  2388. case VALUE_TYPE_F32:
  2389. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2390. case VALUE_TYPE_FUNCREF:
  2391. case VALUE_TYPE_EXTERNREF:
  2392. #endif
  2393. *(int32 *)global_data = global->initial_value.i32;
  2394. global_data += sizeof(int32);
  2395. break;
  2396. case VALUE_TYPE_I64:
  2397. case VALUE_TYPE_F64:
  2398. bh_memcpy_s(global_data,
  2399. (uint32)(global_data_end - global_data),
  2400. &global->initial_value.i64, sizeof(int64));
  2401. global_data += sizeof(int64);
  2402. break;
  2403. #if WASM_ENABLE_SIMD != 0
  2404. case VALUE_TYPE_V128:
  2405. bh_memcpy_s(global_data, (uint32)sizeof(V128),
  2406. &global->initial_value.v128, sizeof(V128));
  2407. global_data += sizeof(V128);
  2408. break;
  2409. #endif
  2410. #if WASM_ENABLE_GC != 0
  2411. case VALUE_TYPE_EXTERNREF:
  2412. /* the initial value should be a null reference */
  2413. bh_assert(global->initial_value.gc_obj == NULL_REF);
  2414. STORE_PTR((void **)global_data, NULL_REF);
  2415. global_data += sizeof(void *);
  2416. break;
  2417. #endif
  2418. default:
  2419. {
  2420. #if WASM_ENABLE_GC != 0
  2421. InitializerExpression *global_init = NULL;
  2422. bh_assert(wasm_is_type_reftype(global->type));
  2423. if (i >= module->import_global_count) {
  2424. global_init =
  2425. &module->globals[i - module->import_global_count]
  2426. .init_expr;
  2427. }
  2428. if (global->type == REF_TYPE_NULLFUNCREF
  2429. || global->type == REF_TYPE_NULLEXTERNREF
  2430. || global->type == REF_TYPE_NULLREF) {
  2431. STORE_PTR((void **)global_data, NULL_REF);
  2432. global_data += sizeof(void *);
  2433. break;
  2434. }
  2435. /* We can't create funcref obj during global instantiation
  2436. * since the functions are not instantiated yet, so we need
  2437. * to defer the initialization here */
  2438. if (global_init
  2439. && (global_init->init_expr_type
  2440. == INIT_EXPR_TYPE_FUNCREF_CONST)
  2441. && wasm_reftype_is_subtype_of(
  2442. global->type, global->ref_type, REF_TYPE_FUNCREF,
  2443. NULL, module_inst->module->types,
  2444. module_inst->module->type_count)) {
  2445. WASMFuncObjectRef func_obj = NULL;
  2446. /* UINT32_MAX indicates that it is a null reference */
  2447. if ((uint32)global->initial_value.i32 != UINT32_MAX) {
  2448. if (!(func_obj = wasm_create_func_obj(
  2449. module_inst, global->initial_value.i32,
  2450. false, error_buf, error_buf_size)))
  2451. goto fail;
  2452. }
  2453. STORE_PTR((void **)global_data, func_obj);
  2454. global_data += sizeof(void *);
  2455. /* Also update the initial_value since other globals may
  2456. * refer to this */
  2457. global->initial_value.gc_obj = (wasm_obj_t)func_obj;
  2458. break;
  2459. }
  2460. else {
  2461. STORE_PTR((void **)global_data,
  2462. global->initial_value.gc_obj);
  2463. global_data += sizeof(void *);
  2464. break;
  2465. }
  2466. #endif
  2467. bh_assert(0);
  2468. break;
  2469. }
  2470. }
  2471. }
  2472. bh_assert(global_data == global_data_end);
  2473. }
  2474. if (!check_linked_symbol(module_inst, error_buf, error_buf_size)) {
  2475. goto fail;
  2476. }
  2477. /* Initialize the memory data with data segment section */
  2478. for (i = 0; i < module->data_seg_count; i++) {
  2479. WASMMemoryInstance *memory = NULL;
  2480. uint8 *memory_data = NULL;
  2481. uint64 memory_size = 0;
  2482. WASMDataSeg *data_seg = module->data_segments[i];
  2483. WASMValue offset_value;
  2484. #if WASM_ENABLE_BULK_MEMORY != 0
  2485. if (data_seg->is_passive)
  2486. continue;
  2487. #endif
  2488. if (is_sub_inst)
  2489. /* Ignore setting memory init data if the memory has been
  2490. initialized */
  2491. continue;
  2492. /* has check it in loader */
  2493. memory = module_inst->memories[data_seg->memory_index];
  2494. bh_assert(memory);
  2495. memory_data = memory->memory_data;
  2496. memory_size =
  2497. (uint64)memory->num_bytes_per_page * memory->cur_page_count;
  2498. bh_assert(memory_data || memory_size == 0);
  2499. uint8 offset_flag = data_seg->base_offset.init_expr_type;
  2500. bh_assert(offset_flag == INIT_EXPR_TYPE_GET_GLOBAL
  2501. || (memory->is_memory64 ? is_valid_i64_offset(offset_flag)
  2502. : is_valid_i32_offset(offset_flag)));
  2503. if (!get_init_value_recursive(module, &data_seg->base_offset, globals,
  2504. &offset_value, error_buf,
  2505. error_buf_size)) {
  2506. goto fail;
  2507. }
  2508. if (offset_flag == INIT_EXPR_TYPE_GET_GLOBAL) {
  2509. if (!globals
  2510. || globals[data_seg->base_offset.u.unary.v.global_index].type
  2511. != (memory->is_memory64 ? VALUE_TYPE_I64
  2512. : VALUE_TYPE_I32)) {
  2513. set_error_buf(error_buf, error_buf_size,
  2514. "data segment does not fit");
  2515. goto fail;
  2516. }
  2517. }
  2518. #if WASM_ENABLE_MEMORY64 != 0
  2519. if (memory->is_memory64) {
  2520. base_offset = (uint64)offset_value.i64;
  2521. }
  2522. else
  2523. #endif
  2524. {
  2525. base_offset = (uint32)offset_value.i32;
  2526. }
  2527. /* check offset */
  2528. if (base_offset > memory_size) {
  2529. #if WASM_ENABLE_MEMORY64 != 0
  2530. LOG_DEBUG("base_offset(%" PRIu64 ") > memory_size(%" PRIu64 ")",
  2531. base_offset, memory_size);
  2532. #else
  2533. LOG_DEBUG("base_offset(%u) > memory_size(%" PRIu64 ")", base_offset,
  2534. memory_size);
  2535. #endif
  2536. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2537. set_error_buf(error_buf, error_buf_size,
  2538. "out of bounds memory access");
  2539. #else
  2540. set_error_buf(error_buf, error_buf_size,
  2541. "data segment does not fit");
  2542. #endif
  2543. goto fail;
  2544. }
  2545. /* check offset + length(could be zero) */
  2546. length = data_seg->data_length;
  2547. if ((uint64)base_offset + length > memory_size) {
  2548. #if WASM_ENABLE_MEMORY64 != 0
  2549. LOG_DEBUG("base_offset(%" PRIu64
  2550. ") + length(%d) > memory_size(%" PRIu64 ")",
  2551. base_offset, length, memory_size);
  2552. #else
  2553. LOG_DEBUG("base_offset(%u) + length(%d) > memory_size(%" PRIu64 ")",
  2554. base_offset, length, memory_size);
  2555. #endif
  2556. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2557. set_error_buf(error_buf, error_buf_size,
  2558. "out of bounds memory access");
  2559. #else
  2560. set_error_buf(error_buf, error_buf_size,
  2561. "data segment does not fit");
  2562. #endif
  2563. goto fail;
  2564. }
  2565. if (memory_data) {
  2566. bh_memcpy_s(memory_data + base_offset,
  2567. (uint32)(memory_size - base_offset), data_seg->data,
  2568. length);
  2569. }
  2570. }
  2571. #if WASM_ENABLE_JIT != 0 && WASM_ENABLE_SHARED_HEAP != 0
  2572. #if UINTPTR_MAX == UINT64_MAX
  2573. module_inst->e->shared_heap_start_off.u64 = UINT64_MAX;
  2574. #else
  2575. module_inst->e->shared_heap_start_off.u32[0] = UINT32_MAX;
  2576. #endif
  2577. module_inst->e->shared_heap = NULL;
  2578. #endif
  2579. #if WASM_ENABLE_GC != 0
  2580. /* Initialize the table data with init expr */
  2581. for (i = 0; i < module->table_count; i++) {
  2582. WASMTable *table = module->tables + i;
  2583. WASMTableInstance *table_inst = module_inst->tables[i];
  2584. table_elem_type_t *table_data;
  2585. uint32 j;
  2586. if (table->init_expr.init_expr_type == 0) {
  2587. /* No table initializer */
  2588. continue;
  2589. }
  2590. table_data = table_inst->elems;
  2591. bh_assert(
  2592. table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL
  2593. || table->init_expr.init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST
  2594. || table->init_expr.init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST);
  2595. if (table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  2596. if (!check_global_init_expr(module,
  2597. table->init_expr.u.unary.v.global_index,
  2598. error_buf, error_buf_size)) {
  2599. goto fail;
  2600. }
  2601. table->init_expr.u.unary.v.gc_obj =
  2602. globals[table->init_expr.u.unary.v.global_index]
  2603. .initial_value.gc_obj;
  2604. }
  2605. else if (table->init_expr.init_expr_type
  2606. == INIT_EXPR_TYPE_FUNCREF_CONST) {
  2607. uint32 func_idx = table->init_expr.u.unary.v.ref_index;
  2608. if (func_idx != UINT32_MAX) {
  2609. if (!(table->init_expr.u.unary.v.gc_obj =
  2610. wasm_create_func_obj(module_inst, func_idx, false,
  2611. error_buf, error_buf_size)))
  2612. goto fail;
  2613. }
  2614. else {
  2615. table->init_expr.u.unary.v.gc_obj = NULL_REF;
  2616. }
  2617. }
  2618. else if (table->init_expr.init_expr_type
  2619. == INIT_EXPR_TYPE_REFNULL_CONST) {
  2620. table->init_expr.u.unary.v.gc_obj = NULL_REF;
  2621. }
  2622. LOG_DEBUG("Init table [%d] elements from [%d] to [%d] as: %p", i, 0,
  2623. table_inst->cur_size,
  2624. (void *)table->init_expr.u.unary.v.gc_obj);
  2625. for (j = 0; j < table_inst->cur_size; j++) {
  2626. *(table_data + j) = table->init_expr.u.unary.v.gc_obj;
  2627. }
  2628. }
  2629. #endif /* end of WASM_ENABLE_GC != 0 */
  2630. /* Initialize the table data with table segment section */
  2631. for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count;
  2632. i++) {
  2633. WASMTableSeg *table_seg = module->table_segments + i;
  2634. /* has check it in loader */
  2635. WASMTableInstance *table = module_inst->tables[table_seg->table_index];
  2636. table_elem_type_t *table_data;
  2637. WASMValue offset_value;
  2638. uint32 j;
  2639. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2640. uint8 tbl_elem_type;
  2641. uint32 tbl_init_size, tbl_max_size;
  2642. #endif
  2643. #if WASM_ENABLE_GC != 0
  2644. WASMRefType *tbl_elem_ref_type;
  2645. #endif
  2646. bh_assert(table);
  2647. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2648. (void)wasm_runtime_get_table_inst_elem_type(
  2649. (WASMModuleInstanceCommon *)module_inst, table_seg->table_index,
  2650. &tbl_elem_type,
  2651. #if WASM_ENABLE_GC != 0
  2652. &tbl_elem_ref_type,
  2653. #endif
  2654. &tbl_init_size, &tbl_max_size);
  2655. #if WASM_ENABLE_GC == 0
  2656. if (tbl_elem_type != VALUE_TYPE_FUNCREF
  2657. && tbl_elem_type != VALUE_TYPE_EXTERNREF) {
  2658. set_error_buf(error_buf, error_buf_size,
  2659. "type mismatch: elements segment does not fit");
  2660. goto fail;
  2661. }
  2662. #elif WASM_ENABLE_GC != 0
  2663. if (!wasm_elem_is_declarative(table_seg->mode)
  2664. && !wasm_reftype_is_subtype_of(
  2665. table_seg->elem_type, table_seg->elem_ref_type,
  2666. table->elem_type, table->elem_ref_type.elem_ref_type,
  2667. module->types, module->type_count)) {
  2668. set_error_buf(error_buf, error_buf_size,
  2669. "type mismatch: elements segment does not fit");
  2670. goto fail;
  2671. }
  2672. #endif
  2673. (void)tbl_init_size;
  2674. (void)tbl_max_size;
  2675. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  2676. table_data = table->elems;
  2677. #if WASM_ENABLE_MULTI_MODULE != 0
  2678. if (table_seg->table_index < module->import_table_count
  2679. && module_inst->e->table_insts_linked[table_seg->table_index]) {
  2680. table_data =
  2681. module_inst->e->table_insts_linked[table_seg->table_index]
  2682. ->elems;
  2683. }
  2684. #endif
  2685. bh_assert(table_data);
  2686. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2687. if (!wasm_elem_is_active(table_seg->mode))
  2688. continue;
  2689. #endif
  2690. uint8 offset_flag = table_seg->base_offset.init_expr_type;
  2691. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2692. bh_assert(offset_flag == INIT_EXPR_TYPE_GET_GLOBAL
  2693. || offset_flag == INIT_EXPR_TYPE_FUNCREF_CONST
  2694. || offset_flag == INIT_EXPR_TYPE_REFNULL_CONST
  2695. || is_valid_i32_offset(offset_flag));
  2696. #else
  2697. bh_assert(offset_flag == INIT_EXPR_TYPE_GET_GLOBAL
  2698. || is_valid_i32_offset(offset_flag));
  2699. #endif
  2700. if (!get_init_value_recursive(module, &table_seg->base_offset, globals,
  2701. &offset_value, error_buf,
  2702. error_buf_size)) {
  2703. goto fail;
  2704. }
  2705. if (offset_flag == INIT_EXPR_TYPE_GET_GLOBAL) {
  2706. if (!globals
  2707. || globals[table_seg->base_offset.u.unary.v.global_index].type
  2708. != VALUE_TYPE_I32) {
  2709. set_error_buf(error_buf, error_buf_size,
  2710. "type mismatch: elements segment does not fit");
  2711. goto fail;
  2712. }
  2713. }
  2714. /* check offset since length might negative */
  2715. if ((uint32)offset_value.i32 > table->cur_size) {
  2716. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)", offset_value.i32,
  2717. table->cur_size);
  2718. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2719. set_error_buf(error_buf, error_buf_size,
  2720. "out of bounds table access");
  2721. #else
  2722. set_error_buf(error_buf, error_buf_size,
  2723. "type mismatch: elements segment does not fit");
  2724. #endif
  2725. goto fail;
  2726. }
  2727. /* check offset + length(could be zero) */
  2728. length = table_seg->value_count;
  2729. if ((uint32)offset_value.i32 + length > table->cur_size) {
  2730. LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)",
  2731. offset_value.i32, length, table->cur_size);
  2732. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2733. set_error_buf(error_buf, error_buf_size,
  2734. "out of bounds table access");
  2735. #else
  2736. set_error_buf(error_buf, error_buf_size,
  2737. "type mismatch: elements segment does not fit");
  2738. #endif
  2739. goto fail;
  2740. }
  2741. for (j = 0; j < length; j++) {
  2742. InitializerExpression *init_expr = &table_seg->init_values[j];
  2743. uint8 flag = init_expr->init_expr_type;
  2744. void *ref = NULL;
  2745. /* const and get global init values should be resolved during
  2746. * loading */
  2747. bh_assert((flag == INIT_EXPR_TYPE_GET_GLOBAL)
  2748. || (flag == INIT_EXPR_TYPE_REFNULL_CONST)
  2749. || ((flag >= INIT_EXPR_TYPE_FUNCREF_CONST)
  2750. && (flag <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY)));
  2751. switch (flag) {
  2752. case INIT_EXPR_TYPE_REFNULL_CONST:
  2753. ref = NULL;
  2754. break;
  2755. case INIT_EXPR_TYPE_FUNCREF_CONST:
  2756. {
  2757. #if WASM_ENABLE_GC == 0
  2758. ref = (void *)(uintptr_t)init_expr->u.unary.v.ref_index;
  2759. #else
  2760. WASMFuncObjectRef func_obj;
  2761. uint32 func_idx = init_expr->u.unary.v.ref_index;
  2762. /* UINT32_MAX indicates that it is a null reference */
  2763. if (func_idx != UINT32_MAX) {
  2764. if (!(func_obj = wasm_create_func_obj(
  2765. module_inst, func_idx, false, error_buf,
  2766. error_buf_size))) {
  2767. goto fail;
  2768. }
  2769. ref = func_obj;
  2770. }
  2771. else {
  2772. ref = NULL_REF;
  2773. }
  2774. #endif /* end of WASM_ENABLE_GC != 0 */
  2775. break;
  2776. }
  2777. #if WASM_ENABLE_GC != 0
  2778. case INIT_EXPR_TYPE_GET_GLOBAL:
  2779. {
  2780. if (!check_global_init_expr(
  2781. module, init_expr->u.unary.v.global_index,
  2782. error_buf, error_buf_size)) {
  2783. goto fail;
  2784. }
  2785. ref = globals[init_expr->u.unary.v.global_index]
  2786. .initial_value.gc_obj;
  2787. break;
  2788. }
  2789. case INIT_EXPR_TYPE_STRUCT_NEW:
  2790. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  2791. {
  2792. WASMRttType *rtt_type;
  2793. WASMStructObjectRef struct_obj;
  2794. WASMStructType *struct_type;
  2795. WASMStructNewInitValues *init_values = NULL;
  2796. uint32 type_idx;
  2797. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  2798. init_values = (WASMStructNewInitValues *)
  2799. init_expr->u.unary.v.data;
  2800. type_idx = init_values->type_idx;
  2801. }
  2802. else {
  2803. type_idx = init_expr->u.unary.v.type_index;
  2804. }
  2805. struct_type = (WASMStructType *)module->types[type_idx];
  2806. if (!(rtt_type = wasm_rtt_type_new(
  2807. (WASMType *)struct_type, type_idx,
  2808. module->rtt_types, module->type_count,
  2809. &module->rtt_type_lock))) {
  2810. set_error_buf(error_buf, error_buf_size,
  2811. "create rtt object failed");
  2812. goto fail;
  2813. }
  2814. if (!(struct_obj = wasm_struct_obj_new_internal(
  2815. module_inst->e->common.gc_heap_handle,
  2816. rtt_type))) {
  2817. set_error_buf(error_buf, error_buf_size,
  2818. "create struct object failed");
  2819. goto fail;
  2820. }
  2821. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  2822. uint32 field_idx;
  2823. bh_assert(init_values->count
  2824. == struct_type->field_count);
  2825. for (field_idx = 0; field_idx < init_values->count;
  2826. field_idx++) {
  2827. wasm_struct_obj_set_field(
  2828. struct_obj, field_idx,
  2829. &init_values->fields[field_idx]);
  2830. }
  2831. }
  2832. ref = struct_obj;
  2833. break;
  2834. }
  2835. case INIT_EXPR_TYPE_ARRAY_NEW:
  2836. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  2837. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  2838. {
  2839. WASMRttType *rtt_type;
  2840. WASMArrayObjectRef array_obj;
  2841. WASMArrayType *array_type;
  2842. WASMArrayNewInitValues *init_values = NULL;
  2843. WASMValue *arr_init_val = NULL, empty_val = { 0 };
  2844. uint32 type_idx, len;
  2845. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  2846. type_idx =
  2847. init_expr->u.unary.v.array_new_default.type_index;
  2848. len = init_expr->u.unary.v.array_new_default.length;
  2849. arr_init_val = &empty_val;
  2850. }
  2851. else {
  2852. init_values =
  2853. (WASMArrayNewInitValues *)init_expr->u.unary.v.data;
  2854. type_idx = init_values->type_idx;
  2855. len = init_values->length;
  2856. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  2857. arr_init_val = init_values->elem_data;
  2858. }
  2859. }
  2860. array_type = (WASMArrayType *)module->types[type_idx];
  2861. if (!(rtt_type = wasm_rtt_type_new(
  2862. (WASMType *)array_type, type_idx,
  2863. module->rtt_types, module->type_count,
  2864. &module->rtt_type_lock))) {
  2865. set_error_buf(error_buf, error_buf_size,
  2866. "create rtt object failed");
  2867. goto fail;
  2868. }
  2869. if (!(array_obj = wasm_array_obj_new_internal(
  2870. module_inst->e->common.gc_heap_handle, rtt_type,
  2871. len, arr_init_val))) {
  2872. set_error_buf(error_buf, error_buf_size,
  2873. "create array object failed");
  2874. goto fail;
  2875. }
  2876. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  2877. uint32 elem_idx;
  2878. bh_assert(init_values);
  2879. for (elem_idx = 0; elem_idx < len; elem_idx++) {
  2880. wasm_array_obj_set_elem(
  2881. array_obj, elem_idx,
  2882. &init_values->elem_data[elem_idx]);
  2883. }
  2884. }
  2885. ref = array_obj;
  2886. break;
  2887. }
  2888. case INIT_EXPR_TYPE_I31_NEW:
  2889. {
  2890. ref =
  2891. (wasm_obj_t)wasm_i31_obj_new(init_expr->u.unary.v.i32);
  2892. break;
  2893. }
  2894. #endif /* end of WASM_ENABLE_GC != 0 */
  2895. }
  2896. *(table_data + offset_value.i32 + j) = (table_elem_type_t)ref;
  2897. }
  2898. }
  2899. /* Initialize the thread related data */
  2900. if (stack_size == 0)
  2901. stack_size = DEFAULT_WASM_STACK_SIZE;
  2902. module_inst->default_wasm_stack_size = stack_size;
  2903. if (module->malloc_function != (uint32)-1) {
  2904. module_inst->e->malloc_function =
  2905. &module_inst->e->functions[module->malloc_function];
  2906. }
  2907. if (module->free_function != (uint32)-1) {
  2908. module_inst->e->free_function =
  2909. &module_inst->e->functions[module->free_function];
  2910. }
  2911. if (module->retain_function != (uint32)-1) {
  2912. module_inst->e->retain_function =
  2913. &module_inst->e->functions[module->retain_function];
  2914. }
  2915. #if WASM_ENABLE_LIBC_WASI != 0
  2916. /* The sub-instance will get the wasi_ctx from main-instance */
  2917. if (!is_sub_inst) {
  2918. if (!wasm_runtime_init_wasi(
  2919. (WASMModuleInstanceCommon *)module_inst,
  2920. module->wasi_args.dir_list, module->wasi_args.dir_count,
  2921. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  2922. module->wasi_args.env, module->wasi_args.env_count,
  2923. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  2924. module->wasi_args.ns_lookup_pool,
  2925. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  2926. module->wasi_args.argc, module->wasi_args.stdio[0],
  2927. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  2928. error_buf, error_buf_size)) {
  2929. goto fail;
  2930. }
  2931. }
  2932. #endif
  2933. #if WASM_ENABLE_DEBUG_INTERP != 0
  2934. if (!is_sub_inst) {
  2935. /* Add module instance into module's instance list */
  2936. os_mutex_lock(&module->instance_list_lock);
  2937. if (module->instance_list) {
  2938. LOG_WARNING(
  2939. "warning: multiple instances referencing to the same module "
  2940. "may cause unexpected behaviour during debugging");
  2941. }
  2942. module_inst->e->next = module->instance_list;
  2943. module->instance_list = module_inst;
  2944. os_mutex_unlock(&module->instance_list_lock);
  2945. }
  2946. #endif
  2947. /* Set running mode before executing wasm functions */
  2948. if (!set_running_mode(module_inst, wasm_runtime_get_default_running_mode(),
  2949. true)) {
  2950. set_error_buf(error_buf, error_buf_size,
  2951. "set instance running mode failed");
  2952. goto fail;
  2953. }
  2954. if (module->start_function != (uint32)-1) {
  2955. /* TODO: fix start function can be import function issue */
  2956. if (module->start_function >= module->import_function_count)
  2957. module_inst->e->start_function =
  2958. &module_inst->e->functions[module->start_function];
  2959. }
  2960. if (!execute_post_instantiate_functions(module_inst, is_sub_inst,
  2961. exec_env_main)) {
  2962. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  2963. goto fail;
  2964. }
  2965. #if WASM_ENABLE_MEMORY_TRACING != 0
  2966. wasm_runtime_dump_module_inst_mem_consumption(
  2967. (WASMModuleInstanceCommon *)module_inst);
  2968. #endif
  2969. (void)global_data_end;
  2970. return module_inst;
  2971. fail:
  2972. wasm_deinstantiate(module_inst, false);
  2973. return NULL;
  2974. }
  2975. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2976. static void
  2977. destroy_c_api_frames(Vector *frames)
  2978. {
  2979. WASMCApiFrame frame = { 0 };
  2980. uint32 i, total_frames, ret;
  2981. total_frames = (uint32)bh_vector_size(frames);
  2982. for (i = 0; i < total_frames; i++) {
  2983. ret = bh_vector_get(frames, i, &frame);
  2984. bh_assert(ret);
  2985. if (frame.lp)
  2986. wasm_runtime_free(frame.lp);
  2987. }
  2988. ret = bh_vector_destroy(frames);
  2989. bh_assert(ret);
  2990. (void)ret;
  2991. }
  2992. #endif
  2993. void
  2994. wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst)
  2995. {
  2996. if (!module_inst)
  2997. return;
  2998. if (module_inst->exec_env_singleton) {
  2999. /* wasm_exec_env_destroy will call
  3000. wasm_cluster_wait_for_all_except_self to wait for other
  3001. threads, so as to destroy their exec_envs and module
  3002. instances first, and avoid accessing the shared resources
  3003. of current module instance after it is deinstantiated. */
  3004. wasm_exec_env_destroy(module_inst->exec_env_singleton);
  3005. }
  3006. #if WASM_ENABLE_DEBUG_INTERP != 0 \
  3007. || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  3008. && WASM_ENABLE_LAZY_JIT != 0)
  3009. /* Remove instance from module's instance list before freeing
  3010. func_ptrs and fast_jit_func_ptrs of the instance, to avoid
  3011. accessing the freed memory in the jit backend compilation
  3012. threads */
  3013. {
  3014. WASMModule *module = module_inst->module;
  3015. WASMModuleInstance *instance_prev = NULL, *instance;
  3016. os_mutex_lock(&module->instance_list_lock);
  3017. instance = module->instance_list;
  3018. while (instance) {
  3019. if (instance == module_inst) {
  3020. if (!instance_prev)
  3021. module->instance_list = instance->e->next;
  3022. else
  3023. instance_prev->e->next = instance->e->next;
  3024. break;
  3025. }
  3026. instance_prev = instance;
  3027. instance = instance->e->next;
  3028. }
  3029. os_mutex_unlock(&module->instance_list_lock);
  3030. }
  3031. #endif
  3032. #if WASM_ENABLE_JIT != 0
  3033. if (module_inst->func_ptrs)
  3034. wasm_runtime_free(module_inst->func_ptrs);
  3035. #endif
  3036. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  3037. && WASM_ENABLE_LAZY_JIT != 0
  3038. if (module_inst->fast_jit_func_ptrs
  3039. && module_inst->fast_jit_func_ptrs
  3040. != module_inst->module->fast_jit_func_ptrs)
  3041. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  3042. #endif
  3043. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  3044. if (module_inst->func_type_indexes)
  3045. wasm_runtime_free(module_inst->func_type_indexes);
  3046. #endif
  3047. #if WASM_ENABLE_MULTI_MODULE != 0
  3048. wasm_runtime_sub_module_deinstantiate(
  3049. (WASMModuleInstanceCommon *)module_inst);
  3050. #endif
  3051. if (module_inst->memory_count > 0)
  3052. memories_deinstantiate(module_inst, module_inst->memories,
  3053. module_inst->memory_count);
  3054. if (module_inst->import_func_ptrs) {
  3055. wasm_runtime_free(module_inst->import_func_ptrs);
  3056. }
  3057. tables_deinstantiate(module_inst);
  3058. functions_deinstantiate(module_inst->e->functions);
  3059. #if WASM_ENABLE_TAGS != 0
  3060. tags_deinstantiate(module_inst->e->tags, module_inst->e->import_tag_ptrs);
  3061. #endif
  3062. globals_deinstantiate(module_inst->e->globals);
  3063. export_functions_deinstantiate(module_inst->export_functions);
  3064. #if WASM_ENABLE_TAGS != 0
  3065. export_tags_deinstantiate(module_inst->e->export_tags);
  3066. #endif
  3067. #if WASM_ENABLE_MULTI_MODULE != 0
  3068. export_globals_deinstantiate(module_inst->export_globals);
  3069. #endif
  3070. #if WASM_ENABLE_MULTI_MEMORY != 0
  3071. export_memories_deinstantiate(module_inst->export_memories);
  3072. #endif
  3073. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3074. wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst);
  3075. #endif
  3076. #if WASM_ENABLE_GC != 0
  3077. if (!is_sub_inst) {
  3078. if (module_inst->e->common.gc_heap_handle)
  3079. mem_allocator_destroy(module_inst->e->common.gc_heap_handle);
  3080. if (module_inst->e->common.gc_heap_pool)
  3081. wasm_runtime_free(module_inst->e->common.gc_heap_pool);
  3082. }
  3083. #endif
  3084. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3085. if (module_inst->frames) {
  3086. destroy_c_api_frames(module_inst->frames);
  3087. wasm_runtime_free(module_inst->frames);
  3088. module_inst->frames = NULL;
  3089. }
  3090. #endif
  3091. if (module_inst->c_api_func_imports)
  3092. wasm_runtime_free(module_inst->c_api_func_imports);
  3093. if (!is_sub_inst) {
  3094. wasm_native_call_context_dtors((WASMModuleInstanceCommon *)module_inst);
  3095. }
  3096. #if WASM_ENABLE_BULK_MEMORY != 0
  3097. bh_bitmap_delete(module_inst->e->common.data_dropped);
  3098. #endif
  3099. #if WASM_ENABLE_REF_TYPES != 0
  3100. bh_bitmap_delete(module_inst->e->common.elem_dropped);
  3101. #endif
  3102. wasm_runtime_free(module_inst);
  3103. }
  3104. WASMFunctionInstance *
  3105. wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name)
  3106. {
  3107. WASMExportFuncInstance key = { .name = (char *)name };
  3108. WASMExportFuncInstance *export_func_inst;
  3109. if (!module_inst->export_functions)
  3110. return NULL;
  3111. export_func_inst = bsearch(
  3112. &key, module_inst->export_functions, module_inst->export_func_count,
  3113. sizeof(WASMExportFuncInstance), cmp_export_func_inst);
  3114. if (!export_func_inst)
  3115. return NULL;
  3116. return export_func_inst->function;
  3117. }
  3118. WASMMemoryInstance *
  3119. wasm_lookup_memory(const WASMModuleInstance *module_inst, const char *name)
  3120. {
  3121. #if WASM_ENABLE_MULTI_MEMORY != 0
  3122. uint32 i;
  3123. for (i = 0; i < module_inst->export_memory_count; i++)
  3124. if (!strcmp(module_inst->export_memories[i].name, name))
  3125. return module_inst->export_memories[i].memory;
  3126. return NULL;
  3127. #else
  3128. (void)module_inst->export_memories;
  3129. if (!module_inst->memories)
  3130. return NULL;
  3131. return module_inst->memories[0];
  3132. #endif
  3133. }
  3134. #if WASM_ENABLE_MULTI_MODULE != 0
  3135. WASMGlobalInstance *
  3136. wasm_lookup_global(const WASMModuleInstance *module_inst, const char *name)
  3137. {
  3138. uint32 i;
  3139. for (i = 0; i < module_inst->export_global_count; i++)
  3140. if (!strcmp(module_inst->export_globals[i].name, name))
  3141. return module_inst->export_globals[i].global;
  3142. return NULL;
  3143. }
  3144. WASMTableInstance *
  3145. wasm_lookup_table(const WASMModuleInstance *module_inst, const char *name)
  3146. {
  3147. /**
  3148. * using a strong assumption that one module instance only has
  3149. * one table instance
  3150. */
  3151. (void)module_inst->export_tables;
  3152. return module_inst->tables[0];
  3153. }
  3154. #if WASM_ENABLE_TAGS != 0
  3155. WASMTagInstance *
  3156. wasm_lookup_tag(const WASMModuleInstance *module_inst, const char *name,
  3157. const char *signature)
  3158. {
  3159. uint32 i;
  3160. for (i = 0; i < module_inst->e->export_tag_count; i++)
  3161. if (!strcmp(module_inst->e->export_tags[i].name, name))
  3162. return module_inst->e->export_tags[i].tag;
  3163. (void)signature;
  3164. return NULL;
  3165. }
  3166. #endif
  3167. #endif
  3168. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3169. static void
  3170. call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst,
  3171. WASMExecEnv *exec_env,
  3172. WASMFunctionInstance *function, unsigned argc,
  3173. uint32 argv[])
  3174. {
  3175. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  3176. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  3177. WASMRuntimeFrame *prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  3178. uint8 *prev_top = exec_env->wasm_stack.top;
  3179. #ifdef BH_PLATFORM_WINDOWS
  3180. int result;
  3181. bool has_exception;
  3182. char exception[EXCEPTION_BUF_LEN];
  3183. #endif
  3184. bool ret = true;
  3185. if (!exec_env_tls) {
  3186. if (!os_thread_signal_inited()) {
  3187. wasm_set_exception(module_inst, "thread signal env not inited");
  3188. return;
  3189. }
  3190. /* Set thread handle and stack boundary if they haven't been set */
  3191. wasm_exec_env_set_thread_info(exec_env);
  3192. wasm_runtime_set_exec_env_tls(exec_env);
  3193. }
  3194. else {
  3195. if (exec_env_tls != exec_env) {
  3196. wasm_set_exception(module_inst, "invalid exec env");
  3197. return;
  3198. }
  3199. }
  3200. /* Check native stack overflow firstly to ensure we have enough
  3201. native stack to run the following codes before actually calling
  3202. the aot function in invokeNative function. */
  3203. if (!wasm_runtime_detect_native_stack_overflow(exec_env)) {
  3204. return;
  3205. }
  3206. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  3207. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  3208. #ifndef BH_PLATFORM_WINDOWS
  3209. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3210. #else
  3211. __try {
  3212. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3213. } __except (wasm_copy_exception(module_inst, NULL)
  3214. ? EXCEPTION_EXECUTE_HANDLER
  3215. : EXCEPTION_CONTINUE_SEARCH) {
  3216. /* Exception was thrown in wasm_exception_handler */
  3217. ret = false;
  3218. }
  3219. has_exception = wasm_copy_exception(module_inst, exception);
  3220. if (has_exception && strstr(exception, "native stack overflow")) {
  3221. /* After a stack overflow, the stack was left
  3222. in a damaged state, let the CRT repair it */
  3223. result = _resetstkoflw();
  3224. bh_assert(result != 0);
  3225. }
  3226. #endif
  3227. }
  3228. else {
  3229. /* Exception has been set in signal handler before calling longjmp */
  3230. ret = false;
  3231. }
  3232. /* Note: can't check wasm_get_exception(module_inst) here, there may be
  3233. * exception which is not caught by hardware (e.g. uninitialized elements),
  3234. * then the stack-frame is already freed inside wasm_interp_call_wasm */
  3235. if (!ret) {
  3236. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3237. if (wasm_interp_create_call_stack(exec_env)) {
  3238. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  3239. }
  3240. #endif
  3241. /* Restore operand frames */
  3242. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  3243. exec_env->wasm_stack.top = prev_top;
  3244. }
  3245. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  3246. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  3247. if (!exec_env->jmpbuf_stack_top) {
  3248. wasm_runtime_set_exec_env_tls(NULL);
  3249. }
  3250. if (!ret) {
  3251. os_sigreturn();
  3252. os_signal_unmask();
  3253. }
  3254. (void)jmpbuf_node_pop;
  3255. }
  3256. #define interp_call_wasm call_wasm_with_hw_bound_check
  3257. #else
  3258. #define interp_call_wasm wasm_interp_call_wasm
  3259. #endif
  3260. bool
  3261. wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function,
  3262. unsigned argc, uint32 argv[])
  3263. {
  3264. WASMModuleInstance *module_inst =
  3265. (WASMModuleInstance *)exec_env->module_inst;
  3266. #ifndef OS_ENABLE_HW_BOUND_CHECK
  3267. /* Set thread handle and stack boundary */
  3268. wasm_exec_env_set_thread_info(exec_env);
  3269. #else
  3270. /* Set thread info in call_wasm_with_hw_bound_check when
  3271. hw bound check is enabled */
  3272. #endif
  3273. /* Set exec env, so it can be later retrieved from instance */
  3274. module_inst->cur_exec_env = exec_env;
  3275. interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3276. return !wasm_copy_exception(module_inst, NULL);
  3277. }
  3278. #if WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0
  3279. /* look for the function name */
  3280. static char *
  3281. get_func_name_from_index(const WASMModuleInstance *inst, uint32 func_index)
  3282. {
  3283. char *func_name = NULL;
  3284. WASMFunctionInstance *func_inst = inst->e->functions + func_index;
  3285. if (func_inst->is_import_func) {
  3286. func_name = func_inst->u.func_import->field_name;
  3287. }
  3288. else {
  3289. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  3290. func_name = func_inst->u.func->field_name;
  3291. #endif
  3292. /* if custom name section is not generated,
  3293. search symbols from export table */
  3294. if (!func_name) {
  3295. unsigned j;
  3296. for (j = 0; j < inst->export_func_count; j++) {
  3297. WASMExportFuncInstance *export_func =
  3298. inst->export_functions + j;
  3299. if (export_func->function == func_inst) {
  3300. func_name = export_func->name;
  3301. break;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. return func_name;
  3307. }
  3308. #endif /*WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0*/
  3309. #if WASM_ENABLE_PERF_PROFILING != 0
  3310. void
  3311. wasm_dump_perf_profiling(const WASMModuleInstance *module_inst)
  3312. {
  3313. WASMFunctionInstance *func_inst;
  3314. char *func_name;
  3315. uint32 i;
  3316. os_printf("Performance profiler data:\n");
  3317. for (i = 0; i < module_inst->e->function_count; i++) {
  3318. func_inst = module_inst->e->functions + i;
  3319. if (func_inst->total_exec_cnt == 0)
  3320. continue;
  3321. func_name = get_func_name_from_index(module_inst, i);
  3322. if (func_name)
  3323. os_printf(
  3324. " func %s, execution time: %.3f ms, execution count: %" PRIu32
  3325. " times, children execution time: %.3f ms\n",
  3326. func_name, func_inst->total_exec_time / 1000.0f,
  3327. func_inst->total_exec_cnt,
  3328. func_inst->children_exec_time / 1000.0f);
  3329. else
  3330. os_printf(" func %" PRIu32
  3331. ", execution time: %.3f ms, execution count: %" PRIu32
  3332. " times, children execution time: %.3f ms\n",
  3333. i, func_inst->total_exec_time / 1000.0f,
  3334. func_inst->total_exec_cnt,
  3335. func_inst->children_exec_time / 1000.0f);
  3336. }
  3337. }
  3338. double
  3339. wasm_summarize_wasm_execute_time(const WASMModuleInstance *inst)
  3340. {
  3341. double ret = 0;
  3342. unsigned i;
  3343. for (i = 0; i < inst->e->function_count; i++) {
  3344. WASMFunctionInstance *func = inst->e->functions + i;
  3345. ret += (func->total_exec_time - func->children_exec_time) / 1000.0f;
  3346. }
  3347. return ret;
  3348. }
  3349. double
  3350. wasm_get_wasm_func_exec_time(const WASMModuleInstance *inst,
  3351. const char *func_name)
  3352. {
  3353. unsigned i;
  3354. for (i = 0; i < inst->e->function_count; i++) {
  3355. char *name_in_wasm = get_func_name_from_index(inst, i);
  3356. if (name_in_wasm && strcmp(name_in_wasm, func_name) == 0) {
  3357. WASMFunctionInstance *func = inst->e->functions + i;
  3358. return (func->total_exec_time - func->children_exec_time) / 1000.0f;
  3359. }
  3360. }
  3361. return -1.0;
  3362. }
  3363. #endif /*WASM_ENABLE_PERF_PROFILING != 0*/
  3364. uint64
  3365. wasm_module_malloc_internal(WASMModuleInstance *module_inst,
  3366. WASMExecEnv *exec_env, uint64 size,
  3367. void **p_native_addr)
  3368. {
  3369. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3370. uint8 *addr = NULL;
  3371. uint64 offset = 0;
  3372. /* TODO: Memory64 size check based on memory idx type */
  3373. bh_assert(size <= UINT32_MAX);
  3374. if (!memory) {
  3375. wasm_set_exception(module_inst, "uninitialized memory");
  3376. return 0;
  3377. }
  3378. if (memory->heap_handle) {
  3379. addr = mem_allocator_malloc(memory->heap_handle, (uint32)size);
  3380. }
  3381. else if (module_inst->e->malloc_function && module_inst->e->free_function) {
  3382. if (!execute_malloc_function(
  3383. module_inst, exec_env, module_inst->e->malloc_function,
  3384. module_inst->e->retain_function, size, &offset)) {
  3385. return 0;
  3386. }
  3387. /* If we use app's malloc function,
  3388. the default memory may be changed while memory growing */
  3389. memory = wasm_get_default_memory(module_inst);
  3390. addr = offset ? memory->memory_data + offset : NULL;
  3391. }
  3392. if (!addr) {
  3393. if (memory->heap_handle
  3394. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  3395. wasm_runtime_show_app_heap_corrupted_prompt();
  3396. wasm_set_exception(module_inst, "app heap corrupted");
  3397. }
  3398. else {
  3399. LOG_WARNING("warning: allocate %" PRIu64 " bytes memory failed",
  3400. size);
  3401. }
  3402. return 0;
  3403. }
  3404. if (p_native_addr)
  3405. *p_native_addr = addr;
  3406. return (uint64)(addr - memory->memory_data);
  3407. }
  3408. uint64
  3409. wasm_module_realloc_internal(WASMModuleInstance *module_inst,
  3410. WASMExecEnv *exec_env, uint64 ptr, uint64 size,
  3411. void **p_native_addr)
  3412. {
  3413. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3414. uint8 *addr = NULL;
  3415. /* TODO: Memory64 ptr and size check based on memory idx type */
  3416. bh_assert(ptr <= UINT32_MAX);
  3417. bh_assert(size <= UINT32_MAX);
  3418. if (!memory) {
  3419. wasm_set_exception(module_inst, "uninitialized memory");
  3420. return 0;
  3421. }
  3422. if (memory->heap_handle) {
  3423. addr = mem_allocator_realloc(
  3424. memory->heap_handle,
  3425. (uint32)ptr ? memory->memory_data + (uint32)ptr : NULL,
  3426. (uint32)size);
  3427. }
  3428. /* Only support realloc in WAMR's app heap */
  3429. (void)exec_env;
  3430. if (!addr) {
  3431. if (memory->heap_handle
  3432. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  3433. wasm_set_exception(module_inst, "app heap corrupted");
  3434. }
  3435. else {
  3436. wasm_set_exception(module_inst, "out of memory");
  3437. }
  3438. return 0;
  3439. }
  3440. if (p_native_addr)
  3441. *p_native_addr = addr;
  3442. return (uint64)(addr - memory->memory_data);
  3443. }
  3444. void
  3445. wasm_module_free_internal(WASMModuleInstance *module_inst,
  3446. WASMExecEnv *exec_env, uint64 ptr)
  3447. {
  3448. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3449. /* TODO: Memory64 ptr and size check based on memory idx type */
  3450. bh_assert(ptr <= UINT32_MAX);
  3451. if (!memory) {
  3452. return;
  3453. }
  3454. if (ptr) {
  3455. uint8 *addr = memory->memory_data + (uint32)ptr;
  3456. uint8 *memory_data_end;
  3457. /* memory->memory_data_end may be changed in memory grow */
  3458. SHARED_MEMORY_LOCK(memory);
  3459. memory_data_end = memory->memory_data_end;
  3460. SHARED_MEMORY_UNLOCK(memory);
  3461. if (memory->heap_handle && memory->heap_data <= addr
  3462. && addr < memory->heap_data_end) {
  3463. mem_allocator_free(memory->heap_handle, addr);
  3464. }
  3465. else if (module_inst->e->malloc_function
  3466. && module_inst->e->free_function && memory->memory_data <= addr
  3467. && addr < memory_data_end) {
  3468. execute_free_function(module_inst, exec_env,
  3469. module_inst->e->free_function, ptr);
  3470. }
  3471. }
  3472. }
  3473. uint64
  3474. wasm_module_malloc(WASMModuleInstance *module_inst, uint64 size,
  3475. void **p_native_addr)
  3476. {
  3477. return wasm_module_malloc_internal(module_inst, NULL, size, p_native_addr);
  3478. }
  3479. uint64
  3480. wasm_module_realloc(WASMModuleInstance *module_inst, uint64 ptr, uint64 size,
  3481. void **p_native_addr)
  3482. {
  3483. return wasm_module_realloc_internal(module_inst, NULL, ptr, size,
  3484. p_native_addr);
  3485. }
  3486. void
  3487. wasm_module_free(WASMModuleInstance *module_inst, uint64 ptr)
  3488. {
  3489. wasm_module_free_internal(module_inst, NULL, ptr);
  3490. }
  3491. uint64
  3492. wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src,
  3493. uint64 size)
  3494. {
  3495. char *buffer;
  3496. uint64 buffer_offset;
  3497. /* TODO: Memory64 size check based on memory idx type */
  3498. bh_assert(size <= UINT32_MAX);
  3499. buffer_offset = wasm_module_malloc(module_inst, size, (void **)&buffer);
  3500. if (buffer_offset != 0) {
  3501. buffer = wasm_runtime_addr_app_to_native(
  3502. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  3503. bh_memcpy_s(buffer, (uint32)size, src, (uint32)size);
  3504. }
  3505. return buffer_offset;
  3506. }
  3507. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  3508. bool
  3509. wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx,
  3510. uint32 inc_size, table_elem_type_t init_val)
  3511. {
  3512. uint32 total_size, i;
  3513. table_elem_type_t *new_table_data_start;
  3514. WASMTableInstance *table_inst;
  3515. if (!inc_size) {
  3516. return true;
  3517. }
  3518. bh_assert(table_idx < module_inst->table_count);
  3519. table_inst = wasm_get_table_inst(module_inst, table_idx);
  3520. if (!table_inst) {
  3521. return false;
  3522. }
  3523. if (inc_size > UINT32_MAX - table_inst->cur_size) {
  3524. return false;
  3525. }
  3526. total_size = table_inst->cur_size + inc_size;
  3527. if (total_size > table_inst->max_size) {
  3528. return false;
  3529. }
  3530. /* fill in */
  3531. new_table_data_start = table_inst->elems + table_inst->cur_size;
  3532. for (i = 0; i < inc_size; ++i) {
  3533. new_table_data_start[i] = init_val;
  3534. }
  3535. table_inst->cur_size = total_size;
  3536. return true;
  3537. }
  3538. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  3539. static bool
  3540. call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 tbl_elem_idx,
  3541. uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx)
  3542. {
  3543. WASMModuleInstance *module_inst = NULL;
  3544. WASMTableInstance *table_inst = NULL;
  3545. table_elem_type_t tbl_elem_val = NULL_REF;
  3546. uint32 func_idx = 0;
  3547. WASMFunctionInstance *func_inst = NULL;
  3548. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  3549. bh_assert(module_inst);
  3550. table_inst = module_inst->tables[tbl_idx];
  3551. if (!table_inst) {
  3552. wasm_set_exception(module_inst, "unknown table");
  3553. goto got_exception;
  3554. }
  3555. if (tbl_elem_idx >= table_inst->cur_size) {
  3556. wasm_set_exception(module_inst, "undefined element");
  3557. goto got_exception;
  3558. }
  3559. tbl_elem_val = ((table_elem_type_t *)table_inst->elems)[tbl_elem_idx];
  3560. if (tbl_elem_val == NULL_REF) {
  3561. wasm_set_exception(module_inst, "uninitialized element");
  3562. goto got_exception;
  3563. }
  3564. #if WASM_ENABLE_GC == 0
  3565. func_idx = (uint32)tbl_elem_val;
  3566. #else
  3567. func_idx =
  3568. wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val);
  3569. #endif
  3570. /**
  3571. * we insist to call functions owned by the module itself
  3572. **/
  3573. if (func_idx >= module_inst->e->function_count) {
  3574. wasm_set_exception(module_inst, "unknown function");
  3575. goto got_exception;
  3576. }
  3577. func_inst = module_inst->e->functions + func_idx;
  3578. if (check_type_idx) {
  3579. WASMType *cur_type = module_inst->module->types[type_idx];
  3580. WASMType *cur_func_type;
  3581. if (func_inst->is_import_func)
  3582. cur_func_type = (WASMType *)func_inst->u.func_import->func_type;
  3583. else
  3584. cur_func_type = (WASMType *)func_inst->u.func->func_type;
  3585. if (cur_type != cur_func_type) {
  3586. wasm_set_exception(module_inst, "indirect call type mismatch");
  3587. goto got_exception;
  3588. }
  3589. }
  3590. interp_call_wasm(module_inst, exec_env, func_inst, argc, argv);
  3591. return !wasm_copy_exception(module_inst, NULL);
  3592. got_exception:
  3593. return false;
  3594. }
  3595. bool
  3596. wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3597. uint32 argc, uint32 argv[])
  3598. {
  3599. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  3600. }
  3601. #if WASM_ENABLE_THREAD_MGR != 0
  3602. bool
  3603. wasm_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size)
  3604. {
  3605. WASMModuleInstance *module_inst =
  3606. (WASMModuleInstance *)exec_env->module_inst;
  3607. uint32 stack_top_idx = module_inst->module->aux_stack_top_global_index;
  3608. #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0
  3609. /* Check the aux stack space */
  3610. uint64 data_end = module_inst->module->aux_data_end;
  3611. uint64 stack_bottom = module_inst->module->aux_stack_bottom;
  3612. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  3613. if ((is_stack_before_data && (size > start_offset))
  3614. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  3615. return false;
  3616. #endif
  3617. if (stack_top_idx != (uint32)-1) {
  3618. /* The aux stack top is a wasm global,
  3619. set the initial value for the global */
  3620. uint8 *global_addr =
  3621. module_inst->global_data
  3622. + module_inst->e->globals[stack_top_idx].data_offset;
  3623. *(int32 *)global_addr = (uint32)start_offset;
  3624. /* The aux stack boundary is a constant value,
  3625. set the value to exec_env */
  3626. exec_env->aux_stack_boundary = (uintptr_t)start_offset - size;
  3627. exec_env->aux_stack_bottom = (uintptr_t)start_offset;
  3628. return true;
  3629. }
  3630. return false;
  3631. }
  3632. bool
  3633. wasm_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size)
  3634. {
  3635. WASMModuleInstance *module_inst =
  3636. (WASMModuleInstance *)exec_env->module_inst;
  3637. /* The aux stack information is resolved in loader
  3638. and store in module */
  3639. uint64 stack_bottom = module_inst->module->aux_stack_bottom;
  3640. uint32 total_aux_stack_size = module_inst->module->aux_stack_size;
  3641. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  3642. if (start_offset)
  3643. *start_offset = stack_bottom;
  3644. if (size)
  3645. *size = total_aux_stack_size;
  3646. return true;
  3647. }
  3648. return false;
  3649. }
  3650. #endif
  3651. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  3652. void
  3653. wasm_get_module_mem_consumption(const WASMModule *module,
  3654. WASMModuleMemConsumption *mem_conspn)
  3655. {
  3656. uint32 i, size;
  3657. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3658. mem_conspn->module_struct_size = sizeof(WASMModule);
  3659. mem_conspn->types_size = sizeof(WASMFuncType *) * module->type_count;
  3660. for (i = 0; i < module->type_count; i++) {
  3661. WASMFuncType *type = module->types[i];
  3662. size = offsetof(WASMFuncType, types)
  3663. + sizeof(uint8) * (type->param_count + type->result_count);
  3664. mem_conspn->types_size += size;
  3665. }
  3666. mem_conspn->imports_size = sizeof(WASMImport) * module->import_count;
  3667. mem_conspn->functions_size =
  3668. sizeof(WASMFunction *) * module->function_count;
  3669. for (i = 0; i < module->function_count; i++) {
  3670. WASMFunction *func = module->functions[i];
  3671. WASMFuncType *type = func->func_type;
  3672. size = sizeof(WASMFunction) + func->local_count
  3673. + sizeof(uint16) * (type->param_count + func->local_count);
  3674. #if WASM_ENABLE_FAST_INTERP != 0
  3675. size +=
  3676. func->code_compiled_size + sizeof(uint32) * func->const_cell_num;
  3677. #endif
  3678. mem_conspn->functions_size += size;
  3679. }
  3680. mem_conspn->tables_size = sizeof(WASMTable) * module->table_count;
  3681. mem_conspn->memories_size = sizeof(WASMMemory) * module->memory_count;
  3682. mem_conspn->globals_size = sizeof(WASMGlobal) * module->global_count;
  3683. mem_conspn->exports_size = sizeof(WASMExport) * module->export_count;
  3684. mem_conspn->table_segs_size =
  3685. sizeof(WASMTableSeg) * module->table_seg_count;
  3686. for (i = 0; i < module->table_seg_count; i++) {
  3687. WASMTableSeg *table_seg = &module->table_segments[i];
  3688. mem_conspn->tables_size +=
  3689. sizeof(InitializerExpression *) * table_seg->value_count;
  3690. }
  3691. mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count;
  3692. for (i = 0; i < module->data_seg_count; i++) {
  3693. mem_conspn->data_segs_size += sizeof(WASMDataSeg);
  3694. }
  3695. if (module->const_str_list) {
  3696. StringNode *node = module->const_str_list, *node_next;
  3697. while (node) {
  3698. node_next = node->next;
  3699. mem_conspn->const_strs_size +=
  3700. sizeof(StringNode) + strlen(node->str) + 1;
  3701. node = node_next;
  3702. }
  3703. }
  3704. mem_conspn->total_size += mem_conspn->module_struct_size;
  3705. mem_conspn->total_size += mem_conspn->types_size;
  3706. mem_conspn->total_size += mem_conspn->imports_size;
  3707. mem_conspn->total_size += mem_conspn->functions_size;
  3708. mem_conspn->total_size += mem_conspn->tables_size;
  3709. mem_conspn->total_size += mem_conspn->memories_size;
  3710. mem_conspn->total_size += mem_conspn->globals_size;
  3711. mem_conspn->total_size += mem_conspn->exports_size;
  3712. mem_conspn->total_size += mem_conspn->table_segs_size;
  3713. mem_conspn->total_size += mem_conspn->data_segs_size;
  3714. mem_conspn->total_size += mem_conspn->const_strs_size;
  3715. }
  3716. void
  3717. wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst,
  3718. WASMModuleInstMemConsumption *mem_conspn)
  3719. {
  3720. uint32 i;
  3721. uint64 size;
  3722. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3723. mem_conspn->module_inst_struct_size = (uint8 *)module_inst->e
  3724. - (uint8 *)module_inst
  3725. + sizeof(WASMModuleInstanceExtra);
  3726. mem_conspn->memories_size =
  3727. sizeof(WASMMemoryInstance *) * module_inst->memory_count;
  3728. for (i = 0; i < module_inst->memory_count; i++) {
  3729. WASMMemoryInstance *memory = module_inst->memories[i];
  3730. size = (uint64)memory->num_bytes_per_page * memory->cur_page_count;
  3731. mem_conspn->memories_size += size;
  3732. mem_conspn->app_heap_size += memory->heap_data_end - memory->heap_data;
  3733. /* size of app heap structure */
  3734. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  3735. /* Module instance structures have been appended into the end of
  3736. module instance */
  3737. }
  3738. mem_conspn->tables_size =
  3739. sizeof(WASMTableInstance *) * module_inst->table_count;
  3740. /* Table instance structures and table elements have been appended into
  3741. the end of module instance */
  3742. mem_conspn->functions_size =
  3743. sizeof(WASMFunctionInstance) * module_inst->e->function_count;
  3744. mem_conspn->globals_size =
  3745. sizeof(WASMGlobalInstance) * module_inst->e->global_count;
  3746. /* Global data has been appended into the end of module instance */
  3747. mem_conspn->exports_size =
  3748. sizeof(WASMExportFuncInstance) * module_inst->export_func_count;
  3749. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  3750. mem_conspn->total_size += mem_conspn->memories_size;
  3751. mem_conspn->total_size += mem_conspn->functions_size;
  3752. mem_conspn->total_size += mem_conspn->tables_size;
  3753. mem_conspn->total_size += mem_conspn->globals_size;
  3754. mem_conspn->total_size += mem_conspn->exports_size;
  3755. }
  3756. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  3757. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  3758. #if WASM_ENABLE_COPY_CALL_STACK != 0
  3759. uint32
  3760. wasm_interp_copy_callstack(WASMExecEnv *exec_env, WASMCApiFrame *buffer,
  3761. uint32 length, uint32 skip_n, char *error_buf,
  3762. uint32_t error_buf_size)
  3763. {
  3764. /*
  3765. * Note for devs: please refrain from such modifications inside of
  3766. * wasm_interp_copy_callstack
  3767. * - any allocations/freeing memory
  3768. * - dereferencing any pointers other than: exec_env, exec_env->module_inst,
  3769. * exec_env->module_inst->module, pointers between stack's bottom and
  3770. * top_boundary For more details check wasm_copy_callstack in
  3771. * wasm_export.h
  3772. */
  3773. WASMModuleInstance *module_inst =
  3774. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3775. WASMInterpFrame *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  3776. uint8 *top_boundary = exec_env->wasm_stack.top_boundary;
  3777. uint8 *bottom = exec_env->wasm_stack.bottom;
  3778. uint32 count = 0;
  3779. WASMCApiFrame record_frame;
  3780. while (cur_frame && (uint8_t *)cur_frame >= bottom
  3781. && (uint8_t *)cur_frame + sizeof(WASMInterpFrame) <= top_boundary
  3782. && count < (skip_n + length)) {
  3783. if (!cur_frame->function) {
  3784. cur_frame = cur_frame->prev_frame;
  3785. continue;
  3786. }
  3787. if (count < skip_n) {
  3788. ++count;
  3789. cur_frame = cur_frame->prev_frame;
  3790. continue;
  3791. }
  3792. record_frame.instance = module_inst;
  3793. record_frame.module_offset = 0;
  3794. // It's safe to dereference module_inst->e because "e" is asigned only
  3795. // once in wasm_instantiate
  3796. record_frame.func_index =
  3797. (uint32)(cur_frame->function - module_inst->e->functions);
  3798. buffer[count - skip_n] = record_frame;
  3799. cur_frame = cur_frame->prev_frame;
  3800. ++count;
  3801. }
  3802. return count >= skip_n ? count - skip_n : 0;
  3803. }
  3804. #endif // WASM_ENABLE_COPY_CALL_STACK
  3805. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3806. bool
  3807. wasm_interp_create_call_stack(struct WASMExecEnv *exec_env)
  3808. {
  3809. WASMModuleInstance *module_inst =
  3810. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3811. WASMModule *module = module_inst->module;
  3812. WASMInterpFrame *first_frame,
  3813. *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  3814. uint32 n = 0;
  3815. /* count frames includes a function */
  3816. first_frame = cur_frame;
  3817. while (cur_frame) {
  3818. if (cur_frame->function) {
  3819. n++;
  3820. }
  3821. cur_frame = cur_frame->prev_frame;
  3822. }
  3823. /* release previous stack frames and create new ones */
  3824. destroy_c_api_frames(module_inst->frames);
  3825. if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) {
  3826. return false;
  3827. }
  3828. cur_frame = first_frame;
  3829. n = 0;
  3830. while (cur_frame) {
  3831. WASMCApiFrame frame = { 0 };
  3832. WASMFunctionInstance *func_inst = cur_frame->function;
  3833. const char *func_name = NULL;
  3834. const uint8 *func_code_base = NULL;
  3835. uint32 max_local_cell_num, max_stack_cell_num;
  3836. uint32 all_cell_num, lp_size;
  3837. if (!func_inst) {
  3838. cur_frame = cur_frame->prev_frame;
  3839. continue;
  3840. }
  3841. /* place holder, will overwrite it in wasm_c_api */
  3842. frame.instance = module_inst;
  3843. frame.module_offset = 0;
  3844. frame.func_index = (uint32)(func_inst - module_inst->e->functions);
  3845. func_code_base = wasm_get_func_code(func_inst);
  3846. if (!cur_frame->ip || !func_code_base) {
  3847. frame.func_offset = 0;
  3848. }
  3849. else {
  3850. #if WASM_ENABLE_FAST_INTERP == 0
  3851. frame.func_offset = (uint32)(cur_frame->ip - module->load_addr);
  3852. #else
  3853. frame.func_offset = (uint32)(cur_frame->ip - func_code_base);
  3854. #endif
  3855. }
  3856. func_name = get_func_name_from_index(module_inst, frame.func_index);
  3857. frame.func_name_wp = func_name;
  3858. if (frame.func_index >= module->import_function_count) {
  3859. uint32 wasm_func_idx =
  3860. frame.func_index - module->import_function_count;
  3861. max_local_cell_num =
  3862. module->functions[wasm_func_idx]->param_cell_num
  3863. + module->functions[wasm_func_idx]->local_cell_num;
  3864. max_stack_cell_num =
  3865. module->functions[wasm_func_idx]->max_stack_cell_num;
  3866. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3867. #if WASM_ENABLE_FAST_INTERP != 0
  3868. all_cell_num += module->functions[wasm_func_idx]->const_cell_num;
  3869. #endif
  3870. }
  3871. else {
  3872. WASMFuncType *func_type =
  3873. module->import_functions[frame.func_index].u.function.func_type;
  3874. max_local_cell_num =
  3875. func_type->param_cell_num > 2 ? func_type->param_cell_num : 2;
  3876. max_stack_cell_num = 0;
  3877. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3878. }
  3879. #if WASM_ENABLE_GC == 0
  3880. lp_size = all_cell_num * 4;
  3881. #else
  3882. lp_size = align_uint(all_cell_num * 5, 4);
  3883. #endif
  3884. if (lp_size > 0) {
  3885. if (!(frame.lp = wasm_runtime_malloc(lp_size))) {
  3886. destroy_c_api_frames(module_inst->frames);
  3887. return false;
  3888. }
  3889. bh_memcpy_s(frame.lp, lp_size, cur_frame->lp, lp_size);
  3890. #if WASM_ENABLE_GC != 0
  3891. #if WASM_ENABLE_FAST_INTERP == 0
  3892. frame.sp = frame.lp + (cur_frame->sp - cur_frame->lp);
  3893. #else
  3894. /* for fast-interp, let frame sp point to the end of the frame */
  3895. frame.sp = frame.lp + all_cell_num;
  3896. #endif
  3897. frame.frame_ref = (uint8 *)frame.lp
  3898. + (wasm_interp_get_frame_ref(cur_frame)
  3899. - (uint8 *)cur_frame->lp);
  3900. #endif
  3901. }
  3902. if (!bh_vector_append(module_inst->frames, &frame)) {
  3903. if (frame.lp)
  3904. wasm_runtime_free(frame.lp);
  3905. destroy_c_api_frames(module_inst->frames);
  3906. return false;
  3907. }
  3908. cur_frame = cur_frame->prev_frame;
  3909. n++;
  3910. }
  3911. return true;
  3912. }
  3913. #define PRINT_OR_DUMP() \
  3914. do { \
  3915. total_len += \
  3916. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  3917. if ((!print) && buf && (len == 0)) { \
  3918. exception_unlock(module_inst); \
  3919. return total_len; \
  3920. } \
  3921. } while (0)
  3922. uint32
  3923. wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf,
  3924. uint32 len)
  3925. {
  3926. WASMModuleInstance *module_inst =
  3927. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3928. uint32 n = 0, total_len = 0, total_frames;
  3929. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  3930. * will be truncated */
  3931. char line_buf[256];
  3932. if (!module_inst->frames) {
  3933. return 0;
  3934. }
  3935. total_frames = (uint32)bh_vector_size(module_inst->frames);
  3936. if (total_frames == 0) {
  3937. return 0;
  3938. }
  3939. exception_lock(module_inst);
  3940. snprintf(line_buf, sizeof(line_buf), "\n");
  3941. PRINT_OR_DUMP();
  3942. while (n < total_frames) {
  3943. WASMCApiFrame frame = { 0 };
  3944. uint32 line_length, i;
  3945. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  3946. exception_unlock(module_inst);
  3947. return 0;
  3948. }
  3949. #if WASM_ENABLE_FAST_JIT != 0
  3950. /* Fast JIT doesn't support committing ip (instruction pointer) yet */
  3951. if (module_inst->e->running_mode == Mode_Fast_JIT
  3952. || module_inst->e->running_mode == Mode_Multi_Tier_JIT) {
  3953. /* function name not exported, print number instead */
  3954. if (frame.func_name_wp == NULL) {
  3955. line_length = snprintf(line_buf, sizeof(line_buf),
  3956. "#%02" PRIu32 " $f%" PRIu32 "\n", n,
  3957. frame.func_index);
  3958. }
  3959. else {
  3960. line_length =
  3961. snprintf(line_buf, sizeof(line_buf), "#%02" PRIu32 " %s\n",
  3962. n, frame.func_name_wp);
  3963. }
  3964. }
  3965. else
  3966. #endif
  3967. {
  3968. /* function name not exported, print number instead */
  3969. if (frame.func_name_wp == NULL) {
  3970. line_length =
  3971. snprintf(line_buf, sizeof(line_buf),
  3972. "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n", n,
  3973. frame.func_offset, frame.func_index);
  3974. }
  3975. else {
  3976. line_length = snprintf(line_buf, sizeof(line_buf),
  3977. "#%02" PRIu32 ": 0x%04x - %s\n", n,
  3978. frame.func_offset, frame.func_name_wp);
  3979. }
  3980. }
  3981. if (line_length >= sizeof(line_buf)) {
  3982. uint32 line_buffer_len = sizeof(line_buf);
  3983. /* If line too long, ensure the last character is '\n' */
  3984. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  3985. line_buf[i] = '.';
  3986. }
  3987. line_buf[line_buffer_len - 2] = '\n';
  3988. }
  3989. PRINT_OR_DUMP();
  3990. n++;
  3991. }
  3992. snprintf(line_buf, sizeof(line_buf), "\n");
  3993. PRINT_OR_DUMP();
  3994. exception_unlock(module_inst);
  3995. return total_len + 1;
  3996. }
  3997. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  3998. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  3999. || WASM_ENABLE_WAMR_COMPILER != 0
  4000. void
  4001. jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  4002. {
  4003. if (id != EXCE_ALREADY_THROWN)
  4004. wasm_set_exception_with_id(module_inst, id);
  4005. #ifdef OS_ENABLE_HW_BOUND_CHECK
  4006. wasm_runtime_access_exce_check_guard_page();
  4007. #endif
  4008. }
  4009. bool
  4010. jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str,
  4011. uint64 app_buf_addr, uint64 app_buf_size,
  4012. void **p_native_addr)
  4013. {
  4014. bool ret = wasm_check_app_addr_and_convert(
  4015. module_inst, is_str, app_buf_addr, app_buf_size, p_native_addr);
  4016. #ifdef OS_ENABLE_HW_BOUND_CHECK
  4017. if (!ret)
  4018. wasm_runtime_access_exce_check_guard_page();
  4019. #endif
  4020. return ret;
  4021. }
  4022. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  4023. || WASM_ENABLE_WAMR_COMPILER != 0 */
  4024. #if WASM_ENABLE_FAST_JIT != 0
  4025. bool
  4026. fast_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  4027. uint32 type_idx, uint32 argc, uint32 *argv)
  4028. {
  4029. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, true,
  4030. type_idx);
  4031. }
  4032. #endif /* end of WASM_ENABLE_FAST_JIT != 0 */
  4033. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  4034. bool
  4035. llvm_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  4036. uint32 argc, uint32 *argv)
  4037. {
  4038. bool ret;
  4039. bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode);
  4040. ret = call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  4041. #ifdef OS_ENABLE_HW_BOUND_CHECK
  4042. if (!ret)
  4043. wasm_runtime_access_exce_check_guard_page();
  4044. #endif
  4045. return ret;
  4046. }
  4047. bool
  4048. llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  4049. uint32 *argv)
  4050. {
  4051. WASMModuleInstance *module_inst;
  4052. WASMModule *module;
  4053. uint32 *func_type_indexes;
  4054. uint32 func_type_idx;
  4055. WASMFuncType *func_type;
  4056. void *func_ptr;
  4057. WASMFunctionImport *import_func;
  4058. CApiFuncImport *c_api_func_import = NULL;
  4059. const char *signature;
  4060. void *attachment;
  4061. char buf[96];
  4062. bool ret = false;
  4063. bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode);
  4064. module_inst = (WASMModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  4065. module = module_inst->module;
  4066. func_type_indexes = module_inst->func_type_indexes;
  4067. func_type_idx = func_type_indexes[func_idx];
  4068. func_type = (WASMFuncType *)module->types[func_type_idx];
  4069. func_ptr = module_inst->func_ptrs[func_idx];
  4070. bh_assert(func_idx < module->import_function_count);
  4071. import_func = &module->import_functions[func_idx].u.function;
  4072. if (import_func->call_conv_wasm_c_api) {
  4073. if (module_inst->c_api_func_imports) {
  4074. c_api_func_import = module_inst->c_api_func_imports + func_idx;
  4075. func_ptr = c_api_func_import->func_ptr_linked;
  4076. }
  4077. else {
  4078. c_api_func_import = NULL;
  4079. func_ptr = NULL;
  4080. }
  4081. }
  4082. if (!func_ptr) {
  4083. snprintf(buf, sizeof(buf),
  4084. "failed to call unlinked import function (%s, %s)",
  4085. import_func->module_name, import_func->field_name);
  4086. wasm_set_exception(module_inst, buf);
  4087. goto fail;
  4088. }
  4089. attachment = import_func->attachment;
  4090. if (import_func->call_conv_wasm_c_api) {
  4091. ret = wasm_runtime_invoke_c_api_native(
  4092. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  4093. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  4094. }
  4095. else if (!import_func->call_conv_raw) {
  4096. signature = import_func->signature;
  4097. ret =
  4098. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  4099. attachment, argv, argc, argv);
  4100. }
  4101. else {
  4102. signature = import_func->signature;
  4103. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  4104. signature, attachment, argv, argc,
  4105. argv);
  4106. }
  4107. fail:
  4108. #ifdef OS_ENABLE_HW_BOUND_CHECK
  4109. if (!ret)
  4110. wasm_runtime_access_exce_check_guard_page();
  4111. #endif
  4112. return ret;
  4113. }
  4114. #if WASM_ENABLE_BULK_MEMORY != 0
  4115. bool
  4116. llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index,
  4117. uint32 offset, uint32 len, size_t dst)
  4118. {
  4119. WASMMemoryInstance *memory_inst;
  4120. WASMModule *module;
  4121. uint8 *data;
  4122. uint8 *maddr;
  4123. uint64 seg_len;
  4124. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4125. memory_inst = wasm_get_default_memory(module_inst);
  4126. if (bh_bitmap_get_bit(module_inst->e->common.data_dropped, seg_index)) {
  4127. seg_len = 0;
  4128. data = NULL;
  4129. }
  4130. else {
  4131. module = module_inst->module;
  4132. seg_len = module->data_segments[seg_index]->data_length;
  4133. data = module->data_segments[seg_index]->data;
  4134. }
  4135. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  4136. (uint64)dst, (uint64)len))
  4137. return false;
  4138. if ((uint64)offset + (uint64)len > seg_len) {
  4139. wasm_set_exception(module_inst, "out of bounds memory access");
  4140. return false;
  4141. }
  4142. maddr = wasm_runtime_addr_app_to_native(
  4143. (WASMModuleInstanceCommon *)module_inst, (uint64)dst);
  4144. SHARED_MEMORY_LOCK(memory_inst);
  4145. bh_memcpy_s(maddr, CLAMP_U64_TO_U32(memory_inst->memory_data_size - dst),
  4146. data + offset, len);
  4147. SHARED_MEMORY_UNLOCK(memory_inst);
  4148. return true;
  4149. }
  4150. bool
  4151. llvm_jit_data_drop(WASMModuleInstance *module_inst, uint32 seg_index)
  4152. {
  4153. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4154. bh_bitmap_set_bit(module_inst->e->common.data_dropped, seg_index);
  4155. /* Currently we can't free the dropped data segment
  4156. as they are stored in wasm bytecode */
  4157. return true;
  4158. }
  4159. #endif /* end of WASM_ENABLE_BULK_MEMORY != 0 */
  4160. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  4161. void
  4162. llvm_jit_drop_table_seg(WASMModuleInstance *module_inst, uint32 tbl_seg_idx)
  4163. {
  4164. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4165. bh_bitmap_set_bit(module_inst->e->common.elem_dropped, tbl_seg_idx);
  4166. }
  4167. void
  4168. llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4169. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  4170. uint32 dst_offset)
  4171. {
  4172. WASMTableInstance *tbl_inst;
  4173. WASMTableSeg *tbl_seg;
  4174. table_elem_type_t *table_elems;
  4175. InitializerExpression *tbl_seg_init_values = NULL, *init_values;
  4176. uint32 i, tbl_seg_len = 0;
  4177. #if WASM_ENABLE_GC != 0
  4178. void *func_obj;
  4179. #endif
  4180. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4181. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4182. tbl_seg = module_inst->module->table_segments + tbl_seg_idx;
  4183. bh_assert(tbl_inst);
  4184. bh_assert(tbl_seg);
  4185. if (!bh_bitmap_get_bit(module_inst->e->common.elem_dropped, tbl_seg_idx)) {
  4186. /* table segment isn't dropped */
  4187. tbl_seg_init_values = tbl_seg->init_values;
  4188. tbl_seg_len = tbl_seg->value_count;
  4189. }
  4190. if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len)
  4191. || offset_len_out_of_bounds(dst_offset, length, tbl_inst->cur_size)) {
  4192. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4193. return;
  4194. }
  4195. if (!length) {
  4196. return;
  4197. }
  4198. table_elems = tbl_inst->elems + dst_offset;
  4199. init_values = tbl_seg_init_values + src_offset;
  4200. for (i = 0; i < length; i++) {
  4201. #if WASM_ENABLE_GC != 0
  4202. /* UINT32_MAX indicates that it is a null ref */
  4203. if (init_values[i].u.unary.v.ref_index != UINT32_MAX) {
  4204. if (!(func_obj = wasm_create_func_obj(
  4205. module_inst, init_values[i].u.unary.v.ref_index, true,
  4206. NULL, 0))) {
  4207. wasm_set_exception(module_inst, "null function reference");
  4208. return;
  4209. }
  4210. table_elems[i] = func_obj;
  4211. }
  4212. else {
  4213. table_elems[i] = NULL_REF;
  4214. }
  4215. #else
  4216. table_elems[i] = init_values[i].u.unary.v.ref_index;
  4217. #endif
  4218. }
  4219. }
  4220. void
  4221. llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx,
  4222. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  4223. uint32 dst_offset)
  4224. {
  4225. WASMTableInstance *src_tbl_inst;
  4226. WASMTableInstance *dst_tbl_inst;
  4227. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4228. src_tbl_inst = wasm_get_table_inst(module_inst, src_tbl_idx);
  4229. dst_tbl_inst = wasm_get_table_inst(module_inst, dst_tbl_idx);
  4230. bh_assert(src_tbl_inst);
  4231. bh_assert(dst_tbl_inst);
  4232. if (offset_len_out_of_bounds(dst_offset, length, dst_tbl_inst->cur_size)
  4233. || offset_len_out_of_bounds(src_offset, length,
  4234. src_tbl_inst->cur_size)) {
  4235. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4236. return;
  4237. }
  4238. /* if src_offset >= dst_offset, copy from front to back */
  4239. /* if src_offset < dst_offset, copy from back to front */
  4240. /* merge all together */
  4241. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems)
  4242. + sizeof(table_elem_type_t) * dst_offset,
  4243. (uint32)sizeof(table_elem_type_t)
  4244. * (dst_tbl_inst->cur_size - dst_offset),
  4245. (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems)
  4246. + sizeof(table_elem_type_t) * src_offset,
  4247. (uint32)sizeof(table_elem_type_t) * length);
  4248. }
  4249. void
  4250. llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4251. uint32 length, uintptr_t val, uint32 data_offset)
  4252. {
  4253. WASMTableInstance *tbl_inst;
  4254. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4255. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4256. bh_assert(tbl_inst);
  4257. if (offset_len_out_of_bounds(data_offset, length, tbl_inst->cur_size)) {
  4258. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4259. return;
  4260. }
  4261. for (; length != 0; data_offset++, length--) {
  4262. tbl_inst->elems[data_offset] = (table_elem_type_t)val;
  4263. }
  4264. }
  4265. uint32
  4266. llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4267. uint32 inc_size, uintptr_t init_val)
  4268. {
  4269. WASMTableInstance *tbl_inst;
  4270. uint32 i, orig_size, total_size;
  4271. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4272. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4273. if (!tbl_inst) {
  4274. return (uint32)-1;
  4275. }
  4276. orig_size = tbl_inst->cur_size;
  4277. if (!inc_size) {
  4278. return orig_size;
  4279. }
  4280. if (tbl_inst->cur_size > UINT32_MAX - inc_size) { /* integer overflow */
  4281. #if WASM_ENABLE_SPEC_TEST == 0
  4282. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  4283. ") failed because of integer overflow",
  4284. tbl_inst->cur_size, inc_size);
  4285. #endif
  4286. return (uint32)-1;
  4287. }
  4288. total_size = tbl_inst->cur_size + inc_size;
  4289. if (total_size > tbl_inst->max_size) {
  4290. #if WASM_ENABLE_SPEC_TEST == 0
  4291. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  4292. ") failed because of over max size",
  4293. tbl_inst->cur_size, inc_size);
  4294. #endif
  4295. return (uint32)-1;
  4296. }
  4297. /* fill in */
  4298. for (i = 0; i < inc_size; ++i) {
  4299. tbl_inst->elems[tbl_inst->cur_size + i] = (table_elem_type_t)init_val;
  4300. }
  4301. tbl_inst->cur_size = total_size;
  4302. return orig_size;
  4303. }
  4304. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  4305. #if WASM_ENABLE_GC != 0
  4306. void *
  4307. llvm_jit_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx,
  4308. bool throw_exce, char *error_buf,
  4309. uint32 error_buf_size)
  4310. {
  4311. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4312. return wasm_create_func_obj(module_inst, func_idx, throw_exce, error_buf,
  4313. error_buf_size);
  4314. }
  4315. bool
  4316. llvm_jit_obj_is_instance_of(WASMModuleInstance *module_inst,
  4317. WASMObjectRef gc_obj, uint32 type_index)
  4318. {
  4319. WASMModule *module = module_inst->module;
  4320. WASMType **types = module->types;
  4321. uint32 type_count = module->type_count;
  4322. return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count);
  4323. }
  4324. bool
  4325. llvm_jit_func_type_is_super_of(WASMModuleInstance *module_inst,
  4326. uint32 type_idx1, uint32 type_idx2)
  4327. {
  4328. WASMModule *module = module_inst->module;
  4329. WASMType **types = module->types;
  4330. if (type_idx1 == type_idx2)
  4331. return true;
  4332. bh_assert(types[type_idx1]->type_flag == WASM_TYPE_FUNC);
  4333. bh_assert(types[type_idx2]->type_flag == WASM_TYPE_FUNC);
  4334. return wasm_func_type_is_super_of((WASMFuncType *)types[type_idx1],
  4335. (WASMFuncType *)types[type_idx2]);
  4336. }
  4337. WASMRttTypeRef
  4338. llvm_jit_rtt_type_new(WASMModuleInstance *module_inst, uint32 type_index)
  4339. {
  4340. WASMModule *module = module_inst->module;
  4341. WASMType *defined_type = module->types[type_index];
  4342. WASMRttType **rtt_types = module->rtt_types;
  4343. uint32 rtt_type_count = module->type_count;
  4344. korp_mutex *rtt_type_lock = &module->rtt_type_lock;
  4345. return wasm_rtt_type_new(defined_type, type_index, rtt_types,
  4346. rtt_type_count, rtt_type_lock);
  4347. }
  4348. bool
  4349. llvm_array_init_with_data(WASMModuleInstance *module_inst, uint32 seg_index,
  4350. uint32 data_seg_offset, WASMArrayObjectRef array_obj,
  4351. uint32 elem_size, uint32 array_len)
  4352. {
  4353. WASMModule *wasm_module = module_inst->module;
  4354. WASMDataSeg *data_seg;
  4355. uint8 *array_elem_base;
  4356. uint64 total_size;
  4357. data_seg = wasm_module->data_segments[seg_index];
  4358. total_size = (int64)elem_size * array_len;
  4359. if (data_seg_offset >= data_seg->data_length
  4360. || total_size > data_seg->data_length - data_seg_offset) {
  4361. wasm_set_exception(module_inst, "out of bounds memory access");
  4362. return false;
  4363. }
  4364. array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj);
  4365. bh_memcpy_s(array_elem_base, (uint32)total_size,
  4366. data_seg->data + data_seg_offset, (uint32)total_size);
  4367. return true;
  4368. }
  4369. #endif /* end of WASM_ENABLE_GC != 0 */
  4370. #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
  4371. #if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
  4372. void
  4373. wasm_propagate_wasi_args(WASMModule *module)
  4374. {
  4375. if (!module->import_count)
  4376. return;
  4377. bh_assert(&module->import_module_list_head);
  4378. WASMRegisteredModule *node =
  4379. bh_list_first_elem(&module->import_module_list_head);
  4380. while (node) {
  4381. WASIArguments *wasi_args_impt_mod =
  4382. &((WASMModule *)(node->module))->wasi_args;
  4383. bh_assert(wasi_args_impt_mod);
  4384. bh_memcpy_s(wasi_args_impt_mod, sizeof(WASIArguments),
  4385. &module->wasi_args, sizeof(WASIArguments));
  4386. node = bh_list_elem_next(node);
  4387. }
  4388. }
  4389. #endif
  4390. bool
  4391. wasm_check_utf8_str(const uint8 *str, uint32 len)
  4392. {
  4393. /* The valid ranges are taken from page 125, below link
  4394. https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf */
  4395. const uint8 *p = str, *p_end = str + len;
  4396. uint8 chr;
  4397. while (p < p_end) {
  4398. chr = *p;
  4399. if (chr == 0) {
  4400. LOG_WARNING(
  4401. "LIMITATION: a string which contains '\\00' is unsupported");
  4402. return false;
  4403. }
  4404. else if (chr < 0x80) {
  4405. p++;
  4406. }
  4407. else if (chr >= 0xC2 && chr <= 0xDF && p + 1 < p_end) {
  4408. if (p[1] < 0x80 || p[1] > 0xBF) {
  4409. return false;
  4410. }
  4411. p += 2;
  4412. }
  4413. else if (chr >= 0xE0 && chr <= 0xEF && p + 2 < p_end) {
  4414. if (chr == 0xE0) {
  4415. if (p[1] < 0xA0 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) {
  4416. return false;
  4417. }
  4418. }
  4419. else if (chr == 0xED) {
  4420. if (p[1] < 0x80 || p[1] > 0x9F || p[2] < 0x80 || p[2] > 0xBF) {
  4421. return false;
  4422. }
  4423. }
  4424. else { /* chr >= 0xE1 && chr <= 0xEF */
  4425. if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) {
  4426. return false;
  4427. }
  4428. }
  4429. p += 3;
  4430. }
  4431. else if (chr >= 0xF0 && chr <= 0xF4 && p + 3 < p_end) {
  4432. if (chr == 0xF0) {
  4433. if (p[1] < 0x90 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF
  4434. || p[3] < 0x80 || p[3] > 0xBF) {
  4435. return false;
  4436. }
  4437. }
  4438. else if (chr <= 0xF3) { /* and also chr >= 0xF1 */
  4439. if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF
  4440. || p[3] < 0x80 || p[3] > 0xBF) {
  4441. return false;
  4442. }
  4443. }
  4444. else { /* chr == 0xF4 */
  4445. if (p[1] < 0x80 || p[1] > 0x8F || p[2] < 0x80 || p[2] > 0xBF
  4446. || p[3] < 0x80 || p[3] > 0xBF) {
  4447. return false;
  4448. }
  4449. }
  4450. p += 4;
  4451. }
  4452. else {
  4453. return false;
  4454. }
  4455. }
  4456. return (p == p_end);
  4457. }
  4458. char *
  4459. wasm_const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module,
  4460. bool is_load_from_file_buf, char *error_buf,
  4461. uint32 error_buf_size)
  4462. {
  4463. StringNode *node, *node_next;
  4464. if (!wasm_check_utf8_str(str, len)) {
  4465. set_error_buf(error_buf, error_buf_size, "invalid UTF-8 encoding");
  4466. return NULL;
  4467. }
  4468. if (len == 0) {
  4469. return "";
  4470. }
  4471. else if (is_load_from_file_buf) {
  4472. /* As the file buffer can be referred to after loading, we use
  4473. the previous byte of leb encoded size to adjust the string:
  4474. move string 1 byte backward and then append '\0' */
  4475. char *c_str = (char *)str - 1;
  4476. bh_memmove_s(c_str, len + 1, c_str + 1, len);
  4477. c_str[len] = '\0';
  4478. return c_str;
  4479. }
  4480. /* Search const str list */
  4481. node = module->const_str_list;
  4482. while (node) {
  4483. node_next = node->next;
  4484. if (strlen(node->str) == len && !memcmp(node->str, str, len))
  4485. break;
  4486. node = node_next;
  4487. }
  4488. if (node) {
  4489. return node->str;
  4490. }
  4491. if (!(node = runtime_malloc(sizeof(StringNode) + len + 1, error_buf,
  4492. error_buf_size))) {
  4493. return NULL;
  4494. }
  4495. node->str = ((char *)node) + sizeof(StringNode);
  4496. bh_memcpy_s(node->str, len + 1, str, len);
  4497. node->str[len] = '\0';
  4498. if (!module->const_str_list) {
  4499. /* set as head */
  4500. module->const_str_list = node;
  4501. node->next = NULL;
  4502. }
  4503. else {
  4504. /* insert it */
  4505. node->next = module->const_str_list;
  4506. module->const_str_list = node;
  4507. }
  4508. return node->str;
  4509. }
  4510. bool
  4511. wasm_set_module_name(WASMModule *module, const char *name, char *error_buf,
  4512. uint32_t error_buf_size)
  4513. {
  4514. if (!name)
  4515. return false;
  4516. module->name =
  4517. wasm_const_str_list_insert((const uint8 *)name, (uint32)strlen(name),
  4518. module, false, error_buf, error_buf_size);
  4519. return module->name != NULL;
  4520. }
  4521. const char *
  4522. wasm_get_module_name(WASMModule *module)
  4523. {
  4524. return module->name;
  4525. }