wasm_runtime.c 155 KB

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