wasm_runtime.c 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831
  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_loader.h"
  7. #include "wasm_interp.h"
  8. #include "bh_common.h"
  9. #include "bh_log.h"
  10. #include "mem_alloc.h"
  11. #include "../common/wasm_runtime_common.h"
  12. #if WASM_ENABLE_GC != 0
  13. #include "../common/gc/gc_object.h"
  14. #endif
  15. #if WASM_ENABLE_SHARED_MEMORY != 0
  16. #include "../common/wasm_shared_memory.h"
  17. #endif
  18. #if WASM_ENABLE_THREAD_MGR != 0
  19. #include "../libraries/thread-mgr/thread_manager.h"
  20. #endif
  21. #if WASM_ENABLE_DEBUG_INTERP != 0
  22. #include "../libraries/debug-engine/debug_engine.h"
  23. #endif
  24. #if WASM_ENABLE_FAST_JIT != 0
  25. #include "../fast-jit/jit_compiler.h"
  26. #endif
  27. #if WASM_ENABLE_JIT != 0
  28. #include "../aot/aot_runtime.h"
  29. #endif
  30. static void
  31. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  32. {
  33. if (error_buf != NULL) {
  34. snprintf(error_buf, error_buf_size,
  35. "WASM module instantiate failed: %s", string);
  36. }
  37. }
  38. static void
  39. set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...)
  40. {
  41. va_list args;
  42. char buf[128];
  43. if (error_buf != NULL) {
  44. va_start(args, format);
  45. vsnprintf(buf, sizeof(buf), format, args);
  46. va_end(args);
  47. snprintf(error_buf, error_buf_size,
  48. "WASM module instantiate failed: %s", buf);
  49. }
  50. }
  51. WASMModule *
  52. wasm_load(uint8 *buf, uint32 size, char *error_buf, uint32 error_buf_size)
  53. {
  54. return wasm_loader_load(buf, size,
  55. #if WASM_ENABLE_MULTI_MODULE != 0
  56. true,
  57. #endif
  58. error_buf, error_buf_size);
  59. }
  60. WASMModule *
  61. wasm_load_from_sections(WASMSection *section_list, char *error_buf,
  62. uint32 error_buf_size)
  63. {
  64. return wasm_loader_load_from_sections(section_list, error_buf,
  65. error_buf_size);
  66. }
  67. void
  68. wasm_unload(WASMModule *module)
  69. {
  70. wasm_loader_unload(module);
  71. }
  72. static void *
  73. runtime_malloc(uint64 size, char *error_buf, uint32 error_buf_size)
  74. {
  75. void *mem;
  76. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  77. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  78. return NULL;
  79. }
  80. memset(mem, 0, (uint32)size);
  81. return mem;
  82. }
  83. #if WASM_ENABLE_MULTI_MODULE != 0
  84. static WASMModuleInstance *
  85. get_sub_module_inst(const WASMModuleInstance *parent_module_inst,
  86. const WASMModule *sub_module)
  87. {
  88. bh_list *sub_module_inst_list = parent_module_inst->e->sub_module_inst_list;
  89. WASMSubModInstNode *node = bh_list_first_elem(sub_module_inst_list);
  90. while (node && sub_module != node->module_inst->module) {
  91. node = bh_list_elem_next(node);
  92. }
  93. return node ? node->module_inst : NULL;
  94. }
  95. #endif
  96. /**
  97. * Destroy memory instances.
  98. */
  99. static void
  100. memories_deinstantiate(WASMModuleInstance *module_inst,
  101. WASMMemoryInstance **memories, uint32 count)
  102. {
  103. uint32 i;
  104. if (memories) {
  105. for (i = 0; i < count; i++) {
  106. if (memories[i]) {
  107. #if WASM_ENABLE_MULTI_MODULE != 0
  108. WASMModule *module = module_inst->module;
  109. if (i < module->import_memory_count
  110. && module->import_memories[i].u.memory.import_module) {
  111. continue;
  112. }
  113. #endif
  114. #if WASM_ENABLE_SHARED_MEMORY != 0
  115. if (memories[i]->is_shared) {
  116. int32 ref_count = shared_memory_dec_reference(
  117. (WASMModuleCommon *)module_inst->module);
  118. bh_assert(ref_count >= 0);
  119. /* if the reference count is not zero,
  120. don't free the memory */
  121. if (ref_count > 0)
  122. continue;
  123. }
  124. #endif
  125. if (memories[i]->heap_handle) {
  126. mem_allocator_destroy(memories[i]->heap_handle);
  127. wasm_runtime_free(memories[i]->heap_handle);
  128. memories[i]->heap_handle = NULL;
  129. }
  130. if (memories[i]->memory_data) {
  131. #ifndef OS_ENABLE_HW_BOUND_CHECK
  132. wasm_runtime_free(memories[i]->memory_data);
  133. #else
  134. #ifdef BH_PLATFORM_WINDOWS
  135. os_mem_decommit(memories[i]->memory_data,
  136. memories[i]->num_bytes_per_page
  137. * memories[i]->cur_page_count);
  138. #endif
  139. os_munmap((uint8 *)memories[i]->memory_data,
  140. 8 * (uint64)BH_GB);
  141. #endif
  142. }
  143. }
  144. }
  145. wasm_runtime_free(memories);
  146. }
  147. (void)module_inst;
  148. }
  149. static WASMMemoryInstance *
  150. memory_instantiate(WASMModuleInstance *module_inst, WASMMemoryInstance *memory,
  151. uint32 num_bytes_per_page, uint32 init_page_count,
  152. uint32 max_page_count, uint32 heap_size, uint32 flags,
  153. char *error_buf, uint32 error_buf_size)
  154. {
  155. WASMModule *module = module_inst->module;
  156. uint64 memory_data_size;
  157. uint32 heap_offset = num_bytes_per_page * init_page_count;
  158. uint32 inc_page_count, aux_heap_base, global_idx;
  159. uint32 bytes_of_last_page, bytes_to_page_end;
  160. uint8 *global_addr;
  161. #ifdef OS_ENABLE_HW_BOUND_CHECK
  162. uint8 *mapped_mem;
  163. uint64 map_size = 8 * (uint64)BH_GB;
  164. uint64 page_size = os_getpagesize();
  165. #endif
  166. #if WASM_ENABLE_SHARED_MEMORY != 0
  167. bool is_shared_memory = flags & 0x02 ? true : false;
  168. /* shared memory */
  169. if (is_shared_memory) {
  170. WASMSharedMemNode *node = wasm_module_get_shared_memory(
  171. (WASMModuleCommon *)module_inst->module);
  172. /* If the memory of this module has been instantiated,
  173. return the memory instance directly */
  174. if (node) {
  175. uint32 ref_count;
  176. ref_count = shared_memory_inc_reference(
  177. (WASMModuleCommon *)module_inst->module);
  178. bh_assert(ref_count > 0);
  179. memory = (WASMMemoryInstance *)shared_memory_get_memory_inst(node);
  180. bh_assert(memory);
  181. (void)ref_count;
  182. return memory;
  183. }
  184. }
  185. #endif /* end of WASM_ENABLE_SHARED_MEMORY */
  186. if (heap_size > 0 && module_inst->module->malloc_function != (uint32)-1
  187. && module_inst->module->free_function != (uint32)-1) {
  188. /* Disable app heap, use malloc/free function exported
  189. by wasm app to allocate/free memory instead */
  190. heap_size = 0;
  191. }
  192. if (init_page_count == max_page_count && init_page_count == 1) {
  193. /* If only one page and at most one page, we just append
  194. the app heap to the end of linear memory, enlarge the
  195. num_bytes_per_page, and don't change the page count */
  196. heap_offset = num_bytes_per_page;
  197. num_bytes_per_page += heap_size;
  198. if (num_bytes_per_page < heap_size) {
  199. set_error_buf(error_buf, error_buf_size,
  200. "failed to insert app heap into linear memory, "
  201. "try using `--heap_size=0` option");
  202. return NULL;
  203. }
  204. }
  205. else if (heap_size > 0) {
  206. if (init_page_count == max_page_count && init_page_count == 0) {
  207. /* If the memory data size is always 0, we resize it to
  208. one page for app heap */
  209. num_bytes_per_page = heap_size;
  210. heap_offset = 0;
  211. inc_page_count = 1;
  212. }
  213. else if (module->aux_heap_base_global_index != (uint32)-1
  214. && module->aux_heap_base
  215. < num_bytes_per_page * init_page_count) {
  216. /* Insert app heap before __heap_base */
  217. aux_heap_base = module->aux_heap_base;
  218. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  219. if (bytes_of_last_page == 0)
  220. bytes_of_last_page = num_bytes_per_page;
  221. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  222. inc_page_count =
  223. (heap_size - bytes_to_page_end + num_bytes_per_page - 1)
  224. / num_bytes_per_page;
  225. heap_offset = aux_heap_base;
  226. aux_heap_base += heap_size;
  227. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  228. if (bytes_of_last_page == 0)
  229. bytes_of_last_page = num_bytes_per_page;
  230. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  231. if (bytes_to_page_end < 1 * BH_KB) {
  232. aux_heap_base += 1 * BH_KB;
  233. inc_page_count++;
  234. }
  235. /* Adjust __heap_base global value */
  236. global_idx = module->aux_heap_base_global_index;
  237. bh_assert(module_inst->e->globals
  238. && global_idx < module_inst->e->global_count);
  239. global_addr = module_inst->global_data
  240. + module_inst->e->globals[global_idx].data_offset;
  241. *(uint32 *)global_addr = aux_heap_base;
  242. LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base);
  243. }
  244. else {
  245. /* Insert app heap before new page */
  246. inc_page_count =
  247. (heap_size + num_bytes_per_page - 1) / num_bytes_per_page;
  248. heap_offset = num_bytes_per_page * init_page_count;
  249. heap_size = num_bytes_per_page * inc_page_count;
  250. if (heap_size > 0)
  251. heap_size -= 1 * BH_KB;
  252. }
  253. init_page_count += inc_page_count;
  254. max_page_count += inc_page_count;
  255. if (init_page_count > DEFAULT_MAX_PAGES) {
  256. set_error_buf(error_buf, error_buf_size,
  257. "failed to insert app heap into linear memory, "
  258. "try using `--heap_size=0` option");
  259. return NULL;
  260. }
  261. else if (init_page_count == DEFAULT_MAX_PAGES) {
  262. num_bytes_per_page = UINT32_MAX;
  263. init_page_count = max_page_count = 1;
  264. }
  265. if (max_page_count > DEFAULT_MAX_PAGES)
  266. max_page_count = DEFAULT_MAX_PAGES;
  267. }
  268. LOG_VERBOSE("Memory instantiate:");
  269. LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u",
  270. num_bytes_per_page, init_page_count, max_page_count);
  271. LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size);
  272. memory_data_size = (uint64)num_bytes_per_page * init_page_count;
  273. #if WASM_ENABLE_SHARED_MEMORY != 0
  274. if (is_shared_memory) {
  275. /* Allocate max page for shared memory */
  276. memory_data_size = (uint64)num_bytes_per_page * max_page_count;
  277. }
  278. #endif
  279. bh_assert(memory_data_size <= 4 * (uint64)BH_GB);
  280. bh_assert(memory != NULL);
  281. #ifndef OS_ENABLE_HW_BOUND_CHECK
  282. if (memory_data_size > 0
  283. && !(memory->memory_data =
  284. runtime_malloc(memory_data_size, error_buf, error_buf_size))) {
  285. goto fail1;
  286. }
  287. #else
  288. memory_data_size = (memory_data_size + page_size - 1) & ~(page_size - 1);
  289. /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G:
  290. * ea = i + memarg.offset
  291. * both i and memarg.offset are u32 in range 0 to 4G
  292. * so the range of ea is 0 to 8G
  293. */
  294. if (!(memory->memory_data = mapped_mem =
  295. os_mmap(NULL, map_size, MMAP_PROT_NONE, MMAP_MAP_NONE))) {
  296. set_error_buf(error_buf, error_buf_size, "mmap memory failed");
  297. goto fail1;
  298. }
  299. #ifdef BH_PLATFORM_WINDOWS
  300. if (!os_mem_commit(mapped_mem, memory_data_size,
  301. MMAP_PROT_READ | MMAP_PROT_WRITE)) {
  302. set_error_buf(error_buf, error_buf_size, "commit memory failed");
  303. os_munmap(mapped_mem, map_size);
  304. goto fail1;
  305. }
  306. #endif
  307. if (os_mprotect(mapped_mem, memory_data_size,
  308. MMAP_PROT_READ | MMAP_PROT_WRITE)
  309. != 0) {
  310. set_error_buf(error_buf, error_buf_size, "mprotect memory failed");
  311. goto fail2;
  312. }
  313. /* Newly allocated pages are filled with zero by the OS, we don't fill it
  314. * again here */
  315. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  316. if (memory_data_size > UINT32_MAX)
  317. memory_data_size = (uint32)memory_data_size;
  318. memory->module_type = Wasm_Module_Bytecode;
  319. memory->num_bytes_per_page = num_bytes_per_page;
  320. memory->cur_page_count = init_page_count;
  321. memory->max_page_count = max_page_count;
  322. memory->memory_data_size = (uint32)memory_data_size;
  323. memory->heap_data = memory->memory_data + heap_offset;
  324. memory->heap_data_end = memory->heap_data + heap_size;
  325. memory->memory_data_end = memory->memory_data + (uint32)memory_data_size;
  326. /* Initialize heap */
  327. if (heap_size > 0) {
  328. uint32 heap_struct_size = mem_allocator_get_heap_struct_size();
  329. if (!(memory->heap_handle = runtime_malloc(
  330. (uint64)heap_struct_size, error_buf, error_buf_size))) {
  331. goto fail2;
  332. }
  333. if (!mem_allocator_create_with_struct_and_pool(
  334. memory->heap_handle, heap_struct_size, memory->heap_data,
  335. heap_size)) {
  336. set_error_buf(error_buf, error_buf_size, "init app heap failed");
  337. goto fail3;
  338. }
  339. }
  340. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  341. if (memory_data_size > 0) {
  342. #if UINTPTR_MAX == UINT64_MAX
  343. memory->mem_bound_check_1byte.u64 = memory_data_size - 1;
  344. memory->mem_bound_check_2bytes.u64 = memory_data_size - 2;
  345. memory->mem_bound_check_4bytes.u64 = memory_data_size - 4;
  346. memory->mem_bound_check_8bytes.u64 = memory_data_size - 8;
  347. memory->mem_bound_check_16bytes.u64 = memory_data_size - 16;
  348. #else
  349. memory->mem_bound_check_1byte.u32[0] = (uint32)memory_data_size - 1;
  350. memory->mem_bound_check_2bytes.u32[0] = (uint32)memory_data_size - 2;
  351. memory->mem_bound_check_4bytes.u32[0] = (uint32)memory_data_size - 4;
  352. memory->mem_bound_check_8bytes.u32[0] = (uint32)memory_data_size - 8;
  353. memory->mem_bound_check_16bytes.u32[0] = (uint32)memory_data_size - 16;
  354. #endif
  355. }
  356. #endif
  357. #if WASM_ENABLE_SHARED_MEMORY != 0
  358. if (is_shared_memory) {
  359. memory->is_shared = true;
  360. if (!shared_memory_set_memory_inst(
  361. (WASMModuleCommon *)module_inst->module,
  362. (WASMMemoryInstanceCommon *)memory)) {
  363. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  364. goto fail4;
  365. }
  366. }
  367. #endif
  368. LOG_VERBOSE("Memory instantiate success.");
  369. return memory;
  370. #if WASM_ENABLE_SHARED_MEMORY != 0
  371. fail4:
  372. if (heap_size > 0)
  373. mem_allocator_destroy(memory->heap_handle);
  374. #endif
  375. fail3:
  376. if (heap_size > 0)
  377. wasm_runtime_free(memory->heap_handle);
  378. fail2:
  379. #ifndef OS_ENABLE_HW_BOUND_CHECK
  380. if (memory->memory_data)
  381. wasm_runtime_free(memory->memory_data);
  382. #else
  383. #ifdef BH_PLATFORM_WINDOWS
  384. os_mem_decommit(mapped_mem, memory_data_size);
  385. #endif
  386. os_munmap(mapped_mem, map_size);
  387. #endif
  388. fail1:
  389. return NULL;
  390. }
  391. /**
  392. * Instantiate memories in a module.
  393. */
  394. static WASMMemoryInstance **
  395. memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  396. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  397. {
  398. WASMImport *import;
  399. uint32 mem_index = 0, i,
  400. memory_count = module->import_memory_count + module->memory_count;
  401. uint64 total_size;
  402. WASMMemoryInstance **memories, *memory;
  403. total_size = sizeof(WASMMemoryInstance *) * (uint64)memory_count;
  404. if (!(memories = runtime_malloc(total_size, error_buf, error_buf_size))) {
  405. return NULL;
  406. }
  407. memory = module_inst->global_table_data.memory_instances;
  408. /* instantiate memories from import section */
  409. import = module->import_memories;
  410. for (i = 0; i < module->import_memory_count; i++, import++, memory++) {
  411. uint32 num_bytes_per_page = import->u.memory.num_bytes_per_page;
  412. uint32 init_page_count = import->u.memory.init_page_count;
  413. uint32 max_page_count = import->u.memory.max_page_count;
  414. uint32 flags = import->u.memory.flags;
  415. uint32 actual_heap_size = heap_size;
  416. #if WASM_ENABLE_MULTI_MODULE != 0
  417. if (import->u.memory.import_module != NULL) {
  418. WASMModuleInstance *module_inst_linked;
  419. if (!(module_inst_linked = get_sub_module_inst(
  420. module_inst, import->u.memory.import_module))) {
  421. set_error_buf(error_buf, error_buf_size, "unknown memory");
  422. memories_deinstantiate(module_inst, memories, memory_count);
  423. return NULL;
  424. }
  425. if (!(memories[mem_index++] = wasm_lookup_memory(
  426. module_inst_linked, import->u.memory.field_name))) {
  427. set_error_buf(error_buf, error_buf_size, "unknown memory");
  428. memories_deinstantiate(module_inst, memories, memory_count);
  429. return NULL;
  430. }
  431. }
  432. else
  433. #endif
  434. {
  435. if (!(memories[mem_index++] = memory_instantiate(
  436. module_inst, memory, num_bytes_per_page, init_page_count,
  437. max_page_count, actual_heap_size, flags, error_buf,
  438. error_buf_size))) {
  439. memories_deinstantiate(module_inst, memories, memory_count);
  440. return NULL;
  441. }
  442. }
  443. }
  444. /* instantiate memories from memory section */
  445. for (i = 0; i < module->memory_count; i++, memory++) {
  446. if (!(memories[mem_index++] = memory_instantiate(
  447. module_inst, memory, module->memories[i].num_bytes_per_page,
  448. module->memories[i].init_page_count,
  449. module->memories[i].max_page_count, heap_size,
  450. module->memories[i].flags, error_buf, error_buf_size))) {
  451. memories_deinstantiate(module_inst, memories, memory_count);
  452. return NULL;
  453. }
  454. }
  455. bh_assert(mem_index == memory_count);
  456. (void)module_inst;
  457. return memories;
  458. }
  459. /**
  460. * Destroy table instances.
  461. */
  462. static void
  463. tables_deinstantiate(WASMModuleInstance *module_inst)
  464. {
  465. if (module_inst->tables) {
  466. wasm_runtime_free(module_inst->tables);
  467. }
  468. #if WASM_ENABLE_MULTI_MODULE != 0
  469. if (module_inst->e->table_insts_linked) {
  470. wasm_runtime_free(module_inst->e->table_insts_linked);
  471. }
  472. #endif
  473. }
  474. /**
  475. * Instantiate tables in a module.
  476. */
  477. static WASMTableInstance **
  478. tables_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  479. WASMTableInstance *first_table, char *error_buf,
  480. uint32 error_buf_size)
  481. {
  482. WASMImport *import;
  483. uint32 table_index = 0, i;
  484. uint32 table_count = module->import_table_count + module->table_count;
  485. uint64 total_size = (uint64)sizeof(WASMTableInstance *) * table_count;
  486. WASMTableInstance **tables, *table = first_table;
  487. #if WASM_ENABLE_MULTI_MODULE != 0
  488. uint64 total_size_of_tables_linked =
  489. (uint64)sizeof(WASMTableInstance *) * module->import_table_count;
  490. WASMTableInstance **table_linked = NULL;
  491. #endif
  492. if (!(tables = runtime_malloc(total_size, error_buf, error_buf_size))) {
  493. return NULL;
  494. }
  495. #if WASM_ENABLE_MULTI_MODULE != 0
  496. if (module->import_table_count > 0
  497. && !(module_inst->e->table_insts_linked = table_linked = runtime_malloc(
  498. total_size_of_tables_linked, error_buf, error_buf_size))) {
  499. goto fail;
  500. }
  501. #endif
  502. /* instantiate tables from import section */
  503. import = module->import_tables;
  504. for (i = 0; i < module->import_table_count; i++, import++) {
  505. uint32 max_size_fixed = 0;
  506. #if WASM_ENABLE_MULTI_MODULE != 0
  507. WASMTableInstance *table_inst_linked = NULL;
  508. WASMModuleInstance *module_inst_linked = NULL;
  509. if (import->u.table.import_module) {
  510. if (!(module_inst_linked = get_sub_module_inst(
  511. module_inst, import->u.table.import_module))) {
  512. set_error_buf(error_buf, error_buf_size, "unknown table");
  513. goto fail;
  514. }
  515. if (!(table_inst_linked = wasm_lookup_table(
  516. module_inst_linked, import->u.table.field_name))) {
  517. set_error_buf(error_buf, error_buf_size, "unknown table");
  518. goto fail;
  519. }
  520. total_size = offsetof(WASMTableInstance, elems);
  521. }
  522. else
  523. #endif
  524. {
  525. /* in order to save memory, alloc resource as few as possible */
  526. max_size_fixed = import->u.table.possible_grow
  527. ? import->u.table.max_size
  528. : import->u.table.init_size;
  529. /* it is a built-in table, every module has its own */
  530. total_size = offsetof(WASMTableInstance, elems);
  531. /* store function indexes for non-gc, object pointers for gc */
  532. total_size += (uint64)sizeof(table_elem_type_t) * max_size_fixed;
  533. }
  534. tables[table_index++] = table;
  535. #if WASM_ENABLE_GC == 0
  536. /* Set all elements to -1 to mark them as uninitialized elements */
  537. memset(table, -1, (uint32)total_size);
  538. #else
  539. /* For GC, all elements have already been set to NULL_REF (0) as
  540. uninitialized elements */
  541. #endif
  542. #if WASM_ENABLE_MULTI_MODULE != 0
  543. *table_linked = table_inst_linked;
  544. if (table_inst_linked != NULL) {
  545. #if WASM_ENABLE_GC != 0
  546. table->elem_type = table_inst_linked->elem_type;
  547. table->elem_ref_type = table_inst_linked->elem_ref_type;
  548. #endif
  549. table->cur_size = table_inst_linked->cur_size;
  550. table->max_size = table_inst_linked->max_size;
  551. }
  552. else
  553. #endif
  554. {
  555. #if WASM_ENABLE_GC != 0
  556. table->elem_type = import->u.table.elem_type;
  557. table->elem_ref_type = import->u.table.elem_ref_type;
  558. #endif
  559. table->cur_size = import->u.table.init_size;
  560. table->max_size = max_size_fixed;
  561. }
  562. table = (WASMTableInstance *)((uint8 *)table + (uint32)total_size);
  563. #if WASM_ENABLE_MULTI_MODULE != 0
  564. table_linked++;
  565. #endif
  566. }
  567. /* instantiate tables from table section */
  568. for (i = 0; i < module->table_count; i++) {
  569. uint32 max_size_fixed = 0;
  570. total_size = offsetof(WASMTableInstance, elems);
  571. #if WASM_ENABLE_MULTI_MODULE != 0
  572. /* in case, a module which imports this table will grow it */
  573. max_size_fixed = module->tables[i].max_size;
  574. #else
  575. max_size_fixed = module->tables[i].possible_grow
  576. ? module->tables[i].max_size
  577. : module->tables[i].init_size;
  578. #endif
  579. #if WASM_ENABLE_GC == 0
  580. /* Store function indexes */
  581. total_size += sizeof(uint32) * (uint64)max_size_fixed;
  582. #else
  583. /* Store object pointers */
  584. total_size += sizeof(uintptr_t) * (uint64)max_size_fixed;
  585. #endif
  586. tables[table_index++] = table;
  587. #if WASM_ENABLE_GC == 0
  588. /* Set all elements to -1 to mark them as uninitialized elements */
  589. memset(table, -1, (uint32)total_size);
  590. #else
  591. /* For GC, all elements have already been set to NULL_REF (0) as
  592. uninitialized elements */
  593. #endif
  594. #if WASM_ENABLE_GC != 0
  595. table->elem_type = module->tables[i].elem_type;
  596. table->elem_ref_type = module->tables[i].elem_ref_type;
  597. #endif
  598. table->cur_size = module->tables[i].init_size;
  599. table->max_size = max_size_fixed;
  600. table = (WASMTableInstance *)((uint8 *)table + (uint32)total_size);
  601. }
  602. bh_assert(table_index == table_count);
  603. (void)module_inst;
  604. return tables;
  605. #if WASM_ENABLE_MULTI_MODULE != 0
  606. fail:
  607. wasm_runtime_free(tables);
  608. return NULL;
  609. #endif
  610. }
  611. /**
  612. * Destroy function instances.
  613. */
  614. static void
  615. functions_deinstantiate(WASMFunctionInstance *functions, uint32 count)
  616. {
  617. if (functions) {
  618. wasm_runtime_free(functions);
  619. }
  620. }
  621. /**
  622. * Instantiate functions in a module.
  623. */
  624. static WASMFunctionInstance *
  625. functions_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  626. char *error_buf, uint32 error_buf_size)
  627. {
  628. WASMImport *import;
  629. uint32 i,
  630. function_count = module->import_function_count + module->function_count;
  631. uint64 total_size = sizeof(WASMFunctionInstance) * (uint64)function_count;
  632. WASMFunctionInstance *functions, *function;
  633. if (!(functions = runtime_malloc(total_size, error_buf, error_buf_size))) {
  634. return NULL;
  635. }
  636. total_size = sizeof(void *) * (uint64)module->import_function_count;
  637. if (total_size > 0
  638. && !(module_inst->import_func_ptrs =
  639. runtime_malloc(total_size, error_buf, error_buf_size))) {
  640. wasm_runtime_free(functions);
  641. return NULL;
  642. }
  643. /* instantiate functions from import section */
  644. function = functions;
  645. import = module->import_functions;
  646. for (i = 0; i < module->import_function_count; i++, import++) {
  647. function->is_import_func = true;
  648. #if WASM_ENABLE_MULTI_MODULE != 0
  649. if (import->u.function.import_module) {
  650. function->import_module_inst = get_sub_module_inst(
  651. module_inst, import->u.function.import_module);
  652. if (function->import_module_inst) {
  653. function->import_func_inst =
  654. wasm_lookup_function(function->import_module_inst,
  655. import->u.function.field_name, NULL);
  656. }
  657. }
  658. #endif /* WASM_ENABLE_MULTI_MODULE */
  659. function->u.func_import = &import->u.function;
  660. function->param_cell_num = import->u.function.func_type->param_cell_num;
  661. function->ret_cell_num = import->u.function.func_type->ret_cell_num;
  662. function->param_count =
  663. (uint16)function->u.func_import->func_type->param_count;
  664. function->param_types = function->u.func_import->func_type->types;
  665. function->local_cell_num = 0;
  666. function->local_count = 0;
  667. function->local_types = NULL;
  668. /* Copy the function pointer to current instance */
  669. module_inst->import_func_ptrs[i] =
  670. function->u.func_import->func_ptr_linked;
  671. function++;
  672. }
  673. /* instantiate functions from function section */
  674. for (i = 0; i < module->function_count; i++) {
  675. function->is_import_func = false;
  676. function->u.func = module->functions[i];
  677. function->param_cell_num = function->u.func->param_cell_num;
  678. function->ret_cell_num = function->u.func->ret_cell_num;
  679. function->local_cell_num = function->u.func->local_cell_num;
  680. function->param_count =
  681. (uint16)function->u.func->func_type->param_count;
  682. function->local_count = (uint16)function->u.func->local_count;
  683. function->param_types = function->u.func->func_type->types;
  684. function->local_types = function->u.func->local_types;
  685. function->local_offsets = function->u.func->local_offsets;
  686. #if WASM_ENABLE_FAST_INTERP != 0
  687. function->const_cell_num = function->u.func->const_cell_num;
  688. #endif
  689. function++;
  690. }
  691. bh_assert((uint32)(function - functions) == function_count);
  692. #if WASM_ENABLE_FAST_JIT != 0
  693. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  694. #endif
  695. return functions;
  696. }
  697. /**
  698. * Destroy global instances.
  699. */
  700. static void
  701. globals_deinstantiate(WASMGlobalInstance *globals)
  702. {
  703. if (globals)
  704. wasm_runtime_free(globals);
  705. }
  706. static bool
  707. check_global_init_expr(const WASMModule *module, uint32 global_index,
  708. char *error_buf, uint32 error_buf_size)
  709. {
  710. if (global_index >= module->import_global_count + module->global_count) {
  711. set_error_buf_v(error_buf, error_buf_size, "unknown global %d",
  712. global_index);
  713. return false;
  714. }
  715. #if WASM_ENABLE_GC == 0
  716. /**
  717. * Currently, constant expressions occurring as initializers of
  718. * globals are further constrained in that contained global.get
  719. * instructions are only allowed to refer to imported globals.
  720. *
  721. * And initializer expression cannot reference a mutable global.
  722. */
  723. if (global_index >= module->import_global_count
  724. || (module->import_globals + global_index)->u.global.is_mutable) {
  725. set_error_buf(error_buf, error_buf_size,
  726. "constant expression required");
  727. return false;
  728. }
  729. #endif
  730. return true;
  731. }
  732. /**
  733. * Instantiate globals in a module.
  734. */
  735. static WASMGlobalInstance *
  736. globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  737. char *error_buf, uint32 error_buf_size)
  738. {
  739. WASMImport *import;
  740. uint32 global_data_offset = 0;
  741. uint32 i, global_count = module->import_global_count + module->global_count;
  742. uint64 total_size = sizeof(WASMGlobalInstance) * (uint64)global_count;
  743. WASMGlobalInstance *globals, *global;
  744. if (!(globals = runtime_malloc(total_size, error_buf, error_buf_size))) {
  745. return NULL;
  746. }
  747. /* instantiate globals from import section */
  748. global = globals;
  749. import = module->import_globals;
  750. for (i = 0; i < module->import_global_count; i++, import++) {
  751. WASMGlobalImport *global_import = &import->u.global;
  752. global->type = global_import->type;
  753. global->is_mutable = global_import->is_mutable;
  754. #if WASM_ENABLE_GC != 0
  755. global->ref_type = global_import->ref_type;
  756. #endif
  757. #if WASM_ENABLE_MULTI_MODULE != 0
  758. if (global_import->import_module) {
  759. if (!(global->import_module_inst = get_sub_module_inst(
  760. module_inst, global_import->import_module))) {
  761. set_error_buf(error_buf, error_buf_size, "unknown global");
  762. goto fail;
  763. }
  764. if (!(global->import_global_inst = wasm_lookup_global(
  765. global->import_module_inst, global_import->field_name))) {
  766. set_error_buf(error_buf, error_buf_size, "unknown global");
  767. goto fail;
  768. }
  769. /* The linked global instance has been initialized, we
  770. just need to copy the value. */
  771. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  772. &(global_import->import_global_linked->init_expr),
  773. sizeof(WASMValue));
  774. }
  775. else
  776. #endif
  777. {
  778. /* native globals share their initial_values in one module */
  779. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  780. &(global_import->global_data_linked),
  781. sizeof(WASMValue));
  782. }
  783. #if WASM_ENABLE_FAST_JIT != 0
  784. bh_assert(global_data_offset == global_import->data_offset);
  785. #endif
  786. global->data_offset = global_data_offset;
  787. global_data_offset += wasm_value_type_size(global->type);
  788. global++;
  789. }
  790. /* instantiate globals from global section */
  791. for (i = 0; i < module->global_count; i++) {
  792. InitializerExpression *init_expr = &(module->globals[i].init_expr);
  793. global->type = module->globals[i].type;
  794. global->is_mutable = module->globals[i].is_mutable;
  795. #if WASM_ENABLE_FAST_JIT != 0
  796. bh_assert(global_data_offset == module->globals[i].data_offset);
  797. #endif
  798. global->data_offset = global_data_offset;
  799. global_data_offset += wasm_value_type_size(global->type);
  800. #if WASM_ENABLE_GC != 0
  801. global->ref_type = module->globals[i].ref_type;
  802. #endif
  803. if (init_expr->init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  804. if (!check_global_init_expr(module, init_expr->u.global_index,
  805. error_buf, error_buf_size)) {
  806. goto fail;
  807. }
  808. bh_memcpy_s(
  809. &(global->initial_value), sizeof(WASMValue),
  810. &(globals[init_expr->u.global_index].initial_value),
  811. sizeof(globals[init_expr->u.global_index].initial_value));
  812. }
  813. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  814. else if (init_expr->init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST) {
  815. /* UINT32_MAX indicates that it is an null reference */
  816. global->initial_value.u32 = (uint32)UINT32_MAX;
  817. }
  818. #endif
  819. #if WASM_ENABLE_GC != 0
  820. else if (init_expr->init_expr_type == INIT_EXPR_TYPE_I31_NEW) {
  821. global->initial_value.gc_obj =
  822. (void *)wasm_i31_obj_new(init_expr->u.i32);
  823. }
  824. #endif
  825. else {
  826. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  827. &(init_expr->u), sizeof(init_expr->u));
  828. }
  829. global++;
  830. }
  831. bh_assert((uint32)(global - globals) == global_count);
  832. bh_assert(global_data_offset == module->global_data_size);
  833. (void)module_inst;
  834. return globals;
  835. fail:
  836. wasm_runtime_free(globals);
  837. return NULL;
  838. }
  839. /**
  840. * Return export function count in module export section.
  841. */
  842. static uint32
  843. get_export_count(const WASMModule *module, uint8 kind)
  844. {
  845. WASMExport *export = module->exports;
  846. uint32 count = 0, i;
  847. for (i = 0; i < module->export_count; i++, export ++)
  848. if (export->kind == kind)
  849. count++;
  850. return count;
  851. }
  852. /**
  853. * Destroy export function instances.
  854. */
  855. static void
  856. export_functions_deinstantiate(WASMExportFuncInstance *functions)
  857. {
  858. if (functions)
  859. wasm_runtime_free(functions);
  860. }
  861. /**
  862. * Instantiate export functions in a module.
  863. */
  864. static WASMExportFuncInstance *
  865. export_functions_instantiate(const WASMModule *module,
  866. WASMModuleInstance *module_inst,
  867. uint32 export_func_count, char *error_buf,
  868. uint32 error_buf_size)
  869. {
  870. WASMExportFuncInstance *export_funcs, *export_func;
  871. WASMExport *export = module->exports;
  872. uint32 i;
  873. uint64 total_size =
  874. sizeof(WASMExportFuncInstance) * (uint64)export_func_count;
  875. if (!(export_func = export_funcs =
  876. runtime_malloc(total_size, error_buf, error_buf_size))) {
  877. return NULL;
  878. }
  879. for (i = 0; i < module->export_count; i++, export ++)
  880. if (export->kind == EXPORT_KIND_FUNC) {
  881. export_func->name = export->name;
  882. export_func->function = &module_inst->e->functions[export->index];
  883. export_func++;
  884. }
  885. bh_assert((uint32)(export_func - export_funcs) == export_func_count);
  886. return export_funcs;
  887. }
  888. #if WASM_ENABLE_MULTI_MODULE != 0
  889. static void
  890. export_globals_deinstantiate(WASMExportGlobInstance *globals)
  891. {
  892. if (globals)
  893. wasm_runtime_free(globals);
  894. }
  895. static WASMExportGlobInstance *
  896. export_globals_instantiate(const WASMModule *module,
  897. WASMModuleInstance *module_inst,
  898. uint32 export_glob_count, char *error_buf,
  899. uint32 error_buf_size)
  900. {
  901. WASMExportGlobInstance *export_globals, *export_global;
  902. WASMExport *export = module->exports;
  903. uint32 i;
  904. uint64 total_size =
  905. sizeof(WASMExportGlobInstance) * (uint64)export_glob_count;
  906. if (!(export_global = export_globals =
  907. runtime_malloc(total_size, error_buf, error_buf_size))) {
  908. return NULL;
  909. }
  910. for (i = 0; i < module->export_count; i++, export ++)
  911. if (export->kind == EXPORT_KIND_GLOBAL) {
  912. export_global->name = export->name;
  913. export_global->global = &module_inst->e->globals[export->index];
  914. export_global++;
  915. }
  916. bh_assert((uint32)(export_global - export_globals) == export_glob_count);
  917. return export_globals;
  918. }
  919. #endif
  920. static WASMFunctionInstance *
  921. lookup_post_instantiate_func(WASMModuleInstance *module_inst,
  922. const char *func_name)
  923. {
  924. WASMFunctionInstance *func;
  925. WASMFuncType *func_type;
  926. if (!(func = wasm_lookup_function(module_inst, func_name, NULL)))
  927. /* Not found */
  928. return NULL;
  929. func_type = func->u.func->func_type;
  930. if (!(func_type->param_count == 0 && func_type->result_count == 0))
  931. /* Not a valid function type, ignore it */
  932. return NULL;
  933. return func;
  934. }
  935. static bool
  936. execute_post_instantiate_functions(WASMModuleInstance *module_inst,
  937. bool is_sub_inst, WASMExecEnv *exec_env_main)
  938. {
  939. WASMFunctionInstance *start_func = module_inst->e->start_function;
  940. WASMFunctionInstance *initialize_func = NULL;
  941. WASMFunctionInstance *post_inst_func = NULL;
  942. WASMFunctionInstance *call_ctors_func = NULL;
  943. #if WASM_ENABLE_LIBC_WASI != 0
  944. WASMModule *module = module_inst->module;
  945. #endif
  946. WASMModuleInstanceCommon *module_inst_main = NULL;
  947. #ifdef OS_ENABLE_HW_BOUND_CHECK
  948. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  949. #endif
  950. WASMExecEnv *exec_env = NULL, *exec_env_created = NULL;
  951. bool ret = false;
  952. #if WASM_ENABLE_LIBC_WASI != 0
  953. /*
  954. * WASI reactor instances may assume that _initialize will be called by
  955. * the environment at most once, and that none of their other exports
  956. * are accessed before that call.
  957. */
  958. if (!is_sub_inst && module->import_wasi_api) {
  959. initialize_func =
  960. lookup_post_instantiate_func(module_inst, "_initialize");
  961. }
  962. #endif
  963. /* Execute possible "__post_instantiate" function if wasm app is
  964. compiled by emsdk's early version */
  965. if (!is_sub_inst) {
  966. post_inst_func =
  967. lookup_post_instantiate_func(module_inst, "__post_instantiate");
  968. }
  969. #if WASM_ENABLE_BULK_MEMORY != 0
  970. /* Only execute the memory init function for main instance since
  971. the data segments will be dropped once initialized */
  972. if (!is_sub_inst
  973. #if WASM_ENABLE_LIBC_WASI != 0
  974. && !module->import_wasi_api
  975. #endif
  976. ) {
  977. call_ctors_func =
  978. lookup_post_instantiate_func(module_inst, "__wasm_call_ctors");
  979. }
  980. #endif
  981. if (!start_func && !initialize_func && !post_inst_func
  982. && !call_ctors_func) {
  983. /* No post instantiation functions to call */
  984. return true;
  985. }
  986. if (is_sub_inst) {
  987. bh_assert(exec_env_main);
  988. #ifdef OS_ENABLE_HW_BOUND_CHECK
  989. bh_assert(exec_env_tls == exec_env_main);
  990. (void)exec_env_tls;
  991. #endif
  992. exec_env = exec_env_main;
  993. /* Temporarily replace parent exec_env's module inst to current
  994. module inst to avoid checking failure when calling the
  995. wasm functions, and ensure that the exec_env's module inst
  996. is the correct one. */
  997. module_inst_main = exec_env_main->module_inst;
  998. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  999. }
  1000. else {
  1001. /* Try using the existing exec_env */
  1002. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1003. exec_env = exec_env_tls;
  1004. #endif
  1005. #if WASM_ENABLE_THREAD_MGR != 0
  1006. if (!exec_env)
  1007. exec_env = wasm_clusters_search_exec_env(
  1008. (WASMModuleInstanceCommon *)module_inst);
  1009. #endif
  1010. if (!exec_env) {
  1011. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1012. (WASMModuleInstanceCommon *)module_inst,
  1013. module_inst->default_wasm_stack_size))) {
  1014. wasm_set_exception(module_inst, "allocate memory failed");
  1015. return false;
  1016. }
  1017. }
  1018. else {
  1019. /* Temporarily replace exec_env's module inst with current
  1020. module inst to ensure that the exec_env's module inst
  1021. is the correct one. */
  1022. module_inst_main = exec_env->module_inst;
  1023. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  1024. }
  1025. }
  1026. /* Execute start function for both main insance and sub instance */
  1027. if (start_func && !wasm_call_function(exec_env, start_func, 0, NULL)) {
  1028. goto fail;
  1029. }
  1030. if (initialize_func
  1031. && !wasm_call_function(exec_env, initialize_func, 0, NULL)) {
  1032. goto fail;
  1033. }
  1034. if (post_inst_func
  1035. && !wasm_call_function(exec_env, post_inst_func, 0, NULL)) {
  1036. goto fail;
  1037. }
  1038. if (call_ctors_func
  1039. && !wasm_call_function(exec_env, call_ctors_func, 0, NULL)) {
  1040. goto fail;
  1041. }
  1042. ret = true;
  1043. fail:
  1044. if (is_sub_inst) {
  1045. /* Restore the parent exec_env's module inst */
  1046. exec_env_main->module_inst = module_inst_main;
  1047. }
  1048. else {
  1049. if (module_inst_main)
  1050. /* Restore the existing exec_env's module inst */
  1051. exec_env->module_inst = module_inst_main;
  1052. if (exec_env_created)
  1053. wasm_exec_env_destroy(exec_env_created);
  1054. }
  1055. return ret;
  1056. }
  1057. static bool
  1058. execute_malloc_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1059. WASMFunctionInstance *malloc_func,
  1060. WASMFunctionInstance *retain_func, uint32 size,
  1061. uint32 *p_result)
  1062. {
  1063. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1064. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1065. #endif
  1066. WASMExecEnv *exec_env_created = NULL;
  1067. WASMModuleInstanceCommon *module_inst_old = NULL;
  1068. uint32 argv[2], argc;
  1069. bool ret;
  1070. argv[0] = size;
  1071. argc = 1;
  1072. /* if __retain is exported, then this module is compiled by
  1073. assemblyscript, the memory should be managed by as's runtime,
  1074. in this case we need to call the retain function after malloc
  1075. the memory */
  1076. if (retain_func) {
  1077. /* the malloc functino from assemblyscript is:
  1078. function __new(size: usize, id: u32)
  1079. id = 0 means this is an ArrayBuffer object */
  1080. argv[1] = 0;
  1081. argc = 2;
  1082. }
  1083. if (exec_env) {
  1084. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1085. if (exec_env_tls) {
  1086. bh_assert(exec_env_tls == exec_env);
  1087. }
  1088. #endif
  1089. bh_assert(exec_env->module_inst
  1090. == (WASMModuleInstanceCommon *)module_inst);
  1091. }
  1092. else {
  1093. /* Try using the existing exec_env */
  1094. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1095. exec_env = exec_env_tls;
  1096. #endif
  1097. #if WASM_ENABLE_THREAD_MGR != 0
  1098. if (!exec_env)
  1099. exec_env = wasm_clusters_search_exec_env(
  1100. (WASMModuleInstanceCommon *)module_inst);
  1101. #endif
  1102. if (!exec_env) {
  1103. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1104. (WASMModuleInstanceCommon *)module_inst,
  1105. module_inst->default_wasm_stack_size))) {
  1106. wasm_set_exception(module_inst, "allocate memory failed");
  1107. return false;
  1108. }
  1109. }
  1110. else {
  1111. /* Temporarily replace exec_env's module inst with current
  1112. module inst to ensure that the exec_env's module inst
  1113. is the correct one. */
  1114. module_inst_old = exec_env->module_inst;
  1115. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  1116. }
  1117. }
  1118. ret = wasm_call_function(exec_env, malloc_func, argc, argv);
  1119. if (retain_func && ret)
  1120. ret = wasm_call_function(exec_env, retain_func, 1, argv);
  1121. if (module_inst_old)
  1122. /* Restore the existing exec_env's module inst */
  1123. exec_env->module_inst = module_inst_old;
  1124. if (exec_env_created)
  1125. wasm_exec_env_destroy(exec_env_created);
  1126. if (ret)
  1127. *p_result = argv[0];
  1128. return ret;
  1129. }
  1130. static bool
  1131. execute_free_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1132. WASMFunctionInstance *free_func, uint32 offset)
  1133. {
  1134. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1135. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1136. #endif
  1137. WASMExecEnv *exec_env_created = NULL;
  1138. WASMModuleInstanceCommon *module_inst_old = NULL;
  1139. uint32 argv[2];
  1140. bool ret;
  1141. argv[0] = offset;
  1142. if (exec_env) {
  1143. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1144. if (exec_env_tls) {
  1145. bh_assert(exec_env_tls == exec_env);
  1146. }
  1147. #endif
  1148. bh_assert(exec_env->module_inst
  1149. == (WASMModuleInstanceCommon *)module_inst);
  1150. }
  1151. else {
  1152. /* Try using the existing exec_env */
  1153. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1154. exec_env = exec_env_tls;
  1155. #endif
  1156. #if WASM_ENABLE_THREAD_MGR != 0
  1157. if (!exec_env)
  1158. exec_env = wasm_clusters_search_exec_env(
  1159. (WASMModuleInstanceCommon *)module_inst);
  1160. #endif
  1161. if (!exec_env) {
  1162. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1163. (WASMModuleInstanceCommon *)module_inst,
  1164. module_inst->default_wasm_stack_size))) {
  1165. wasm_set_exception(module_inst, "allocate memory failed");
  1166. return false;
  1167. }
  1168. }
  1169. else {
  1170. /* Temporarily replace exec_env's module inst with current
  1171. module inst to ensure that the exec_env's module inst
  1172. is the correct one. */
  1173. module_inst_old = exec_env->module_inst;
  1174. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  1175. }
  1176. }
  1177. ret = wasm_call_function(exec_env, free_func, 1, argv);
  1178. if (module_inst_old)
  1179. /* Restore the existing exec_env's module inst */
  1180. exec_env->module_inst = module_inst_old;
  1181. if (exec_env_created)
  1182. wasm_exec_env_destroy(exec_env_created);
  1183. return ret;
  1184. }
  1185. #if WASM_ENABLE_MULTI_MODULE != 0
  1186. static bool
  1187. sub_module_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
  1188. uint32 stack_size, uint32 heap_size, char *error_buf,
  1189. uint32 error_buf_size)
  1190. {
  1191. bh_list *sub_module_inst_list = module_inst->e->sub_module_inst_list;
  1192. WASMRegisteredModule *sub_module_list_node =
  1193. bh_list_first_elem(module->import_module_list);
  1194. while (sub_module_list_node) {
  1195. WASMSubModInstNode *sub_module_inst_list_node = NULL;
  1196. WASMModule *sub_module = (WASMModule *)sub_module_list_node->module;
  1197. WASMModuleInstance *sub_module_inst = NULL;
  1198. sub_module_inst =
  1199. wasm_instantiate(sub_module, false, NULL, stack_size, heap_size,
  1200. error_buf, error_buf_size);
  1201. if (!sub_module_inst) {
  1202. LOG_DEBUG("instantiate %s failed",
  1203. sub_module_list_node->module_name);
  1204. goto failed;
  1205. }
  1206. sub_module_inst_list_node = runtime_malloc(sizeof(WASMSubModInstNode),
  1207. error_buf, error_buf_size);
  1208. if (!sub_module_inst_list_node) {
  1209. LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d",
  1210. sizeof(WASMSubModInstNode));
  1211. goto failed;
  1212. }
  1213. sub_module_inst_list_node->module_inst = sub_module_inst;
  1214. sub_module_inst_list_node->module_name =
  1215. sub_module_list_node->module_name;
  1216. bh_list_status ret =
  1217. bh_list_insert(sub_module_inst_list, sub_module_inst_list_node);
  1218. bh_assert(BH_LIST_SUCCESS == ret);
  1219. (void)ret;
  1220. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  1221. continue;
  1222. failed:
  1223. if (sub_module_inst_list_node) {
  1224. bh_list_remove(sub_module_inst_list, sub_module_inst_list_node);
  1225. wasm_runtime_free(sub_module_inst_list_node);
  1226. }
  1227. if (sub_module_inst)
  1228. wasm_deinstantiate(sub_module_inst, false);
  1229. return false;
  1230. }
  1231. return true;
  1232. }
  1233. static void
  1234. sub_module_deinstantiate(WASMModuleInstance *module_inst)
  1235. {
  1236. bh_list *list = module_inst->e->sub_module_inst_list;
  1237. WASMSubModInstNode *node = bh_list_first_elem(list);
  1238. while (node) {
  1239. WASMSubModInstNode *next_node = bh_list_elem_next(node);
  1240. bh_list_remove(list, node);
  1241. wasm_deinstantiate(node->module_inst, false);
  1242. wasm_runtime_free(node);
  1243. node = next_node;
  1244. }
  1245. }
  1246. #endif
  1247. static bool
  1248. check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf,
  1249. uint32 error_buf_size)
  1250. {
  1251. WASMModule *module = module_inst->module;
  1252. uint32 i;
  1253. for (i = 0; i < module->import_function_count; i++) {
  1254. WASMFunctionImport *func =
  1255. &((module->import_functions + i)->u.function);
  1256. if (!func->func_ptr_linked
  1257. #if WASM_ENABLE_MULTI_MODULE != 0
  1258. && !func->import_func_linked
  1259. #endif
  1260. ) {
  1261. #if WASM_ENABLE_WAMR_COMPILER == 0
  1262. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1263. func->module_name, func->field_name);
  1264. /* will throw exception only if calling */
  1265. #else
  1266. /* do nothing to avoid confused message */
  1267. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1268. }
  1269. }
  1270. for (i = 0; i < module->import_global_count; i++) {
  1271. WASMGlobalImport *global = &((module->import_globals + i)->u.global);
  1272. if (!global->is_linked) {
  1273. #if WASM_ENABLE_SPEC_TEST != 0
  1274. set_error_buf(error_buf, error_buf_size,
  1275. "unknown import or incompatible import type");
  1276. return false;
  1277. #else
  1278. #if WASM_ENABLE_WAMR_COMPILER == 0
  1279. set_error_buf_v(error_buf, error_buf_size,
  1280. "failed to link import global (%s, %s)",
  1281. global->module_name, global->field_name);
  1282. return false;
  1283. #else
  1284. /* do nothing to avoid confused message */
  1285. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1286. #endif /* WASM_ENABLE_SPEC_TEST != 0 */
  1287. }
  1288. }
  1289. return true;
  1290. }
  1291. #if WASM_ENABLE_JIT != 0
  1292. static bool
  1293. init_func_ptrs(WASMModuleInstance *module_inst, WASMModule *module,
  1294. char *error_buf, uint32 error_buf_size)
  1295. {
  1296. uint32 i;
  1297. void **func_ptrs;
  1298. uint64 total_size = (uint64)sizeof(void *) * module_inst->e->function_count;
  1299. /* Allocate memory */
  1300. if (!(func_ptrs = module_inst->func_ptrs =
  1301. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1302. return false;
  1303. }
  1304. /* Set import function pointers */
  1305. for (i = 0; i < module->import_function_count; i++, func_ptrs++) {
  1306. WASMFunctionImport *import_func =
  1307. &module->import_functions[i].u.function;
  1308. /* TODO: handle multi module */
  1309. *func_ptrs = import_func->func_ptr_linked;
  1310. }
  1311. /* The defined function pointers will be set in
  1312. wasm_runtime_set_running_mode, no need to set them here */
  1313. return true;
  1314. }
  1315. #endif /* end of WASM_ENABLE_JIT != 0 */
  1316. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1317. static uint32
  1318. get_smallest_type_idx(WASMModule *module, WASMFuncType *func_type)
  1319. {
  1320. uint32 i;
  1321. for (i = 0; i < module->type_count; i++) {
  1322. if (func_type == module->types[i])
  1323. return i;
  1324. }
  1325. bh_assert(0);
  1326. return -1;
  1327. }
  1328. static bool
  1329. init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf,
  1330. uint32 error_buf_size)
  1331. {
  1332. uint32 i;
  1333. uint64 total_size = (uint64)sizeof(uint32) * module_inst->e->function_count;
  1334. /* Allocate memory */
  1335. if (!(module_inst->func_type_indexes =
  1336. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1337. return false;
  1338. }
  1339. for (i = 0; i < module_inst->e->function_count; i++) {
  1340. WASMFunctionInstance *func_inst = module_inst->e->functions + i;
  1341. WASMFuncType *func_type = func_inst->is_import_func
  1342. ? func_inst->u.func_import->func_type
  1343. : func_inst->u.func->func_type;
  1344. module_inst->func_type_indexes[i] =
  1345. get_smallest_type_idx(module_inst->module, func_type);
  1346. }
  1347. return true;
  1348. }
  1349. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 */
  1350. #if WASM_ENABLE_GC != 0
  1351. void *
  1352. wasm_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx,
  1353. bool throw_exce, char *error_buf, uint32 error_buf_size)
  1354. {
  1355. WASMModule *module = module_inst->module;
  1356. WASMRttTypeRef rtt_type;
  1357. WASMFuncObjectRef func_obj;
  1358. WASMFunctionInstance *func_inst;
  1359. WASMFuncType *func_type;
  1360. uint32 type_idx;
  1361. if (throw_exce) {
  1362. error_buf = module_inst->cur_exception;
  1363. error_buf_size = sizeof(module_inst->cur_exception);
  1364. }
  1365. if (func_idx >= module_inst->e->function_count) {
  1366. set_error_buf_v(error_buf, error_buf_size, "unknown function %d",
  1367. func_idx);
  1368. return NULL;
  1369. }
  1370. func_inst = &module_inst->e->functions[func_idx];
  1371. func_type = func_inst->is_import_func ? func_inst->u.func_import->func_type
  1372. : func_inst->u.func->func_type;
  1373. type_idx = func_inst->is_import_func ? func_inst->u.func_import->type_idx
  1374. : func_inst->u.func->type_idx;
  1375. if (!(rtt_type = wasm_rtt_type_new((WASMType *)func_type, type_idx,
  1376. module->rtt_types, module->type_count,
  1377. &module->rtt_type_lock))) {
  1378. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  1379. return NULL;
  1380. }
  1381. if (!(func_obj = wasm_func_obj_new_internal(module_inst->e->gc_heap_handle,
  1382. rtt_type, func_idx))) {
  1383. set_error_buf(error_buf, error_buf_size, "create func object failed");
  1384. return NULL;
  1385. }
  1386. return func_obj;
  1387. }
  1388. static bool
  1389. wasm_global_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1390. {
  1391. WASMGlobalInstance *global = module_inst->e->globals;
  1392. WASMGlobalInstance *global_end = global + module_inst->e->global_count;
  1393. uint8 *global_data = module_inst->global_data;
  1394. WASMObjectRef gc_obj;
  1395. while (global < global_end) {
  1396. if (wasm_is_type_reftype(global->type)) {
  1397. gc_obj = GET_REF_FROM_ADDR(
  1398. (uint32 *)(global_data + global->data_offset));
  1399. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1400. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1401. return false;
  1402. }
  1403. }
  1404. global++;
  1405. }
  1406. return true;
  1407. }
  1408. static bool
  1409. wasm_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1410. {
  1411. WASMTableInstance **tables = module_inst->tables, *table;
  1412. uint32 table_count = module_inst->table_count, i, j;
  1413. WASMObjectRef gc_obj, *table_elems;
  1414. for (i = 0; i < table_count; i++) {
  1415. table = tables[i];
  1416. table_elems = (WASMObjectRef *)table->elems;
  1417. for (j = 0; j < table->cur_size; j++) {
  1418. gc_obj = table_elems[j];
  1419. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1420. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1421. return false;
  1422. }
  1423. }
  1424. }
  1425. return true;
  1426. }
  1427. static bool
  1428. local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1429. {
  1430. WASMLocalObjectRef *r;
  1431. WASMObjectRef gc_obj;
  1432. for (r = exec_env->cur_local_object_ref; r; r = r->prev) {
  1433. gc_obj = r->val;
  1434. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1435. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1436. return false;
  1437. }
  1438. }
  1439. return true;
  1440. }
  1441. bool
  1442. wasm_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1443. {
  1444. WASMModuleInstance *module_inst =
  1445. (WASMModuleInstance *)exec_env->module_inst;
  1446. bool ret;
  1447. ret = wasm_global_traverse_gc_rootset(module_inst, heap);
  1448. if (!ret)
  1449. return ret;
  1450. ret = wasm_table_traverse_gc_rootset(module_inst, heap);
  1451. if (!ret)
  1452. return ret;
  1453. ret = local_object_refs_traverse_gc_rootset(exec_env, heap);
  1454. if (!ret)
  1455. return ret;
  1456. return wasm_interp_traverse_gc_rootset(exec_env, heap);
  1457. }
  1458. #endif /* end of WASM_ENABLE_GC != 0 */
  1459. static bool
  1460. set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode,
  1461. bool first_time_set)
  1462. {
  1463. WASMModule *module = module_inst->module;
  1464. if (running_mode == Mode_Default) {
  1465. #if WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT == 0
  1466. running_mode = Mode_Interp;
  1467. #elif WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT == 0
  1468. running_mode = Mode_Fast_JIT;
  1469. #elif WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT != 0
  1470. running_mode = Mode_LLVM_JIT;
  1471. #else /* WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 */
  1472. #if WASM_ENABLE_LAZY_JIT == 0
  1473. running_mode = Mode_LLVM_JIT;
  1474. #else
  1475. running_mode = Mode_Multi_Tier_JIT;
  1476. #endif
  1477. #endif
  1478. }
  1479. if (!wasm_runtime_is_running_mode_supported(running_mode))
  1480. return false;
  1481. #if !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1482. && WASM_ENABLE_LAZY_JIT != 0) /* No possible multi-tier JIT */
  1483. module_inst->e->running_mode = running_mode;
  1484. if (running_mode == Mode_Interp) {
  1485. /* Do nothing for Mode_Interp */
  1486. }
  1487. else if (running_mode == Mode_Fast_JIT) {
  1488. /* Do nothing for Mode_Fast_JIT since
  1489. module_inst->fast_jit_func_ptrs is same as
  1490. module->fast_jit_func_ptrs */
  1491. }
  1492. #if WASM_ENABLE_JIT != 0
  1493. else if (running_mode == Mode_LLVM_JIT) {
  1494. /* Set defined function pointers */
  1495. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  1496. sizeof(void *) * module->function_count, module->func_ptrs,
  1497. sizeof(void *) * module->function_count);
  1498. }
  1499. #endif
  1500. else {
  1501. bh_assert(0);
  1502. }
  1503. #else /* Possible multi-tier JIT */
  1504. os_mutex_lock(&module->instance_list_lock);
  1505. module_inst->e->running_mode = running_mode;
  1506. if (running_mode == Mode_Interp) {
  1507. /* Do nothing for Mode_Interp */
  1508. }
  1509. #if WASM_ENABLE_FAST_JIT != 0
  1510. else if (running_mode == Mode_Fast_JIT) {
  1511. JitGlobals *jit_globals = jit_compiler_get_jit_globals();
  1512. uint32 i;
  1513. /* Allocate memory for fast_jit_func_ptrs if needed */
  1514. if (!module_inst->fast_jit_func_ptrs
  1515. || module_inst->fast_jit_func_ptrs == module->fast_jit_func_ptrs) {
  1516. uint64 total_size = (uint64)sizeof(void *) * module->function_count;
  1517. if (!(module_inst->fast_jit_func_ptrs =
  1518. runtime_malloc(total_size, NULL, 0))) {
  1519. os_mutex_unlock(&module->instance_list_lock);
  1520. return false;
  1521. }
  1522. }
  1523. for (i = 0; i < module->function_count; i++) {
  1524. if (module->functions[i]->fast_jit_jitted_code) {
  1525. /* current fast jit function has been compiled */
  1526. module_inst->fast_jit_func_ptrs[i] =
  1527. module->functions[i]->fast_jit_jitted_code;
  1528. }
  1529. else {
  1530. module_inst->fast_jit_func_ptrs[i] =
  1531. jit_globals->compile_fast_jit_and_then_call;
  1532. }
  1533. }
  1534. }
  1535. #endif
  1536. #if WASM_ENABLE_JIT != 0
  1537. else if (running_mode == Mode_LLVM_JIT) {
  1538. void **llvm_jit_func_ptrs;
  1539. uint32 i;
  1540. /* Notify backend threads to start llvm jit compilation */
  1541. module->enable_llvm_jit_compilation = true;
  1542. /* Wait until llvm jit finishes initialization */
  1543. os_mutex_lock(&module->tierup_wait_lock);
  1544. while (!module->llvm_jit_inited) {
  1545. os_cond_reltimedwait(&module->tierup_wait_cond,
  1546. &module->tierup_wait_lock, 10000);
  1547. if (module->orcjit_stop_compiling) {
  1548. /* init_llvm_jit_functions_stage2 failed */
  1549. os_mutex_unlock(&module->tierup_wait_lock);
  1550. os_mutex_unlock(&module->instance_list_lock);
  1551. return false;
  1552. }
  1553. }
  1554. os_mutex_unlock(&module->tierup_wait_lock);
  1555. llvm_jit_func_ptrs =
  1556. module_inst->func_ptrs + module->import_function_count;
  1557. for (i = 0; i < module->function_count; i++) {
  1558. llvm_jit_func_ptrs[i] = module->functions[i]->llvm_jit_func_ptr;
  1559. }
  1560. }
  1561. #endif
  1562. else if (running_mode == Mode_Multi_Tier_JIT) {
  1563. /* Notify backend threads to start llvm jit compilation */
  1564. module->enable_llvm_jit_compilation = true;
  1565. /* Free fast_jit_func_ptrs if it is allocated before */
  1566. if (module_inst->fast_jit_func_ptrs
  1567. && module_inst->fast_jit_func_ptrs != module->fast_jit_func_ptrs) {
  1568. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  1569. }
  1570. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  1571. /* Copy all llvm jit func ptrs from the module */
  1572. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  1573. sizeof(void *) * module->function_count, module->func_ptrs,
  1574. sizeof(void *) * module->function_count);
  1575. }
  1576. else {
  1577. bh_assert(0);
  1578. }
  1579. /* Add module instance into module's instance list if not added */
  1580. if (first_time_set) {
  1581. bool found = false;
  1582. WASMModuleInstance *node = module->instance_list;
  1583. while (node) {
  1584. if (node == module_inst) {
  1585. found = true;
  1586. break;
  1587. }
  1588. node = node->e->next;
  1589. }
  1590. if (!found) {
  1591. module_inst->e->next = module->instance_list;
  1592. module->instance_list = module_inst;
  1593. }
  1594. }
  1595. os_mutex_unlock(&module->instance_list_lock);
  1596. #endif /* end of !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1597. && WASM_ENABLE_LAZY_JIT != 0) */
  1598. (void)module;
  1599. return true;
  1600. }
  1601. bool
  1602. wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode)
  1603. {
  1604. return set_running_mode(module_inst, running_mode, false);
  1605. }
  1606. /**
  1607. * Instantiate module
  1608. */
  1609. WASMModuleInstance *
  1610. wasm_instantiate(WASMModule *module, bool is_sub_inst,
  1611. WASMExecEnv *exec_env_main, uint32 stack_size,
  1612. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  1613. {
  1614. WASMModuleInstance *module_inst;
  1615. WASMGlobalInstance *globals = NULL, *global;
  1616. WASMTableInstance *first_table;
  1617. uint32 global_count, i;
  1618. uint32 base_offset, length, extra_info_offset;
  1619. uint32 module_inst_struct_size =
  1620. offsetof(WASMModuleInstance, global_table_data.bytes);
  1621. uint64 module_inst_mem_inst_size;
  1622. uint64 total_size, table_size = 0;
  1623. uint8 *global_data, *global_data_end;
  1624. #if WASM_ENABLE_MULTI_MODULE != 0
  1625. bool ret = false;
  1626. #endif
  1627. if (!module)
  1628. return NULL;
  1629. /* Check the heap size */
  1630. heap_size = align_uint(heap_size, 8);
  1631. if (heap_size > APP_HEAP_SIZE_MAX)
  1632. heap_size = APP_HEAP_SIZE_MAX;
  1633. module_inst_mem_inst_size =
  1634. (uint64)sizeof(WASMMemoryInstance)
  1635. * (module->import_memory_count + module->memory_count);
  1636. #if WASM_ENABLE_JIT != 0
  1637. /* If the module dosen't have memory, reserve one mem_info space
  1638. with empty content to align with llvm jit compiler */
  1639. if (module_inst_mem_inst_size == 0)
  1640. module_inst_mem_inst_size = (uint64)sizeof(WASMMemoryInstance);
  1641. #endif
  1642. /* Size of module inst, memory instances and global data */
  1643. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  1644. + module->global_data_size;
  1645. /* Calculate the size of table data */
  1646. for (i = 0; i < module->import_table_count; i++) {
  1647. WASMTableImport *import_table = &module->import_tables[i].u.table;
  1648. table_size += offsetof(WASMTableInstance, elems);
  1649. #if WASM_ENABLE_MULTI_MODULE != 0
  1650. table_size +=
  1651. (uint64)sizeof(table_elem_type_t) * import_table->max_size;
  1652. #else
  1653. table_size += (uint64)sizeof(table_elem_type_t)
  1654. * (import_table->possible_grow ? import_table->max_size
  1655. : import_table->init_size);
  1656. #endif
  1657. }
  1658. for (i = 0; i < module->table_count; i++) {
  1659. WASMTable *table = module->tables + i;
  1660. table_size += offsetof(WASMTableInstance, elems);
  1661. #if WASM_ENABLE_MULTI_MODULE != 0
  1662. table_size += (uint64)sizeof(table_elem_type_t) * table->max_size;
  1663. #else
  1664. table_size +=
  1665. (uint64)sizeof(table_elem_type_t)
  1666. * (table->possible_grow ? table->max_size : table->init_size);
  1667. #endif
  1668. }
  1669. total_size += table_size;
  1670. /* The offset of WASMModuleInstanceExtra, make it 8-byte aligned */
  1671. total_size = (total_size + 7LL) & ~7LL;
  1672. extra_info_offset = (uint32)total_size;
  1673. total_size += sizeof(WASMModuleInstanceExtra);
  1674. /* Allocate the memory for module instance with memory instances,
  1675. global data, table data appended at the end */
  1676. if (!(module_inst =
  1677. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1678. return NULL;
  1679. }
  1680. module_inst->module_type = Wasm_Module_Bytecode;
  1681. module_inst->module = module;
  1682. module_inst->e =
  1683. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  1684. #if WASM_ENABLE_MULTI_MODULE != 0
  1685. module_inst->e->sub_module_inst_list =
  1686. &module_inst->e->sub_module_inst_list_head;
  1687. ret = sub_module_instantiate(module, module_inst, stack_size, heap_size,
  1688. error_buf, error_buf_size);
  1689. if (!ret) {
  1690. LOG_DEBUG("build a sub module list failed");
  1691. goto fail;
  1692. }
  1693. #endif
  1694. #if WASM_ENABLE_GC != 0
  1695. if (!is_sub_inst) {
  1696. uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default();
  1697. if (gc_heap_size < GC_HEAP_SIZE_MIN)
  1698. gc_heap_size = GC_HEAP_SIZE_MIN;
  1699. if (gc_heap_size > GC_HEAP_SIZE_MAX)
  1700. gc_heap_size = GC_HEAP_SIZE_MAX;
  1701. module_inst->e->gc_heap_pool =
  1702. runtime_malloc(gc_heap_size, error_buf, error_buf_size);
  1703. if (!module_inst->e->gc_heap_pool)
  1704. goto fail;
  1705. module_inst->e->gc_heap_handle =
  1706. mem_allocator_create(module_inst->e->gc_heap_pool, gc_heap_size);
  1707. if (!module_inst->e->gc_heap_handle)
  1708. goto fail;
  1709. }
  1710. #endif
  1711. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1712. if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector),
  1713. error_buf, error_buf_size))) {
  1714. goto fail;
  1715. }
  1716. #endif
  1717. /* Instantiate global firstly to get the mutable data size */
  1718. global_count = module->import_global_count + module->global_count;
  1719. if (global_count
  1720. && !(globals = globals_instantiate(module, module_inst, error_buf,
  1721. error_buf_size))) {
  1722. goto fail;
  1723. }
  1724. module_inst->e->global_count = global_count;
  1725. module_inst->e->globals = globals;
  1726. module_inst->global_data = (uint8 *)module_inst + module_inst_struct_size
  1727. + module_inst_mem_inst_size;
  1728. module_inst->global_data_size = module->global_data_size;
  1729. first_table = (WASMTableInstance *)(module_inst->global_data
  1730. + module->global_data_size);
  1731. module_inst->memory_count =
  1732. module->import_memory_count + module->memory_count;
  1733. module_inst->table_count = module->import_table_count + module->table_count;
  1734. module_inst->e->function_count =
  1735. module->import_function_count + module->function_count;
  1736. /* export */
  1737. module_inst->export_func_count = get_export_count(module, EXPORT_KIND_FUNC);
  1738. #if WASM_ENABLE_MULTI_MODULE != 0
  1739. module_inst->export_table_count =
  1740. get_export_count(module, EXPORT_KIND_TABLE);
  1741. module_inst->export_memory_count =
  1742. get_export_count(module, EXPORT_KIND_MEMORY);
  1743. module_inst->export_global_count =
  1744. get_export_count(module, EXPORT_KIND_GLOBAL);
  1745. #endif
  1746. /* Instantiate memories/tables/functions */
  1747. if ((module_inst->memory_count > 0
  1748. && !(module_inst->memories = memories_instantiate(
  1749. module, module_inst, heap_size, error_buf, error_buf_size)))
  1750. || (module_inst->table_count > 0
  1751. && !(module_inst->tables =
  1752. tables_instantiate(module, module_inst, first_table,
  1753. error_buf, error_buf_size)))
  1754. || (module_inst->e->function_count > 0
  1755. && !(module_inst->e->functions = functions_instantiate(
  1756. module, module_inst, error_buf, error_buf_size)))
  1757. || (module_inst->export_func_count > 0
  1758. && !(module_inst->export_functions = export_functions_instantiate(
  1759. module, module_inst, module_inst->export_func_count,
  1760. error_buf, error_buf_size)))
  1761. #if WASM_ENABLE_MULTI_MODULE != 0
  1762. || (module_inst->export_global_count > 0
  1763. && !(module_inst->export_globals = export_globals_instantiate(
  1764. module, module_inst, module_inst->export_global_count,
  1765. error_buf, error_buf_size)))
  1766. #endif
  1767. #if WASM_ENABLE_JIT != 0
  1768. || (module_inst->e->function_count > 0
  1769. && !init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  1770. #endif
  1771. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1772. || (module_inst->e->function_count > 0
  1773. && !init_func_type_indexes(module_inst, error_buf, error_buf_size))
  1774. #endif
  1775. ) {
  1776. goto fail;
  1777. }
  1778. if (global_count > 0) {
  1779. /* Initialize the global data */
  1780. global_data = module_inst->global_data;
  1781. global_data_end = global_data + module->global_data_size;
  1782. global = globals;
  1783. for (i = 0; i < global_count; i++, global++) {
  1784. switch (global->type) {
  1785. case VALUE_TYPE_I32:
  1786. case VALUE_TYPE_F32:
  1787. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  1788. case VALUE_TYPE_FUNCREF:
  1789. case VALUE_TYPE_EXTERNREF:
  1790. #endif
  1791. *(int32 *)global_data = global->initial_value.i32;
  1792. global_data += sizeof(int32);
  1793. break;
  1794. case VALUE_TYPE_I64:
  1795. case VALUE_TYPE_F64:
  1796. bh_memcpy_s(global_data,
  1797. (uint32)(global_data_end - global_data),
  1798. &global->initial_value.i64, sizeof(int64));
  1799. global_data += sizeof(int64);
  1800. break;
  1801. #if WASM_ENABLE_SIMD != 0
  1802. case VALUE_TYPE_V128:
  1803. bh_memcpy_s(global_data, (uint32)sizeof(V128),
  1804. &global->initial_value.v128, sizeof(V128));
  1805. global_data += sizeof(V128);
  1806. break;
  1807. #endif
  1808. #if WASM_ENABLE_GC != 0
  1809. case VALUE_TYPE_EXTERNREF:
  1810. /* UINT32_MAX indicates that it is an null reference */
  1811. bh_assert((uint32)global->initial_value.i32 == UINT32_MAX);
  1812. STORE_PTR((void **)global_data, NULL_REF);
  1813. global_data += sizeof(void *);
  1814. break;
  1815. #endif
  1816. default:
  1817. #if WASM_ENABLE_GC != 0
  1818. if (global->type != REF_TYPE_NULLFUNCREF
  1819. && wasm_reftype_is_subtype_of(
  1820. global->type, global->ref_type, REF_TYPE_FUNCREF,
  1821. NULL, module_inst->module->types,
  1822. module_inst->module->type_count)) {
  1823. WASMFuncObjectRef func_obj = NULL;
  1824. /* UINT32_MAX indicates that it is an null reference */
  1825. if ((uint32)global->initial_value.i32 != UINT32_MAX) {
  1826. if (!(func_obj = wasm_create_func_obj(
  1827. module_inst, global->initial_value.i32,
  1828. false, error_buf, error_buf_size)))
  1829. goto fail;
  1830. }
  1831. STORE_PTR((void **)global_data, func_obj);
  1832. global_data += sizeof(void *);
  1833. break;
  1834. }
  1835. else if (global->type != REF_TYPE_NULLREF
  1836. && wasm_reftype_is_subtype_of(
  1837. global->type, global->ref_type,
  1838. REF_TYPE_I31REF, NULL,
  1839. module_inst->module->types,
  1840. module_inst->module->type_count)) {
  1841. STORE_PTR((void **)global_data,
  1842. global->initial_value.gc_obj);
  1843. global_data += sizeof(void *);
  1844. break;
  1845. }
  1846. else if (wasm_is_type_reftype(global->type)) {
  1847. STORE_PTR((void **)global_data, NULL_REF);
  1848. global_data += sizeof(void *);
  1849. break;
  1850. }
  1851. #endif
  1852. bh_assert(0);
  1853. break;
  1854. }
  1855. }
  1856. bh_assert(global_data == global_data_end);
  1857. }
  1858. if (!check_linked_symbol(module_inst, error_buf, error_buf_size)) {
  1859. goto fail;
  1860. }
  1861. /* Initialize the memory data with data segment section */
  1862. for (i = 0; i < module->data_seg_count; i++) {
  1863. WASMMemoryInstance *memory = NULL;
  1864. uint8 *memory_data = NULL;
  1865. uint32 memory_size = 0;
  1866. WASMDataSeg *data_seg = module->data_segments[i];
  1867. #if WASM_ENABLE_BULK_MEMORY != 0
  1868. if (data_seg->is_passive)
  1869. continue;
  1870. #endif
  1871. /* has check it in loader */
  1872. memory = module_inst->memories[data_seg->memory_index];
  1873. bh_assert(memory);
  1874. memory_data = memory->memory_data;
  1875. memory_size = memory->num_bytes_per_page * memory->cur_page_count;
  1876. bh_assert(memory_data || memory_size == 0);
  1877. bh_assert(data_seg->base_offset.init_expr_type
  1878. == INIT_EXPR_TYPE_I32_CONST
  1879. || data_seg->base_offset.init_expr_type
  1880. == INIT_EXPR_TYPE_GET_GLOBAL);
  1881. if (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  1882. if (!check_global_init_expr(module,
  1883. data_seg->base_offset.u.global_index,
  1884. error_buf, error_buf_size)) {
  1885. goto fail;
  1886. }
  1887. if (!globals
  1888. || globals[data_seg->base_offset.u.global_index].type
  1889. != VALUE_TYPE_I32) {
  1890. set_error_buf(error_buf, error_buf_size,
  1891. "data segment does not fit");
  1892. goto fail;
  1893. }
  1894. base_offset =
  1895. globals[data_seg->base_offset.u.global_index].initial_value.i32;
  1896. }
  1897. else {
  1898. base_offset = (uint32)data_seg->base_offset.u.i32;
  1899. }
  1900. /* check offset */
  1901. if (base_offset > memory_size) {
  1902. LOG_DEBUG("base_offset(%d) > memory_size(%d)", base_offset,
  1903. memory_size);
  1904. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1905. set_error_buf(error_buf, error_buf_size,
  1906. "out of bounds memory access");
  1907. #else
  1908. set_error_buf(error_buf, error_buf_size,
  1909. "data segment does not fit");
  1910. #endif
  1911. goto fail;
  1912. }
  1913. /* check offset + length(could be zero) */
  1914. length = data_seg->data_length;
  1915. if (base_offset + length > memory_size) {
  1916. LOG_DEBUG("base_offset(%d) + length(%d) > memory_size(%d)",
  1917. base_offset, length, memory_size);
  1918. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1919. set_error_buf(error_buf, error_buf_size,
  1920. "out of bounds memory access");
  1921. #else
  1922. set_error_buf(error_buf, error_buf_size,
  1923. "data segment does not fit");
  1924. #endif
  1925. goto fail;
  1926. }
  1927. if (memory_data) {
  1928. bh_memcpy_s(memory_data + base_offset, memory_size - base_offset,
  1929. data_seg->data, length);
  1930. }
  1931. }
  1932. /* Initialize the table data with table segment section */
  1933. for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count;
  1934. i++) {
  1935. WASMTableSeg *table_seg = module->table_segments + i;
  1936. /* has check it in loader */
  1937. WASMTableInstance *table = module_inst->tables[table_seg->table_index];
  1938. table_elem_type_t *table_data;
  1939. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1940. uint8 tbl_elem_type;
  1941. uint32 tbl_init_size, tbl_max_size;
  1942. #endif
  1943. #if WASM_ENABLE_GC != 0
  1944. WASMRefType *tbl_elem_ref_type;
  1945. uint32 j;
  1946. #endif
  1947. bh_assert(table);
  1948. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1949. (void)wasm_runtime_get_table_inst_elem_type(
  1950. (WASMModuleInstanceCommon *)module_inst, table_seg->table_index,
  1951. &tbl_elem_type,
  1952. #if WASM_ENABLE_GC != 0
  1953. &tbl_elem_ref_type,
  1954. #endif
  1955. &tbl_init_size, &tbl_max_size);
  1956. #if WASM_ENABLE_GC == 0
  1957. if (tbl_elem_type != VALUE_TYPE_FUNCREF
  1958. && tbl_elem_type != VALUE_TYPE_EXTERNREF) {
  1959. set_error_buf(error_buf, error_buf_size,
  1960. "elements segment does not fit");
  1961. goto fail;
  1962. }
  1963. #elif WASM_ENABLE_GC != 0
  1964. if (!wasm_elem_is_declarative(table_seg->mode)
  1965. && !wasm_reftype_is_subtype_of(
  1966. table_seg->elem_type, table_seg->elem_ref_type,
  1967. table->elem_type, table->elem_ref_type, module->types,
  1968. module->type_count)) {
  1969. set_error_buf(error_buf, error_buf_size,
  1970. "elements segment does not fit");
  1971. goto fail;
  1972. }
  1973. #endif
  1974. (void)tbl_init_size;
  1975. (void)tbl_max_size;
  1976. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  1977. table_data = table->elems;
  1978. #if WASM_ENABLE_MULTI_MODULE != 0
  1979. if (table_seg->table_index < module->import_table_count
  1980. && module_inst->e->table_insts_linked[table_seg->table_index]) {
  1981. table_data =
  1982. module_inst->e->table_insts_linked[table_seg->table_index]
  1983. ->elems;
  1984. }
  1985. #endif
  1986. bh_assert(table_data);
  1987. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1988. if (!wasm_elem_is_active(table_seg->mode))
  1989. continue;
  1990. #endif
  1991. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  1992. bh_assert(table_seg->base_offset.init_expr_type
  1993. == INIT_EXPR_TYPE_I32_CONST
  1994. || table_seg->base_offset.init_expr_type
  1995. == INIT_EXPR_TYPE_GET_GLOBAL
  1996. || table_seg->base_offset.init_expr_type
  1997. == INIT_EXPR_TYPE_FUNCREF_CONST
  1998. || table_seg->base_offset.init_expr_type
  1999. == INIT_EXPR_TYPE_REFNULL_CONST);
  2000. #else
  2001. bh_assert(table_seg->base_offset.init_expr_type
  2002. == INIT_EXPR_TYPE_I32_CONST
  2003. || table_seg->base_offset.init_expr_type
  2004. == INIT_EXPR_TYPE_GET_GLOBAL);
  2005. #endif
  2006. /* init vec(funcidx) or vec(expr) */
  2007. if (table_seg->base_offset.init_expr_type
  2008. == INIT_EXPR_TYPE_GET_GLOBAL) {
  2009. if (!check_global_init_expr(module,
  2010. table_seg->base_offset.u.global_index,
  2011. error_buf, error_buf_size)) {
  2012. goto fail;
  2013. }
  2014. if (!globals
  2015. || globals[table_seg->base_offset.u.global_index].type
  2016. != VALUE_TYPE_I32) {
  2017. set_error_buf(error_buf, error_buf_size,
  2018. "elements segment does not fit");
  2019. goto fail;
  2020. }
  2021. table_seg->base_offset.u.i32 =
  2022. globals[table_seg->base_offset.u.global_index]
  2023. .initial_value.i32;
  2024. }
  2025. /* check offset since length might negative */
  2026. if ((uint32)table_seg->base_offset.u.i32 > table->cur_size) {
  2027. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)",
  2028. table_seg->base_offset.u.i32, table->cur_size);
  2029. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2030. set_error_buf(error_buf, error_buf_size,
  2031. "out of bounds table access");
  2032. #else
  2033. set_error_buf(error_buf, error_buf_size,
  2034. "elements segment does not fit");
  2035. #endif
  2036. goto fail;
  2037. }
  2038. /* check offset + length(could be zero) */
  2039. length = table_seg->function_count;
  2040. if ((uint32)table_seg->base_offset.u.i32 + length > table->cur_size) {
  2041. LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)",
  2042. table_seg->base_offset.u.i32, length, table->cur_size);
  2043. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2044. set_error_buf(error_buf, error_buf_size,
  2045. "out of bounds table access");
  2046. #else
  2047. set_error_buf(error_buf, error_buf_size,
  2048. "elements segment does not fit");
  2049. #endif
  2050. goto fail;
  2051. }
  2052. /**
  2053. * Check function index in the current module inst for now.
  2054. * will check the linked table inst owner in future.
  2055. * so loader check is enough
  2056. */
  2057. #if WASM_ENABLE_GC == 0
  2058. bh_memcpy_s(
  2059. table_data + table_seg->base_offset.u.i32,
  2060. (uint32)((table->cur_size - (uint32)table_seg->base_offset.u.i32)
  2061. * sizeof(uint32)),
  2062. table_seg->func_indexes, (uint32)(length * sizeof(uint32)));
  2063. #else
  2064. for (j = 0; j < length; j++) {
  2065. WASMFuncObjectRef func_obj;
  2066. uint32 func_idx = table_seg->func_indexes[j];
  2067. /* UINT32_MAX indicates that it is an null reference */
  2068. if (func_idx != UINT32_MAX) {
  2069. if (!(func_obj =
  2070. wasm_create_func_obj(module_inst, func_idx, false,
  2071. error_buf, error_buf_size))) {
  2072. goto fail;
  2073. }
  2074. *(table_data + table_seg->base_offset.u.i32 + j) = func_obj;
  2075. }
  2076. else {
  2077. *(table_data + table_seg->base_offset.u.i32 + j) = NULL_REF;
  2078. }
  2079. }
  2080. #endif
  2081. }
  2082. /* Initialize the thread related data */
  2083. if (stack_size == 0)
  2084. stack_size = DEFAULT_WASM_STACK_SIZE;
  2085. #if WASM_ENABLE_SPEC_TEST != 0
  2086. if (stack_size < 128 * 1024)
  2087. stack_size = 128 * 1024;
  2088. #endif
  2089. module_inst->default_wasm_stack_size = stack_size;
  2090. if (module->malloc_function != (uint32)-1) {
  2091. module_inst->e->malloc_function =
  2092. &module_inst->e->functions[module->malloc_function];
  2093. }
  2094. if (module->free_function != (uint32)-1) {
  2095. module_inst->e->free_function =
  2096. &module_inst->e->functions[module->free_function];
  2097. }
  2098. if (module->retain_function != (uint32)-1) {
  2099. module_inst->e->retain_function =
  2100. &module_inst->e->functions[module->retain_function];
  2101. }
  2102. #if WASM_ENABLE_LIBC_WASI != 0
  2103. /* The sub-instance will get the wasi_ctx from main-instance */
  2104. if (!is_sub_inst) {
  2105. if (!wasm_runtime_init_wasi(
  2106. (WASMModuleInstanceCommon *)module_inst,
  2107. module->wasi_args.dir_list, module->wasi_args.dir_count,
  2108. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  2109. module->wasi_args.env, module->wasi_args.env_count,
  2110. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  2111. module->wasi_args.ns_lookup_pool,
  2112. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  2113. module->wasi_args.argc, module->wasi_args.stdio[0],
  2114. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  2115. error_buf, error_buf_size)) {
  2116. goto fail;
  2117. }
  2118. }
  2119. #endif
  2120. #if WASM_ENABLE_WASI_NN != 0
  2121. if (!is_sub_inst) {
  2122. if (!(module_inst->e->wasi_nn_ctx = wasi_nn_initialize())) {
  2123. set_error_buf(error_buf, error_buf_size,
  2124. "wasi nn initialization failed");
  2125. goto fail;
  2126. }
  2127. }
  2128. #endif
  2129. #if WASM_ENABLE_DEBUG_INTERP != 0
  2130. if (!is_sub_inst) {
  2131. /* Add module instance into module's instance list */
  2132. os_mutex_lock(&module->instance_list_lock);
  2133. if (module->instance_list) {
  2134. LOG_WARNING(
  2135. "warning: multiple instances referencing to the same module "
  2136. "may cause unexpected behaviour during debugging");
  2137. }
  2138. module_inst->e->next = module->instance_list;
  2139. module->instance_list = module_inst;
  2140. os_mutex_unlock(&module->instance_list_lock);
  2141. }
  2142. #endif
  2143. /* Set running mode before executing wasm functions */
  2144. if (!set_running_mode(module_inst, wasm_runtime_get_default_running_mode(),
  2145. true)) {
  2146. set_error_buf(error_buf, error_buf_size,
  2147. "set instance running mode failed");
  2148. goto fail;
  2149. }
  2150. if (module->start_function != (uint32)-1) {
  2151. /* TODO: fix start function can be import function issue */
  2152. if (module->start_function >= module->import_function_count)
  2153. module_inst->e->start_function =
  2154. &module_inst->e->functions[module->start_function];
  2155. }
  2156. if (!execute_post_instantiate_functions(module_inst, is_sub_inst,
  2157. exec_env_main)) {
  2158. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  2159. goto fail;
  2160. }
  2161. #if WASM_ENABLE_MEMORY_TRACING != 0
  2162. wasm_runtime_dump_module_inst_mem_consumption(
  2163. (WASMModuleInstanceCommon *)module_inst);
  2164. #endif
  2165. (void)global_data_end;
  2166. return module_inst;
  2167. fail:
  2168. wasm_deinstantiate(module_inst, false);
  2169. return NULL;
  2170. }
  2171. void
  2172. wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst)
  2173. {
  2174. if (!module_inst)
  2175. return;
  2176. if (module_inst->exec_env_singleton) {
  2177. /* wasm_exec_env_destroy will call
  2178. wasm_cluster_wait_for_all_except_self to wait for other
  2179. threads, so as to destroy their exec_envs and module
  2180. instances first, and avoid accessing the shared resources
  2181. of current module instance after it is deinstantiated. */
  2182. wasm_exec_env_destroy(module_inst->exec_env_singleton);
  2183. }
  2184. #if WASM_ENABLE_DEBUG_INTERP != 0 \
  2185. || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2186. && WASM_ENABLE_LAZY_JIT != 0)
  2187. /* Remove instance from module's instance list before freeing
  2188. func_ptrs and fast_jit_func_ptrs of the instance, to avoid
  2189. accessing the freed memory in the jit backend compilation
  2190. threads */
  2191. {
  2192. WASMModule *module = module_inst->module;
  2193. WASMModuleInstance *instance_prev = NULL, *instance;
  2194. os_mutex_lock(&module->instance_list_lock);
  2195. instance = module->instance_list;
  2196. while (instance) {
  2197. if (instance == module_inst) {
  2198. if (!instance_prev)
  2199. module->instance_list = instance->e->next;
  2200. else
  2201. instance_prev->e->next = instance->e->next;
  2202. break;
  2203. }
  2204. instance_prev = instance;
  2205. instance = instance->e->next;
  2206. }
  2207. os_mutex_unlock(&module->instance_list_lock);
  2208. }
  2209. #endif
  2210. #if WASM_ENABLE_JIT != 0
  2211. if (module_inst->func_ptrs)
  2212. wasm_runtime_free(module_inst->func_ptrs);
  2213. #endif
  2214. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2215. && WASM_ENABLE_LAZY_JIT != 0
  2216. if (module_inst->fast_jit_func_ptrs
  2217. && module_inst->fast_jit_func_ptrs
  2218. != module_inst->module->fast_jit_func_ptrs)
  2219. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  2220. #endif
  2221. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  2222. if (module_inst->func_type_indexes)
  2223. wasm_runtime_free(module_inst->func_type_indexes);
  2224. #endif
  2225. #if WASM_ENABLE_MULTI_MODULE != 0
  2226. sub_module_deinstantiate(module_inst);
  2227. #endif
  2228. #if WASM_ENABLE_LIBC_WASI != 0
  2229. /* Destroy wasi resource before freeing app heap, since some fields of
  2230. wasi contex are allocated from app heap, and if app heap is freed,
  2231. these fields will be set to NULL, we cannot free their internal data
  2232. which may allocated from global heap. */
  2233. /* Only destroy wasi ctx in the main module instance */
  2234. if (!is_sub_inst)
  2235. wasm_runtime_destroy_wasi((WASMModuleInstanceCommon *)module_inst);
  2236. #endif
  2237. if (module_inst->memory_count > 0)
  2238. memories_deinstantiate(module_inst, module_inst->memories,
  2239. module_inst->memory_count);
  2240. if (module_inst->import_func_ptrs) {
  2241. wasm_runtime_free(module_inst->import_func_ptrs);
  2242. }
  2243. tables_deinstantiate(module_inst);
  2244. functions_deinstantiate(module_inst->e->functions,
  2245. module_inst->e->function_count);
  2246. globals_deinstantiate(module_inst->e->globals);
  2247. export_functions_deinstantiate(module_inst->export_functions);
  2248. #if WASM_ENABLE_MULTI_MODULE != 0
  2249. export_globals_deinstantiate(module_inst->export_globals);
  2250. #endif
  2251. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2252. wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst);
  2253. #endif
  2254. #if WASM_ENABLE_GC != 0
  2255. if (!is_sub_inst) {
  2256. if (module_inst->e->gc_heap_handle)
  2257. mem_allocator_destroy(module_inst->e->gc_heap_handle);
  2258. if (module_inst->e->gc_heap_pool)
  2259. wasm_runtime_free(module_inst->e->gc_heap_pool);
  2260. }
  2261. #endif
  2262. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2263. if (module_inst->frames) {
  2264. bh_vector_destroy(module_inst->frames);
  2265. wasm_runtime_free(module_inst->frames);
  2266. module_inst->frames = NULL;
  2267. }
  2268. #endif
  2269. if (module_inst->e->c_api_func_imports)
  2270. wasm_runtime_free(module_inst->e->c_api_func_imports);
  2271. #if WASM_ENABLE_WASI_NN != 0
  2272. if (!is_sub_inst) {
  2273. WASINNContext *wasi_nn_ctx = module_inst->e->wasi_nn_ctx;
  2274. if (wasi_nn_ctx)
  2275. wasi_nn_destroy(wasi_nn_ctx);
  2276. }
  2277. #endif
  2278. wasm_runtime_free(module_inst);
  2279. }
  2280. WASMFunctionInstance *
  2281. wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name,
  2282. const char *signature)
  2283. {
  2284. uint32 i;
  2285. for (i = 0; i < module_inst->export_func_count; i++)
  2286. if (!strcmp(module_inst->export_functions[i].name, name))
  2287. return module_inst->export_functions[i].function;
  2288. (void)signature;
  2289. return NULL;
  2290. }
  2291. #if WASM_ENABLE_MULTI_MODULE != 0
  2292. WASMGlobalInstance *
  2293. wasm_lookup_global(const WASMModuleInstance *module_inst, const char *name)
  2294. {
  2295. uint32 i;
  2296. for (i = 0; i < module_inst->export_global_count; i++)
  2297. if (!strcmp(module_inst->export_globals[i].name, name))
  2298. return module_inst->export_globals[i].global;
  2299. return NULL;
  2300. }
  2301. WASMMemoryInstance *
  2302. wasm_lookup_memory(const WASMModuleInstance *module_inst, const char *name)
  2303. {
  2304. /**
  2305. * using a strong assumption that one module instance only has
  2306. * one memory instance
  2307. */
  2308. (void)module_inst->export_memories;
  2309. return module_inst->memories[0];
  2310. }
  2311. WASMTableInstance *
  2312. wasm_lookup_table(const WASMModuleInstance *module_inst, const char *name)
  2313. {
  2314. /**
  2315. * using a strong assumption that one module instance only has
  2316. * one table instance
  2317. */
  2318. (void)module_inst->export_tables;
  2319. return module_inst->tables[0];
  2320. }
  2321. #endif
  2322. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2323. static void
  2324. call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst,
  2325. WASMExecEnv *exec_env,
  2326. WASMFunctionInstance *function, unsigned argc,
  2327. uint32 argv[])
  2328. {
  2329. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  2330. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  2331. uint32 page_size = os_getpagesize();
  2332. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  2333. WASMRuntimeFrame *prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  2334. uint8 *prev_top = exec_env->wasm_stack.s.top;
  2335. #ifdef BH_PLATFORM_WINDOWS
  2336. int result;
  2337. bool has_exception;
  2338. char exception[EXCEPTION_BUF_LEN];
  2339. #endif
  2340. bool ret = true;
  2341. /* Check native stack overflow firstly to ensure we have enough
  2342. native stack to run the following codes before actually calling
  2343. the aot function in invokeNative function. */
  2344. RECORD_STACK_USAGE(exec_env, (uint8 *)&exec_env_tls);
  2345. if ((uint8 *)&exec_env_tls < exec_env->native_stack_boundary
  2346. + page_size * (guard_page_count + 1)) {
  2347. wasm_set_exception(module_inst, "native stack overflow");
  2348. return;
  2349. }
  2350. if (exec_env_tls && (exec_env_tls != exec_env)) {
  2351. wasm_set_exception(module_inst, "invalid exec env");
  2352. return;
  2353. }
  2354. if (!os_thread_signal_inited()) {
  2355. wasm_set_exception(module_inst, "thread signal env not inited");
  2356. return;
  2357. }
  2358. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  2359. wasm_runtime_set_exec_env_tls(exec_env);
  2360. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  2361. #ifndef BH_PLATFORM_WINDOWS
  2362. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2363. #else
  2364. __try {
  2365. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2366. } __except (wasm_copy_exception(module_inst, NULL)
  2367. ? EXCEPTION_EXECUTE_HANDLER
  2368. : EXCEPTION_CONTINUE_SEARCH) {
  2369. /* exception was thrown in wasm_exception_handler */
  2370. ret = false;
  2371. }
  2372. has_exception = wasm_copy_exception(module_inst, exception);
  2373. if (has_exception && strstr(exception, "native stack overflow")) {
  2374. /* After a stack overflow, the stack was left
  2375. in a damaged state, let the CRT repair it */
  2376. result = _resetstkoflw();
  2377. bh_assert(result != 0);
  2378. }
  2379. #endif
  2380. }
  2381. else {
  2382. /* Exception has been set in signal handler before calling longjmp */
  2383. ret = false;
  2384. }
  2385. /* Note: can't check wasm_get_exception(module_inst) here, there may be
  2386. * exception which is not caught by hardware (e.g. uninitialized elements),
  2387. * then the stack-frame is already freed inside wasm_interp_call_wasm */
  2388. if (!ret) {
  2389. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2390. if (wasm_interp_create_call_stack(exec_env)) {
  2391. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  2392. }
  2393. #endif
  2394. /* Restore operand frames */
  2395. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  2396. exec_env->wasm_stack.s.top = prev_top;
  2397. }
  2398. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  2399. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  2400. if (!exec_env->jmpbuf_stack_top) {
  2401. wasm_runtime_set_exec_env_tls(NULL);
  2402. }
  2403. if (!ret) {
  2404. os_sigreturn();
  2405. os_signal_unmask();
  2406. }
  2407. (void)jmpbuf_node_pop;
  2408. }
  2409. #define interp_call_wasm call_wasm_with_hw_bound_check
  2410. #else
  2411. #define interp_call_wasm wasm_interp_call_wasm
  2412. #endif
  2413. bool
  2414. wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function,
  2415. unsigned argc, uint32 argv[])
  2416. {
  2417. WASMModuleInstance *module_inst =
  2418. (WASMModuleInstance *)exec_env->module_inst;
  2419. /* set thread handle and stack boundary */
  2420. wasm_exec_env_set_thread_info(exec_env);
  2421. interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2422. return !wasm_copy_exception(module_inst, NULL);
  2423. }
  2424. #if WASM_ENABLE_PERF_PROFILING != 0
  2425. void
  2426. wasm_dump_perf_profiling(const WASMModuleInstance *module_inst)
  2427. {
  2428. WASMExportFuncInstance *export_func;
  2429. WASMFunctionInstance *func_inst;
  2430. char *func_name;
  2431. uint32 i, j;
  2432. os_printf("Performance profiler data:\n");
  2433. for (i = 0; i < module_inst->e->function_count; i++) {
  2434. func_inst = module_inst->e->functions + i;
  2435. if (func_inst->is_import_func) {
  2436. func_name = func_inst->u.func_import->field_name;
  2437. }
  2438. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2439. else if (func_inst->u.func->field_name) {
  2440. func_name = func_inst->u.func->field_name;
  2441. }
  2442. #endif
  2443. else {
  2444. func_name = NULL;
  2445. for (j = 0; j < module_inst->export_func_count; j++) {
  2446. export_func = module_inst->export_functions + j;
  2447. if (export_func->function == func_inst) {
  2448. func_name = export_func->name;
  2449. break;
  2450. }
  2451. }
  2452. }
  2453. if (func_name)
  2454. os_printf(" func %s, execution time: %.3f ms, execution count: %d "
  2455. "times\n",
  2456. func_name,
  2457. module_inst->e->functions[i].total_exec_time / 1000.0f,
  2458. module_inst->e->functions[i].total_exec_cnt);
  2459. else
  2460. os_printf(" func %d, execution time: %.3f ms, execution count: %d "
  2461. "times\n",
  2462. i, module_inst->e->functions[i].total_exec_time / 1000.0f,
  2463. module_inst->e->functions[i].total_exec_cnt);
  2464. }
  2465. }
  2466. #endif
  2467. uint32
  2468. wasm_module_malloc_internal(WASMModuleInstance *module_inst,
  2469. WASMExecEnv *exec_env, uint32 size,
  2470. void **p_native_addr)
  2471. {
  2472. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2473. uint8 *addr = NULL;
  2474. uint32 offset = 0;
  2475. if (!memory) {
  2476. wasm_set_exception(module_inst, "uninitialized memory");
  2477. return 0;
  2478. }
  2479. if (memory->heap_handle) {
  2480. addr = mem_allocator_malloc(memory->heap_handle, size);
  2481. }
  2482. else if (module_inst->e->malloc_function && module_inst->e->free_function) {
  2483. if (!execute_malloc_function(
  2484. module_inst, exec_env, module_inst->e->malloc_function,
  2485. module_inst->e->retain_function, size, &offset)) {
  2486. return 0;
  2487. }
  2488. /* If we use app's malloc function,
  2489. the default memory may be changed while memory growing */
  2490. memory = wasm_get_default_memory(module_inst);
  2491. addr = offset ? memory->memory_data + offset : NULL;
  2492. }
  2493. if (!addr) {
  2494. if (memory->heap_handle
  2495. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  2496. wasm_runtime_show_app_heap_corrupted_prompt();
  2497. wasm_set_exception(module_inst, "app heap corrupted");
  2498. }
  2499. else {
  2500. LOG_WARNING("warning: allocate %u bytes memory failed", size);
  2501. }
  2502. return 0;
  2503. }
  2504. if (p_native_addr)
  2505. *p_native_addr = addr;
  2506. return (uint32)(addr - memory->memory_data);
  2507. }
  2508. uint32
  2509. wasm_module_realloc_internal(WASMModuleInstance *module_inst,
  2510. WASMExecEnv *exec_env, uint32 ptr, uint32 size,
  2511. void **p_native_addr)
  2512. {
  2513. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2514. uint8 *addr = NULL;
  2515. if (!memory) {
  2516. wasm_set_exception(module_inst, "uninitialized memory");
  2517. return 0;
  2518. }
  2519. if (memory->heap_handle) {
  2520. addr = mem_allocator_realloc(
  2521. memory->heap_handle, ptr ? memory->memory_data + ptr : NULL, size);
  2522. }
  2523. /* Only support realloc in WAMR's app heap */
  2524. (void)exec_env;
  2525. if (!addr) {
  2526. if (memory->heap_handle
  2527. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  2528. wasm_set_exception(module_inst, "app heap corrupted");
  2529. }
  2530. else {
  2531. wasm_set_exception(module_inst, "out of memory");
  2532. }
  2533. return 0;
  2534. }
  2535. if (p_native_addr)
  2536. *p_native_addr = addr;
  2537. return (uint32)(addr - memory->memory_data);
  2538. }
  2539. void
  2540. wasm_module_free_internal(WASMModuleInstance *module_inst,
  2541. WASMExecEnv *exec_env, uint32 ptr)
  2542. {
  2543. if (ptr) {
  2544. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2545. uint8 *addr;
  2546. if (!memory) {
  2547. return;
  2548. }
  2549. addr = memory->memory_data + ptr;
  2550. if (memory->heap_handle && memory->heap_data <= addr
  2551. && addr < memory->heap_data_end) {
  2552. mem_allocator_free(memory->heap_handle, addr);
  2553. }
  2554. else if (module_inst->e->malloc_function
  2555. && module_inst->e->free_function && memory->memory_data <= addr
  2556. && addr < memory->memory_data_end) {
  2557. execute_free_function(module_inst, exec_env,
  2558. module_inst->e->free_function, ptr);
  2559. }
  2560. }
  2561. }
  2562. uint32
  2563. wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size,
  2564. void **p_native_addr)
  2565. {
  2566. return wasm_module_malloc_internal(module_inst, NULL, size, p_native_addr);
  2567. }
  2568. uint32
  2569. wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size,
  2570. void **p_native_addr)
  2571. {
  2572. return wasm_module_realloc_internal(module_inst, NULL, ptr, size,
  2573. p_native_addr);
  2574. }
  2575. void
  2576. wasm_module_free(WASMModuleInstance *module_inst, uint32 ptr)
  2577. {
  2578. wasm_module_free_internal(module_inst, NULL, ptr);
  2579. }
  2580. uint32
  2581. wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src,
  2582. uint32 size)
  2583. {
  2584. char *buffer;
  2585. uint32 buffer_offset =
  2586. wasm_module_malloc(module_inst, size, (void **)&buffer);
  2587. if (buffer_offset != 0) {
  2588. buffer = wasm_runtime_addr_app_to_native(
  2589. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  2590. bh_memcpy_s(buffer, size, src, size);
  2591. }
  2592. return buffer_offset;
  2593. }
  2594. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2595. bool
  2596. wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx,
  2597. uint32 inc_size, table_elem_type_t init_val)
  2598. {
  2599. uint32 total_size, i;
  2600. table_elem_type_t *new_table_data_start;
  2601. WASMTableInstance *table_inst;
  2602. if (!inc_size) {
  2603. return true;
  2604. }
  2605. bh_assert(table_idx < module_inst->table_count);
  2606. table_inst = wasm_get_table_inst(module_inst, table_idx);
  2607. if (!table_inst) {
  2608. return false;
  2609. }
  2610. if (inc_size > UINT32_MAX - table_inst->cur_size) {
  2611. return false;
  2612. }
  2613. total_size = table_inst->cur_size + inc_size;
  2614. if (total_size > table_inst->max_size) {
  2615. return false;
  2616. }
  2617. /* fill in */
  2618. new_table_data_start = table_inst->elems + table_inst->cur_size;
  2619. for (i = 0; i < inc_size; ++i) {
  2620. new_table_data_start[i] = init_val;
  2621. }
  2622. table_inst->cur_size = total_size;
  2623. return true;
  2624. }
  2625. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  2626. static bool
  2627. call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 tbl_elem_idx,
  2628. uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx)
  2629. {
  2630. WASMModuleInstance *module_inst = NULL;
  2631. WASMTableInstance *table_inst = NULL;
  2632. table_elem_type_t tbl_elem_val = NULL_REF;
  2633. uint32 func_idx = 0;
  2634. WASMFunctionInstance *func_inst = NULL;
  2635. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  2636. bh_assert(module_inst);
  2637. table_inst = module_inst->tables[tbl_idx];
  2638. if (!table_inst) {
  2639. wasm_set_exception(module_inst, "unknown table");
  2640. goto got_exception;
  2641. }
  2642. if (tbl_elem_idx >= table_inst->cur_size) {
  2643. wasm_set_exception(module_inst, "undefined element");
  2644. goto got_exception;
  2645. }
  2646. tbl_elem_val = ((table_elem_type_t *)table_inst->elems)[tbl_elem_idx];
  2647. if (tbl_elem_val == NULL_REF) {
  2648. wasm_set_exception(module_inst, "uninitialized element");
  2649. goto got_exception;
  2650. }
  2651. #if WASM_ENABLE_GC == 0
  2652. func_idx = tbl_elem_val;
  2653. #else
  2654. func_idx =
  2655. wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val);
  2656. #endif
  2657. /**
  2658. * we insist to call functions owned by the module itself
  2659. **/
  2660. if (func_idx >= module_inst->e->function_count) {
  2661. wasm_set_exception(module_inst, "unknown function");
  2662. goto got_exception;
  2663. }
  2664. func_inst = module_inst->e->functions + func_idx;
  2665. if (check_type_idx) {
  2666. WASMType *cur_type = module_inst->module->types[type_idx];
  2667. WASMType *cur_func_type;
  2668. if (func_inst->is_import_func)
  2669. cur_func_type = (WASMType *)func_inst->u.func_import->func_type;
  2670. else
  2671. cur_func_type = (WASMType *)func_inst->u.func->func_type;
  2672. if (cur_type != cur_func_type) {
  2673. wasm_set_exception(module_inst, "indirect call type mismatch");
  2674. goto got_exception;
  2675. }
  2676. }
  2677. interp_call_wasm(module_inst, exec_env, func_inst, argc, argv);
  2678. return !wasm_copy_exception(module_inst, NULL);
  2679. got_exception:
  2680. return false;
  2681. }
  2682. bool
  2683. wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2684. uint32 argc, uint32 argv[])
  2685. {
  2686. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  2687. }
  2688. #if WASM_ENABLE_THREAD_MGR != 0
  2689. bool
  2690. wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size)
  2691. {
  2692. WASMModuleInstance *module_inst =
  2693. (WASMModuleInstance *)exec_env->module_inst;
  2694. uint32 stack_top_idx = module_inst->module->aux_stack_top_global_index;
  2695. #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0
  2696. /* Check the aux stack space */
  2697. uint32 data_end = module_inst->module->aux_data_end;
  2698. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2699. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  2700. if ((is_stack_before_data && (size > start_offset))
  2701. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  2702. return false;
  2703. #endif
  2704. if (stack_top_idx != (uint32)-1) {
  2705. /* The aux stack top is a wasm global,
  2706. set the initial value for the global */
  2707. uint8 *global_addr =
  2708. module_inst->global_data
  2709. + module_inst->e->globals[stack_top_idx].data_offset;
  2710. *(int32 *)global_addr = start_offset;
  2711. /* The aux stack boundary is a constant value,
  2712. set the value to exec_env */
  2713. exec_env->aux_stack_boundary.boundary = start_offset - size;
  2714. exec_env->aux_stack_bottom.bottom = start_offset;
  2715. return true;
  2716. }
  2717. return false;
  2718. }
  2719. bool
  2720. wasm_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size)
  2721. {
  2722. WASMModuleInstance *module_inst =
  2723. (WASMModuleInstance *)exec_env->module_inst;
  2724. /* The aux stack information is resolved in loader
  2725. and store in module */
  2726. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2727. uint32 total_aux_stack_size = module_inst->module->aux_stack_size;
  2728. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  2729. if (start_offset)
  2730. *start_offset = stack_bottom;
  2731. if (size)
  2732. *size = total_aux_stack_size;
  2733. return true;
  2734. }
  2735. return false;
  2736. }
  2737. #endif
  2738. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  2739. void
  2740. wasm_get_module_mem_consumption(const WASMModule *module,
  2741. WASMModuleMemConsumption *mem_conspn)
  2742. {
  2743. uint32 i, size;
  2744. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2745. mem_conspn->module_struct_size = sizeof(WASMModule);
  2746. mem_conspn->types_size = sizeof(WASMFuncType *) * module->type_count;
  2747. for (i = 0; i < module->type_count; i++) {
  2748. WASMFuncType *type = module->types[i];
  2749. size = offsetof(WASMFuncType, types)
  2750. + sizeof(uint8) * (type->param_count + type->result_count);
  2751. mem_conspn->types_size += size;
  2752. }
  2753. mem_conspn->imports_size = sizeof(WASMImport) * module->import_count;
  2754. mem_conspn->functions_size =
  2755. sizeof(WASMFunction *) * module->function_count;
  2756. for (i = 0; i < module->function_count; i++) {
  2757. WASMFunction *func = module->functions[i];
  2758. WASMFuncType *type = func->func_type;
  2759. size = sizeof(WASMFunction) + func->local_count
  2760. + sizeof(uint16) * (type->param_count + func->local_count);
  2761. #if WASM_ENABLE_FAST_INTERP != 0
  2762. size +=
  2763. func->code_compiled_size + sizeof(uint32) * func->const_cell_num;
  2764. #endif
  2765. mem_conspn->functions_size += size;
  2766. }
  2767. mem_conspn->tables_size = sizeof(WASMTable) * module->table_count;
  2768. mem_conspn->memories_size = sizeof(WASMMemory) * module->memory_count;
  2769. mem_conspn->globals_size = sizeof(WASMGlobal) * module->global_count;
  2770. mem_conspn->exports_size = sizeof(WASMExport) * module->export_count;
  2771. mem_conspn->table_segs_size =
  2772. sizeof(WASMTableSeg) * module->table_seg_count;
  2773. for (i = 0; i < module->table_seg_count; i++) {
  2774. WASMTableSeg *table_seg = &module->table_segments[i];
  2775. mem_conspn->tables_size += sizeof(uint32) * table_seg->function_count;
  2776. }
  2777. mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count;
  2778. for (i = 0; i < module->data_seg_count; i++) {
  2779. mem_conspn->data_segs_size += sizeof(WASMDataSeg);
  2780. }
  2781. if (module->const_str_list) {
  2782. StringNode *node = module->const_str_list, *node_next;
  2783. while (node) {
  2784. node_next = node->next;
  2785. mem_conspn->const_strs_size +=
  2786. sizeof(StringNode) + strlen(node->str) + 1;
  2787. node = node_next;
  2788. }
  2789. }
  2790. mem_conspn->total_size += mem_conspn->module_struct_size;
  2791. mem_conspn->total_size += mem_conspn->types_size;
  2792. mem_conspn->total_size += mem_conspn->imports_size;
  2793. mem_conspn->total_size += mem_conspn->functions_size;
  2794. mem_conspn->total_size += mem_conspn->tables_size;
  2795. mem_conspn->total_size += mem_conspn->memories_size;
  2796. mem_conspn->total_size += mem_conspn->globals_size;
  2797. mem_conspn->total_size += mem_conspn->exports_size;
  2798. mem_conspn->total_size += mem_conspn->table_segs_size;
  2799. mem_conspn->total_size += mem_conspn->data_segs_size;
  2800. mem_conspn->total_size += mem_conspn->const_strs_size;
  2801. }
  2802. void
  2803. wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst,
  2804. WASMModuleInstMemConsumption *mem_conspn)
  2805. {
  2806. uint32 i, size;
  2807. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2808. mem_conspn->module_inst_struct_size = (uint8 *)module_inst->e
  2809. - (uint8 *)module_inst
  2810. + sizeof(WASMModuleInstanceExtra);
  2811. mem_conspn->memories_size =
  2812. sizeof(WASMMemoryInstance *) * module_inst->memory_count;
  2813. for (i = 0; i < module_inst->memory_count; i++) {
  2814. WASMMemoryInstance *memory = module_inst->memories[i];
  2815. size = memory->num_bytes_per_page * memory->cur_page_count;
  2816. mem_conspn->memories_size += size;
  2817. mem_conspn->app_heap_size += memory->heap_data_end - memory->heap_data;
  2818. /* size of app heap structure */
  2819. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  2820. /* Module instance structures have been appened into the end of
  2821. module instance */
  2822. }
  2823. mem_conspn->tables_size =
  2824. sizeof(WASMTableInstance *) * module_inst->table_count;
  2825. /* Table instance structures and table elements have been appened into
  2826. the end of module instance */
  2827. mem_conspn->functions_size =
  2828. sizeof(WASMFunctionInstance) * module_inst->e->function_count;
  2829. mem_conspn->globals_size =
  2830. sizeof(WASMGlobalInstance) * module_inst->e->global_count;
  2831. /* Global data has been appened into the end of module instance */
  2832. mem_conspn->exports_size =
  2833. sizeof(WASMExportFuncInstance) * module_inst->export_func_count;
  2834. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  2835. mem_conspn->total_size += mem_conspn->memories_size;
  2836. mem_conspn->total_size += mem_conspn->functions_size;
  2837. mem_conspn->total_size += mem_conspn->tables_size;
  2838. mem_conspn->total_size += mem_conspn->globals_size;
  2839. mem_conspn->total_size += mem_conspn->exports_size;
  2840. }
  2841. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  2842. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  2843. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2844. bool
  2845. wasm_interp_create_call_stack(struct WASMExecEnv *exec_env)
  2846. {
  2847. WASMModuleInstance *module_inst =
  2848. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2849. WASMInterpFrame *first_frame,
  2850. *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  2851. uint32 n = 0;
  2852. /* count frames includes a function */
  2853. first_frame = cur_frame;
  2854. while (cur_frame) {
  2855. if (cur_frame->function) {
  2856. n++;
  2857. }
  2858. cur_frame = cur_frame->prev_frame;
  2859. }
  2860. /* release previous stack frames and create new ones */
  2861. if (!bh_vector_destroy(module_inst->frames)
  2862. || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame),
  2863. false)) {
  2864. return false;
  2865. }
  2866. cur_frame = first_frame;
  2867. n = 0;
  2868. while (cur_frame) {
  2869. WASMCApiFrame frame = { 0 };
  2870. WASMFunctionInstance *func_inst = cur_frame->function;
  2871. const char *func_name = NULL;
  2872. const uint8 *func_code_base = NULL;
  2873. if (!func_inst) {
  2874. cur_frame = cur_frame->prev_frame;
  2875. continue;
  2876. }
  2877. /* place holder, will overwrite it in wasm_c_api */
  2878. frame.instance = module_inst;
  2879. frame.module_offset = 0;
  2880. frame.func_index = (uint32)(func_inst - module_inst->e->functions);
  2881. func_code_base = wasm_get_func_code(func_inst);
  2882. if (!cur_frame->ip || !func_code_base) {
  2883. frame.func_offset = 0;
  2884. }
  2885. else {
  2886. frame.func_offset = (uint32)(cur_frame->ip - func_code_base);
  2887. }
  2888. /* look for the function name */
  2889. if (func_inst->is_import_func) {
  2890. func_name = func_inst->u.func_import->field_name;
  2891. }
  2892. else {
  2893. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2894. func_name = func_inst->u.func->field_name;
  2895. #endif
  2896. /* if custom name section is not generated,
  2897. search symbols from export table */
  2898. if (!func_name) {
  2899. uint32 i;
  2900. for (i = 0; i < module_inst->export_func_count; i++) {
  2901. WASMExportFuncInstance *export_func =
  2902. module_inst->export_functions + i;
  2903. if (export_func->function == func_inst) {
  2904. func_name = export_func->name;
  2905. break;
  2906. }
  2907. }
  2908. }
  2909. }
  2910. frame.func_name_wp = func_name;
  2911. if (!bh_vector_append(module_inst->frames, &frame)) {
  2912. bh_vector_destroy(module_inst->frames);
  2913. return false;
  2914. }
  2915. cur_frame = cur_frame->prev_frame;
  2916. n++;
  2917. }
  2918. return true;
  2919. }
  2920. #define PRINT_OR_DUMP() \
  2921. do { \
  2922. total_len += \
  2923. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  2924. if ((!print) && buf && (len == 0)) { \
  2925. return total_len; \
  2926. } \
  2927. } while (0)
  2928. uint32
  2929. wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf,
  2930. uint32 len)
  2931. {
  2932. WASMModuleInstance *module_inst =
  2933. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2934. uint32 n = 0, total_len = 0, total_frames;
  2935. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  2936. * will be truncated */
  2937. char line_buf[256];
  2938. if (!module_inst->frames) {
  2939. return 0;
  2940. }
  2941. total_frames = (uint32)bh_vector_size(module_inst->frames);
  2942. if (total_frames == 0) {
  2943. return 0;
  2944. }
  2945. snprintf(line_buf, sizeof(line_buf), "\n");
  2946. PRINT_OR_DUMP();
  2947. while (n < total_frames) {
  2948. WASMCApiFrame frame = { 0 };
  2949. uint32 line_length, i;
  2950. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  2951. return 0;
  2952. }
  2953. /* function name not exported, print number instead */
  2954. if (frame.func_name_wp == NULL) {
  2955. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d $f%d\n",
  2956. n, frame.func_index);
  2957. }
  2958. else {
  2959. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d %s\n", n,
  2960. frame.func_name_wp);
  2961. }
  2962. if (line_length >= sizeof(line_buf)) {
  2963. uint32 line_buffer_len = sizeof(line_buf);
  2964. /* If line too long, ensure the last character is '\n' */
  2965. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  2966. line_buf[i] = '.';
  2967. }
  2968. line_buf[line_buffer_len - 2] = '\n';
  2969. }
  2970. PRINT_OR_DUMP();
  2971. n++;
  2972. }
  2973. snprintf(line_buf, sizeof(line_buf), "\n");
  2974. PRINT_OR_DUMP();
  2975. return total_len + 1;
  2976. }
  2977. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  2978. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  2979. || WASM_ENABLE_WAMR_COMPILER != 0
  2980. void
  2981. jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  2982. {
  2983. if (id != EXCE_ALREADY_THROWN)
  2984. wasm_set_exception_with_id(module_inst, id);
  2985. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2986. wasm_runtime_access_exce_check_guard_page();
  2987. #endif
  2988. }
  2989. bool
  2990. jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str,
  2991. uint32 app_buf_addr, uint32 app_buf_size,
  2992. void **p_native_addr)
  2993. {
  2994. bool ret = wasm_check_app_addr_and_convert(
  2995. module_inst, is_str, app_buf_addr, app_buf_size, p_native_addr);
  2996. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2997. if (!ret)
  2998. wasm_runtime_access_exce_check_guard_page();
  2999. #endif
  3000. return ret;
  3001. }
  3002. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  3003. || WASM_ENABLE_WAMR_COMPILER != 0 */
  3004. #if WASM_ENABLE_FAST_JIT != 0
  3005. bool
  3006. fast_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3007. uint32 type_idx, uint32 argc, uint32 *argv)
  3008. {
  3009. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, true,
  3010. type_idx);
  3011. }
  3012. #endif /* end of WASM_ENABLE_FAST_JIT != 0 */
  3013. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  3014. bool
  3015. llvm_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3016. uint32 argc, uint32 *argv)
  3017. {
  3018. bool ret;
  3019. #if WASM_ENABLE_JIT != 0
  3020. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  3021. return aot_call_indirect(exec_env, tbl_idx, elem_idx, argc, argv);
  3022. }
  3023. #endif
  3024. ret = call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  3025. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3026. if (!ret)
  3027. wasm_runtime_access_exce_check_guard_page();
  3028. #endif
  3029. return ret;
  3030. }
  3031. bool
  3032. llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  3033. uint32 *argv)
  3034. {
  3035. WASMModuleInstance *module_inst;
  3036. WASMModule *module;
  3037. uint32 *func_type_indexes;
  3038. uint32 func_type_idx;
  3039. WASMFuncType *func_type;
  3040. void *func_ptr;
  3041. WASMFunctionImport *import_func;
  3042. CApiFuncImport *c_api_func_import = NULL;
  3043. const char *signature;
  3044. void *attachment;
  3045. char buf[96];
  3046. bool ret = false;
  3047. #if WASM_ENABLE_JIT != 0
  3048. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  3049. return aot_invoke_native(exec_env, func_idx, argc, argv);
  3050. }
  3051. #endif
  3052. module_inst = (WASMModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  3053. module = module_inst->module;
  3054. func_type_indexes = module_inst->func_type_indexes;
  3055. func_type_idx = func_type_indexes[func_idx];
  3056. func_type = module->types[func_type_idx];
  3057. func_ptr = module_inst->func_ptrs[func_idx];
  3058. bh_assert(func_idx < module->import_function_count);
  3059. import_func = &module->import_functions[func_idx].u.function;
  3060. if (import_func->call_conv_wasm_c_api) {
  3061. if (module_inst->e->c_api_func_imports) {
  3062. c_api_func_import = module_inst->e->c_api_func_imports + func_idx;
  3063. func_ptr = c_api_func_import->func_ptr_linked;
  3064. }
  3065. else {
  3066. c_api_func_import = NULL;
  3067. func_ptr = NULL;
  3068. }
  3069. }
  3070. if (!func_ptr) {
  3071. snprintf(buf, sizeof(buf),
  3072. "failed to call unlinked import function (%s, %s)",
  3073. import_func->module_name, import_func->field_name);
  3074. wasm_set_exception(module_inst, buf);
  3075. goto fail;
  3076. }
  3077. attachment = import_func->attachment;
  3078. if (import_func->call_conv_wasm_c_api) {
  3079. ret = wasm_runtime_invoke_c_api_native(
  3080. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  3081. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  3082. }
  3083. else if (!import_func->call_conv_raw) {
  3084. signature = import_func->signature;
  3085. ret =
  3086. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  3087. attachment, argv, argc, argv);
  3088. }
  3089. else {
  3090. signature = import_func->signature;
  3091. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  3092. signature, attachment, argv, argc,
  3093. argv);
  3094. }
  3095. fail:
  3096. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3097. if (!ret)
  3098. wasm_runtime_access_exce_check_guard_page();
  3099. #endif
  3100. return ret;
  3101. }
  3102. #if WASM_ENABLE_BULK_MEMORY != 0
  3103. bool
  3104. llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index,
  3105. uint32 offset, uint32 len, uint32 dst)
  3106. {
  3107. WASMMemoryInstance *memory_inst;
  3108. WASMModule *module;
  3109. uint8 *data = NULL;
  3110. uint8 *maddr;
  3111. uint64 seg_len = 0;
  3112. #if WASM_ENABLE_JIT != 0
  3113. if (Wasm_Module_AoT == module_inst->module_type) {
  3114. return aot_memory_init(module_inst, seg_index, offset, len, dst);
  3115. }
  3116. #endif
  3117. memory_inst = wasm_get_default_memory(module_inst);
  3118. module = module_inst->module;
  3119. seg_len = module->data_segments[seg_index]->data_length;
  3120. data = module->data_segments[seg_index]->data;
  3121. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  3122. dst, len))
  3123. return false;
  3124. if ((uint64)offset + (uint64)len > seg_len) {
  3125. wasm_set_exception(module_inst, "out of bounds memory access");
  3126. return false;
  3127. }
  3128. maddr = wasm_runtime_addr_app_to_native(
  3129. (WASMModuleInstanceCommon *)module_inst, dst);
  3130. bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len);
  3131. return true;
  3132. }
  3133. bool
  3134. llvm_jit_data_drop(WASMModuleInstance *module_inst, uint32 seg_index)
  3135. {
  3136. #if WASM_ENABLE_JIT != 0
  3137. if (Wasm_Module_AoT == module_inst->module_type) {
  3138. return aot_data_drop(module_inst, seg_index);
  3139. }
  3140. #endif
  3141. module_inst->module->data_segments[seg_index]->data_length = 0;
  3142. /* Currently we can't free the dropped data segment
  3143. as they are stored in wasm bytecode */
  3144. return true;
  3145. }
  3146. #endif /* end of WASM_ENABLE_BULK_MEMORY != 0 */
  3147. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  3148. void
  3149. llvm_jit_drop_table_seg(WASMModuleInstance *module_inst, uint32 tbl_seg_idx)
  3150. {
  3151. WASMTableSeg *tbl_segs;
  3152. #if WASM_ENABLE_JIT != 0
  3153. if (Wasm_Module_AoT == module_inst->module_type) {
  3154. return aot_drop_table_seg(module_inst, tbl_seg_idx);
  3155. }
  3156. #endif
  3157. tbl_segs = module_inst->module->table_segments;
  3158. tbl_segs[tbl_seg_idx].is_dropped = true;
  3159. }
  3160. void
  3161. llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx,
  3162. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  3163. uint32 dst_offset)
  3164. {
  3165. WASMTableInstance *tbl_inst;
  3166. WASMTableSeg *tbl_seg;
  3167. #if WASM_ENABLE_JIT != 0
  3168. if (Wasm_Module_AoT == module_inst->module_type) {
  3169. return aot_table_init(module_inst, tbl_idx, tbl_seg_idx, length,
  3170. src_offset, dst_offset);
  3171. }
  3172. #endif
  3173. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  3174. tbl_seg = module_inst->module->table_segments + tbl_seg_idx;
  3175. bh_assert(tbl_inst);
  3176. bh_assert(tbl_seg);
  3177. if (!length) {
  3178. return;
  3179. }
  3180. if (length + src_offset > tbl_seg->function_count
  3181. || dst_offset + length > tbl_inst->cur_size) {
  3182. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3183. return;
  3184. }
  3185. if (tbl_seg->is_dropped) {
  3186. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3187. return;
  3188. }
  3189. if (!wasm_elem_is_passive(tbl_seg->mode)) {
  3190. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3191. return;
  3192. }
  3193. bh_memcpy_s((uint8 *)tbl_inst + offsetof(WASMTableInstance, elems)
  3194. + dst_offset * sizeof(uint32),
  3195. (uint32)sizeof(uint32) * (tbl_inst->cur_size - dst_offset),
  3196. tbl_seg->func_indexes + src_offset,
  3197. (uint32)(length * sizeof(uint32)));
  3198. }
  3199. void
  3200. llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx,
  3201. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  3202. uint32 dst_offset)
  3203. {
  3204. WASMTableInstance *src_tbl_inst;
  3205. WASMTableInstance *dst_tbl_inst;
  3206. #if WASM_ENABLE_JIT != 0
  3207. if (Wasm_Module_AoT == module_inst->module_type) {
  3208. aot_table_copy(module_inst, src_tbl_idx, dst_tbl_idx, length,
  3209. src_offset, dst_offset);
  3210. return;
  3211. }
  3212. #endif
  3213. src_tbl_inst = wasm_get_table_inst(module_inst, src_tbl_idx);
  3214. dst_tbl_inst = wasm_get_table_inst(module_inst, dst_tbl_idx);
  3215. bh_assert(src_tbl_inst);
  3216. bh_assert(dst_tbl_inst);
  3217. if ((uint64)dst_offset + length > dst_tbl_inst->cur_size
  3218. || (uint64)src_offset + length > src_tbl_inst->cur_size) {
  3219. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3220. return;
  3221. }
  3222. /* if src_offset >= dst_offset, copy from front to back */
  3223. /* if src_offset < dst_offset, copy from back to front */
  3224. /* merge all together */
  3225. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems)
  3226. + sizeof(uint32) * dst_offset,
  3227. (uint32)sizeof(uint32) * (dst_tbl_inst->cur_size - dst_offset),
  3228. (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems)
  3229. + sizeof(uint32) * src_offset,
  3230. (uint32)sizeof(uint32) * length);
  3231. }
  3232. void
  3233. llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx,
  3234. uint32 length, uint32 val, uint32 data_offset)
  3235. {
  3236. WASMTableInstance *tbl_inst;
  3237. #if WASM_ENABLE_JIT != 0
  3238. if (Wasm_Module_AoT == module_inst->module_type) {
  3239. aot_table_fill(module_inst, tbl_idx, length, val, data_offset);
  3240. return;
  3241. }
  3242. #endif
  3243. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  3244. bh_assert(tbl_inst);
  3245. if (data_offset + length > tbl_inst->cur_size) {
  3246. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3247. return;
  3248. }
  3249. for (; length != 0; data_offset++, length--) {
  3250. tbl_inst->elems[data_offset] = val;
  3251. }
  3252. }
  3253. uint32
  3254. llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx,
  3255. uint32 inc_size, uint32 init_val)
  3256. {
  3257. WASMTableInstance *tbl_inst;
  3258. uint32 i, orig_size, total_size;
  3259. #if WASM_ENABLE_JIT != 0
  3260. if (Wasm_Module_AoT == module_inst->module_type) {
  3261. return aot_table_grow(module_inst, tbl_idx, inc_size, init_val);
  3262. }
  3263. #endif
  3264. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  3265. if (!tbl_inst) {
  3266. return (uint32)-1;
  3267. }
  3268. orig_size = tbl_inst->cur_size;
  3269. if (!inc_size) {
  3270. return orig_size;
  3271. }
  3272. if (tbl_inst->cur_size > UINT32_MAX - inc_size) { /* integer overflow */
  3273. return (uint32)-1;
  3274. }
  3275. total_size = tbl_inst->cur_size + inc_size;
  3276. if (total_size > tbl_inst->max_size) {
  3277. return (uint32)-1;
  3278. }
  3279. /* fill in */
  3280. for (i = 0; i < inc_size; ++i) {
  3281. tbl_inst->elems[tbl_inst->cur_size + i] = init_val;
  3282. }
  3283. tbl_inst->cur_size = total_size;
  3284. return orig_size;
  3285. }
  3286. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  3287. #if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0
  3288. bool
  3289. llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  3290. {
  3291. WASMModuleInstance *module_inst;
  3292. WASMInterpFrame *frame;
  3293. uint32 size;
  3294. #if WASM_ENABLE_JIT != 0
  3295. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  3296. return aot_alloc_frame(exec_env, func_index);
  3297. }
  3298. #endif
  3299. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  3300. size = wasm_interp_interp_frame_size(0);
  3301. frame = wasm_exec_env_alloc_wasm_frame(exec_env, size);
  3302. if (!frame) {
  3303. wasm_set_exception(module_inst, "wasm operand stack overflow");
  3304. return false;
  3305. }
  3306. frame->function = module_inst->e->functions + func_index;
  3307. frame->ip = NULL;
  3308. frame->sp = frame->lp;
  3309. #if WASM_ENABLE_PERF_PROFILING != 0
  3310. frame->time_started = os_time_get_boot_microsecond();
  3311. #endif
  3312. frame->prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  3313. wasm_exec_env_set_cur_frame(exec_env, frame);
  3314. return true;
  3315. }
  3316. void
  3317. llvm_jit_free_frame(WASMExecEnv *exec_env)
  3318. {
  3319. WASMInterpFrame *frame;
  3320. WASMInterpFrame *prev_frame;
  3321. #if WASM_ENABLE_JIT != 0
  3322. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  3323. aot_free_frame(exec_env);
  3324. return;
  3325. }
  3326. #endif
  3327. frame = wasm_exec_env_get_cur_frame(exec_env);
  3328. prev_frame = frame->prev_frame;
  3329. #if WASM_ENABLE_PERF_PROFILING != 0
  3330. if (frame->function) {
  3331. frame->function->total_exec_time +=
  3332. os_time_get_boot_microsecond() - frame->time_started;
  3333. frame->function->total_exec_cnt++;
  3334. }
  3335. #endif
  3336. wasm_exec_env_free_wasm_frame(exec_env, frame);
  3337. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  3338. }
  3339. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 \
  3340. || WASM_ENABLE_PERF_PROFILING != 0 */
  3341. #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
  3342. #if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
  3343. void
  3344. wasm_propagate_wasi_args(WASMModule *module)
  3345. {
  3346. if (!module->import_count)
  3347. return;
  3348. bh_assert(&module->import_module_list_head);
  3349. WASMRegisteredModule *node =
  3350. bh_list_first_elem(&module->import_module_list_head);
  3351. while (node) {
  3352. WASIArguments *wasi_args_impt_mod =
  3353. &((WASMModule *)(node->module))->wasi_args;
  3354. bh_assert(wasi_args_impt_mod);
  3355. bh_memcpy_s(wasi_args_impt_mod, sizeof(WASIArguments),
  3356. &module->wasi_args, sizeof(WASIArguments));
  3357. node = bh_list_elem_next(node);
  3358. }
  3359. }
  3360. #endif