wasm_runtime.c 129 KB

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