wasm_runtime.c 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  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_SHARED_MEMORY != 0
  13. #include "../common/wasm_shared_memory.h"
  14. #endif
  15. #if WASM_ENABLE_THREAD_MGR != 0
  16. #include "../libraries/thread-mgr/thread_manager.h"
  17. #endif
  18. #if WASM_ENABLE_DEBUG_INTERP != 0
  19. #include "../libraries/debug-engine/debug_engine.h"
  20. #endif
  21. static void
  22. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  23. {
  24. if (error_buf != NULL) {
  25. snprintf(error_buf, error_buf_size,
  26. "WASM module instantiate failed: %s", string);
  27. }
  28. }
  29. static void
  30. set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...)
  31. {
  32. va_list args;
  33. char buf[128];
  34. if (error_buf != NULL) {
  35. va_start(args, format);
  36. vsnprintf(buf, sizeof(buf), format, args);
  37. va_end(args);
  38. snprintf(error_buf, error_buf_size,
  39. "WASM module instantiate failed: %s", buf);
  40. }
  41. }
  42. WASMModule *
  43. wasm_load(uint8 *buf, uint32 size, char *error_buf, uint32 error_buf_size)
  44. {
  45. return wasm_loader_load(buf, size,
  46. #if WASM_ENABLE_MULTI_MODULE != 0
  47. true,
  48. #endif
  49. error_buf, error_buf_size);
  50. }
  51. WASMModule *
  52. wasm_load_from_sections(WASMSection *section_list, char *error_buf,
  53. uint32 error_buf_size)
  54. {
  55. return wasm_loader_load_from_sections(section_list, error_buf,
  56. error_buf_size);
  57. }
  58. void
  59. wasm_unload(WASMModule *module)
  60. {
  61. wasm_loader_unload(module);
  62. }
  63. static void *
  64. runtime_malloc(uint64 size, char *error_buf, uint32 error_buf_size)
  65. {
  66. void *mem;
  67. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  68. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  69. return NULL;
  70. }
  71. memset(mem, 0, (uint32)size);
  72. return mem;
  73. }
  74. #if WASM_ENABLE_MULTI_MODULE != 0
  75. static WASMModuleInstance *
  76. get_sub_module_inst(const WASMModuleInstance *parent_module_inst,
  77. const WASMModule *sub_module)
  78. {
  79. bh_list *sub_module_inst_list = parent_module_inst->sub_module_inst_list;
  80. WASMSubModInstNode *node = bh_list_first_elem(sub_module_inst_list);
  81. while (node && sub_module != node->module_inst->module) {
  82. node = bh_list_elem_next(node);
  83. }
  84. return node ? node->module_inst : NULL;
  85. }
  86. #endif
  87. /**
  88. * Destroy memory instances.
  89. */
  90. static void
  91. memories_deinstantiate(WASMModuleInstance *module_inst,
  92. WASMMemoryInstance **memories, uint32 count)
  93. {
  94. uint32 i;
  95. if (memories) {
  96. for (i = 0; i < count; i++) {
  97. if (memories[i]) {
  98. #if WASM_ENABLE_MULTI_MODULE != 0
  99. if (i < module_inst->module->import_memory_count)
  100. continue;
  101. #endif
  102. #if WASM_ENABLE_SHARED_MEMORY != 0
  103. if (memories[i]->is_shared) {
  104. int32 ref_count = shared_memory_dec_reference(
  105. (WASMModuleCommon *)module_inst->module);
  106. bh_assert(ref_count >= 0);
  107. /* if the reference count is not zero,
  108. don't free the memory */
  109. if (ref_count > 0)
  110. continue;
  111. }
  112. os_mutex_destroy(&memories[i]->mem_lock);
  113. #endif
  114. if (memories[i]->heap_handle) {
  115. mem_allocator_destroy(memories[i]->heap_handle);
  116. wasm_runtime_free(memories[i]->heap_handle);
  117. memories[i]->heap_handle = NULL;
  118. }
  119. if (memories[i]->memory_data) {
  120. #ifndef OS_ENABLE_HW_BOUND_CHECK
  121. wasm_runtime_free(memories[i]->memory_data);
  122. #else
  123. #ifdef BH_PLATFORM_WINDOWS
  124. os_mem_decommit(memories[i]->memory_data,
  125. memories[i]->num_bytes_per_page
  126. * memories[i]->cur_page_count);
  127. #endif
  128. os_munmap((uint8 *)memories[i]->memory_data,
  129. 8 * (uint64)BH_GB);
  130. #endif
  131. }
  132. wasm_runtime_free(memories[i]);
  133. }
  134. }
  135. wasm_runtime_free(memories);
  136. }
  137. (void)module_inst;
  138. }
  139. static WASMMemoryInstance *
  140. memory_instantiate(WASMModuleInstance *module_inst, uint32 num_bytes_per_page,
  141. uint32 init_page_count, uint32 max_page_count,
  142. uint32 heap_size, uint32 flags, char *error_buf,
  143. uint32 error_buf_size)
  144. {
  145. WASMModule *module = module_inst->module;
  146. WASMMemoryInstance *memory;
  147. uint64 memory_data_size;
  148. uint32 heap_offset = num_bytes_per_page * init_page_count;
  149. uint32 inc_page_count, aux_heap_base, global_idx;
  150. uint32 bytes_of_last_page, bytes_to_page_end;
  151. uint8 *global_addr;
  152. #ifdef OS_ENABLE_HW_BOUND_CHECK
  153. uint8 *mapped_mem;
  154. uint64 map_size = 8 * (uint64)BH_GB;
  155. uint64 page_size = os_getpagesize();
  156. #endif
  157. #if WASM_ENABLE_SHARED_MEMORY != 0
  158. bool is_shared_memory = flags & 0x02 ? true : false;
  159. /* shared memory */
  160. if (is_shared_memory) {
  161. WASMSharedMemNode *node = wasm_module_get_shared_memory(
  162. (WASMModuleCommon *)module_inst->module);
  163. /* If the memory of this module has been instantiated,
  164. return the memory instance directly */
  165. if (node) {
  166. uint32 ref_count;
  167. ref_count = shared_memory_inc_reference(
  168. (WASMModuleCommon *)module_inst->module);
  169. bh_assert(ref_count > 0);
  170. memory = (WASMMemoryInstance *)shared_memory_get_memory_inst(node);
  171. bh_assert(memory);
  172. (void)ref_count;
  173. return memory;
  174. }
  175. }
  176. #endif /* end of WASM_ENABLE_SHARED_MEMORY */
  177. if (heap_size > 0 && module_inst->module->malloc_function != (uint32)-1
  178. && module_inst->module->free_function != (uint32)-1) {
  179. /* Disable app heap, use malloc/free function exported
  180. by wasm app to allocate/free memory instead */
  181. heap_size = 0;
  182. }
  183. if (init_page_count == max_page_count && init_page_count == 1) {
  184. /* If only one page and at most one page, we just append
  185. the app heap to the end of linear memory, enlarge the
  186. num_bytes_per_page, and don't change the page count*/
  187. heap_offset = num_bytes_per_page;
  188. num_bytes_per_page += heap_size;
  189. if (num_bytes_per_page < heap_size) {
  190. set_error_buf(error_buf, error_buf_size,
  191. "memory size must be at most 65536 pages (4GiB)");
  192. return NULL;
  193. }
  194. }
  195. else if (heap_size > 0) {
  196. if (module->aux_heap_base_global_index != (uint32)-1
  197. && module->aux_heap_base < num_bytes_per_page * init_page_count) {
  198. /* Insert app heap before __heap_base */
  199. aux_heap_base = module->aux_heap_base;
  200. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  201. if (bytes_of_last_page == 0)
  202. bytes_of_last_page = num_bytes_per_page;
  203. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  204. inc_page_count =
  205. (heap_size - bytes_to_page_end + num_bytes_per_page - 1)
  206. / num_bytes_per_page;
  207. heap_offset = aux_heap_base;
  208. aux_heap_base += heap_size;
  209. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  210. if (bytes_of_last_page == 0)
  211. bytes_of_last_page = num_bytes_per_page;
  212. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  213. if (bytes_to_page_end < 1 * BH_KB) {
  214. aux_heap_base += 1 * BH_KB;
  215. inc_page_count++;
  216. }
  217. /* Adjust __heap_base global value */
  218. global_idx = module->aux_heap_base_global_index;
  219. bh_assert(module_inst->globals
  220. && global_idx < module_inst->global_count);
  221. global_addr = module_inst->global_data
  222. + module_inst->globals[global_idx].data_offset;
  223. *(uint32 *)global_addr = aux_heap_base;
  224. LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base);
  225. }
  226. else {
  227. /* Insert app heap before new page */
  228. inc_page_count =
  229. (heap_size + num_bytes_per_page - 1) / num_bytes_per_page;
  230. heap_offset = num_bytes_per_page * init_page_count;
  231. heap_size = num_bytes_per_page * inc_page_count;
  232. if (heap_size > 0)
  233. heap_size -= 1 * BH_KB;
  234. }
  235. init_page_count += inc_page_count;
  236. max_page_count += inc_page_count;
  237. if (init_page_count > 65536) {
  238. set_error_buf(error_buf, error_buf_size,
  239. "memory size must be at most 65536 pages (4GiB)");
  240. return NULL;
  241. }
  242. if (max_page_count > 65536)
  243. max_page_count = 65536;
  244. }
  245. LOG_VERBOSE("Memory instantiate:");
  246. LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u",
  247. num_bytes_per_page, init_page_count, max_page_count);
  248. LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size);
  249. memory_data_size = (uint64)num_bytes_per_page * init_page_count;
  250. #if WASM_ENABLE_SHARED_MEMORY != 0
  251. if (is_shared_memory) {
  252. /* Allocate max page for shared memory */
  253. memory_data_size = (uint64)num_bytes_per_page * max_page_count;
  254. }
  255. #endif
  256. /* Allocate memory space, addr data and global data */
  257. if (!(memory = runtime_malloc((uint64)sizeof(WASMMemoryInstance), error_buf,
  258. error_buf_size))) {
  259. return NULL;
  260. }
  261. #ifndef OS_ENABLE_HW_BOUND_CHECK
  262. if (memory_data_size > 0
  263. && !(memory->memory_data =
  264. runtime_malloc(memory_data_size, error_buf, error_buf_size))) {
  265. goto fail1;
  266. }
  267. #else
  268. memory_data_size = (memory_data_size + page_size - 1) & ~(page_size - 1);
  269. /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G:
  270. * ea = i + memarg.offset
  271. * both i and memarg.offset are u32 in range 0 to 4G
  272. * so the range of ea is 0 to 8G
  273. */
  274. if (memory_data_size >= UINT32_MAX
  275. || !(memory->memory_data = mapped_mem =
  276. os_mmap(NULL, map_size, MMAP_PROT_NONE, MMAP_MAP_NONE))) {
  277. set_error_buf(error_buf, error_buf_size, "mmap memory failed");
  278. goto fail1;
  279. }
  280. #ifdef BH_PLATFORM_WINDOWS
  281. if (!os_mem_commit(mapped_mem, memory_data_size,
  282. MMAP_PROT_READ | MMAP_PROT_WRITE)) {
  283. set_error_buf(error_buf, error_buf_size, "commit memory failed");
  284. os_munmap(mapped_mem, map_size);
  285. goto fail1;
  286. }
  287. #endif
  288. if (os_mprotect(mapped_mem, memory_data_size,
  289. MMAP_PROT_READ | MMAP_PROT_WRITE)
  290. != 0) {
  291. set_error_buf(error_buf, error_buf_size, "mprotect memory failed");
  292. goto fail2;
  293. }
  294. /* Newly allocated pages are filled with zero by the OS, we don't fill it
  295. * again here */
  296. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  297. memory->module_type = Wasm_Module_Bytecode;
  298. memory->num_bytes_per_page = num_bytes_per_page;
  299. memory->cur_page_count = init_page_count;
  300. memory->max_page_count = max_page_count;
  301. memory->heap_data = memory->memory_data + heap_offset;
  302. memory->heap_data_end = memory->heap_data + heap_size;
  303. memory->memory_data_end = memory->memory_data + (uint32)memory_data_size;
  304. /* Initialize heap */
  305. if (heap_size > 0) {
  306. uint32 heap_struct_size = mem_allocator_get_heap_struct_size();
  307. if (!(memory->heap_handle = runtime_malloc(
  308. (uint64)heap_struct_size, error_buf, error_buf_size))) {
  309. goto fail2;
  310. }
  311. if (!mem_allocator_create_with_struct_and_pool(
  312. memory->heap_handle, heap_struct_size, memory->heap_data,
  313. heap_size)) {
  314. set_error_buf(error_buf, error_buf_size, "init app heap failed");
  315. goto fail3;
  316. }
  317. }
  318. #if WASM_ENABLE_FAST_JIT != 0
  319. if (memory_data_size > 0) {
  320. #if UINTPTR_MAX == UINT64_MAX
  321. memory->mem_bound_check_1byte = memory_data_size - 1;
  322. memory->mem_bound_check_2bytes = memory_data_size - 2;
  323. memory->mem_bound_check_4bytes = memory_data_size - 4;
  324. memory->mem_bound_check_8bytes = memory_data_size - 8;
  325. memory->mem_bound_check_16bytes = memory_data_size - 16;
  326. #else
  327. memory->mem_bound_check_1byte = (uint32)memory_data_size - 1;
  328. memory->mem_bound_check_2bytes = (uint32)memory_data_size - 2;
  329. memory->mem_bound_check_4bytes = (uint32)memory_data_size - 4;
  330. memory->mem_bound_check_8bytes = (uint32)memory_data_size - 8;
  331. memory->mem_bound_check_16bytes = (uint32)memory_data_size - 16;
  332. #endif
  333. }
  334. #endif
  335. #if WASM_ENABLE_SHARED_MEMORY != 0
  336. if (0 != os_mutex_init(&memory->mem_lock)) {
  337. set_error_buf(error_buf, error_buf_size, "init mutex failed");
  338. goto fail4;
  339. }
  340. if (is_shared_memory) {
  341. memory->is_shared = true;
  342. if (!shared_memory_set_memory_inst(
  343. (WASMModuleCommon *)module_inst->module,
  344. (WASMMemoryInstanceCommon *)memory)) {
  345. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  346. goto fail5;
  347. }
  348. }
  349. #endif
  350. LOG_VERBOSE("Memory instantiate success.");
  351. return memory;
  352. #if WASM_ENABLE_SHARED_MEMORY != 0
  353. fail5:
  354. os_mutex_destroy(&memory->mem_lock);
  355. fail4:
  356. if (heap_size > 0)
  357. mem_allocator_destroy(memory->heap_handle);
  358. #endif
  359. fail3:
  360. if (heap_size > 0)
  361. wasm_runtime_free(memory->heap_handle);
  362. fail2:
  363. #ifndef OS_ENABLE_HW_BOUND_CHECK
  364. if (memory->memory_data)
  365. wasm_runtime_free(memory->memory_data);
  366. #else
  367. #ifdef BH_PLATFORM_WINDOWS
  368. os_mem_decommit(mapped_mem, memory_data_size);
  369. #endif
  370. os_munmap(mapped_mem, map_size);
  371. #endif
  372. fail1:
  373. wasm_runtime_free(memory);
  374. return NULL;
  375. }
  376. /**
  377. * Instantiate memories in a module.
  378. */
  379. static WASMMemoryInstance **
  380. memories_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  381. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  382. {
  383. WASMImport *import;
  384. uint32 mem_index = 0, i,
  385. memory_count = module->import_memory_count + module->memory_count;
  386. uint64 total_size;
  387. WASMMemoryInstance **memories, *memory;
  388. total_size = sizeof(WASMMemoryInstance *) * (uint64)memory_count;
  389. if (!(memories = runtime_malloc(total_size, error_buf, error_buf_size))) {
  390. return NULL;
  391. }
  392. /* instantiate memories from import section */
  393. import = module->import_memories;
  394. for (i = 0; i < module->import_memory_count; i++, import++) {
  395. uint32 num_bytes_per_page = import->u.memory.num_bytes_per_page;
  396. uint32 init_page_count = import->u.memory.init_page_count;
  397. uint32 max_page_count = import->u.memory.max_page_count;
  398. uint32 flags = import->u.memory.flags;
  399. uint32 actual_heap_size = heap_size;
  400. #if WASM_ENABLE_MULTI_MODULE != 0
  401. if (import->u.memory.import_module != NULL) {
  402. WASMModuleInstance *module_inst_linked;
  403. if (!(module_inst_linked = get_sub_module_inst(
  404. module_inst, import->u.memory.import_module))) {
  405. set_error_buf(error_buf, error_buf_size, "unknown memory");
  406. memories_deinstantiate(module_inst, memories, memory_count);
  407. return NULL;
  408. }
  409. if (!(memory = memories[mem_index++] = wasm_lookup_memory(
  410. module_inst_linked, import->u.memory.field_name))) {
  411. set_error_buf(error_buf, error_buf_size, "unknown memory");
  412. memories_deinstantiate(module_inst, memories, memory_count);
  413. return NULL;
  414. }
  415. }
  416. else
  417. #endif
  418. {
  419. if (!(memory = memories[mem_index++] = memory_instantiate(
  420. module_inst, num_bytes_per_page, init_page_count,
  421. max_page_count, actual_heap_size, flags, error_buf,
  422. error_buf_size))) {
  423. memories_deinstantiate(module_inst, memories, memory_count);
  424. return NULL;
  425. }
  426. }
  427. }
  428. /* instantiate memories from memory section */
  429. for (i = 0; i < module->memory_count; i++) {
  430. if (!(memory = memories[mem_index++] = memory_instantiate(
  431. module_inst, module->memories[i].num_bytes_per_page,
  432. module->memories[i].init_page_count,
  433. module->memories[i].max_page_count, heap_size,
  434. module->memories[i].flags, error_buf, error_buf_size))) {
  435. memories_deinstantiate(module_inst, memories, memory_count);
  436. return NULL;
  437. }
  438. }
  439. bh_assert(mem_index == memory_count);
  440. (void)module_inst;
  441. return memories;
  442. }
  443. /**
  444. * Destroy table instances.
  445. */
  446. static void
  447. tables_deinstantiate(WASMTableInstance **tables, uint32 count)
  448. {
  449. uint32 i;
  450. if (tables) {
  451. for (i = 0; i < count; i++)
  452. if (tables[i])
  453. wasm_runtime_free(tables[i]);
  454. wasm_runtime_free(tables);
  455. }
  456. }
  457. /**
  458. * Instantiate tables in a module.
  459. */
  460. static WASMTableInstance **
  461. tables_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  462. char *error_buf, uint32 error_buf_size)
  463. {
  464. WASMImport *import;
  465. uint32 table_index = 0, i,
  466. table_count = module->import_table_count + module->table_count;
  467. uint64 total_size = sizeof(WASMTableInstance *) * (uint64)table_count;
  468. WASMTableInstance **tables, *table;
  469. if (!(tables = runtime_malloc(total_size, error_buf, error_buf_size))) {
  470. return NULL;
  471. }
  472. /* instantiate tables from import section */
  473. import = module->import_tables;
  474. for (i = 0; i < module->import_table_count; i++, import++) {
  475. uint32 max_size_fixed = 0;
  476. #if WASM_ENABLE_MULTI_MODULE != 0
  477. WASMTableInstance *table_inst_linked = NULL;
  478. WASMModuleInstance *module_inst_linked = NULL;
  479. if (import->u.table.import_module) {
  480. if (!(module_inst_linked = get_sub_module_inst(
  481. module_inst, import->u.table.import_module))) {
  482. set_error_buf(error_buf, error_buf_size, "unknown table");
  483. tables_deinstantiate(tables, table_count);
  484. return NULL;
  485. }
  486. if (!(table_inst_linked = wasm_lookup_table(
  487. module_inst_linked, import->u.table.field_name))) {
  488. set_error_buf(error_buf, error_buf_size, "unknown table");
  489. tables_deinstantiate(tables, table_count);
  490. return NULL;
  491. }
  492. total_size = offsetof(WASMTableInstance, base_addr);
  493. }
  494. else
  495. #endif
  496. {
  497. /* in order to save memory, alloc resource as few as possible */
  498. max_size_fixed = import->u.table.possible_grow
  499. ? import->u.table.max_size
  500. : import->u.table.init_size;
  501. /* it is a built-in table, every module has its own */
  502. total_size = offsetof(WASMTableInstance, base_addr);
  503. total_size += (uint64)max_size_fixed * sizeof(uint32);
  504. }
  505. if (!(table = tables[table_index++] =
  506. runtime_malloc(total_size, error_buf, error_buf_size))) {
  507. tables_deinstantiate(tables, table_count);
  508. return NULL;
  509. }
  510. /* Set all elements to -1 to mark them as uninitialized elements */
  511. memset(table, -1, (uint32)total_size);
  512. #if WASM_ENABLE_MULTI_MODULE != 0
  513. table->table_inst_linked = table_inst_linked;
  514. if (table_inst_linked != NULL) {
  515. table->elem_type = table_inst_linked->elem_type;
  516. table->cur_size = table_inst_linked->cur_size;
  517. table->max_size = table_inst_linked->max_size;
  518. }
  519. else
  520. #endif
  521. {
  522. table->elem_type = import->u.table.elem_type;
  523. table->cur_size = import->u.table.init_size;
  524. table->max_size = max_size_fixed;
  525. }
  526. }
  527. /* instantiate tables from table section */
  528. for (i = 0; i < module->table_count; i++) {
  529. uint32 max_size_fixed = 0;
  530. total_size = offsetof(WASMTableInstance, base_addr);
  531. #if WASM_ENABLE_MULTI_MODULE != 0
  532. /* in case, a module which imports this table will grow it */
  533. max_size_fixed = module->tables[i].max_size;
  534. #else
  535. max_size_fixed = module->tables[i].possible_grow
  536. ? module->tables[i].max_size
  537. : module->tables[i].init_size;
  538. #endif
  539. total_size += sizeof(uint32) * (uint64)max_size_fixed;
  540. if (!(table = tables[table_index++] =
  541. runtime_malloc(total_size, error_buf, error_buf_size))) {
  542. tables_deinstantiate(tables, table_count);
  543. return NULL;
  544. }
  545. /* Set all elements to -1 to mark them as uninitialized elements */
  546. memset(table, -1, (uint32)total_size);
  547. table->elem_type = module->tables[i].elem_type;
  548. table->cur_size = module->tables[i].init_size;
  549. table->max_size = max_size_fixed;
  550. #if WASM_ENABLE_MULTI_MODULE != 0
  551. table->table_inst_linked = NULL;
  552. #endif
  553. }
  554. bh_assert(table_index == table_count);
  555. (void)module_inst;
  556. return tables;
  557. }
  558. /**
  559. * Destroy function instances.
  560. */
  561. static void
  562. functions_deinstantiate(WASMFunctionInstance *functions, uint32 count)
  563. {
  564. if (functions) {
  565. wasm_runtime_free(functions);
  566. }
  567. }
  568. /**
  569. * Instantiate functions in a module.
  570. */
  571. static WASMFunctionInstance *
  572. functions_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  573. char *error_buf, uint32 error_buf_size)
  574. {
  575. WASMImport *import;
  576. uint32 i,
  577. function_count = module->import_function_count + module->function_count;
  578. uint64 total_size = sizeof(WASMFunctionInstance) * (uint64)function_count;
  579. WASMFunctionInstance *functions, *function;
  580. if (!(functions = runtime_malloc(total_size, error_buf, error_buf_size))) {
  581. return NULL;
  582. }
  583. total_size = sizeof(void *) * (uint64)module->import_function_count;
  584. if (total_size > 0
  585. && !(module_inst->import_func_ptrs =
  586. runtime_malloc(total_size, error_buf, error_buf_size))) {
  587. wasm_runtime_free(functions);
  588. return NULL;
  589. }
  590. /* instantiate functions from import section */
  591. function = functions;
  592. import = module->import_functions;
  593. for (i = 0; i < module->import_function_count; i++, import++) {
  594. function->is_import_func = true;
  595. #if WASM_ENABLE_MULTI_MODULE != 0
  596. if (import->u.function.import_module) {
  597. function->import_module_inst = get_sub_module_inst(
  598. module_inst, import->u.function.import_module);
  599. if (function->import_module_inst) {
  600. function->import_func_inst =
  601. wasm_lookup_function(function->import_module_inst,
  602. import->u.function.field_name, NULL);
  603. }
  604. }
  605. #endif /* WASM_ENABLE_MULTI_MODULE */
  606. function->u.func_import = &import->u.function;
  607. function->param_cell_num = import->u.function.func_type->param_cell_num;
  608. function->ret_cell_num = import->u.function.func_type->ret_cell_num;
  609. function->param_count =
  610. (uint16)function->u.func_import->func_type->param_count;
  611. function->param_types = function->u.func_import->func_type->types;
  612. function->local_cell_num = 0;
  613. function->local_count = 0;
  614. function->local_types = NULL;
  615. /* Copy the function pointer to current instance */
  616. module_inst->import_func_ptrs[i] =
  617. function->u.func_import->func_ptr_linked;
  618. function++;
  619. }
  620. /* instantiate functions from function section */
  621. for (i = 0; i < module->function_count; i++) {
  622. function->is_import_func = false;
  623. function->u.func = module->functions[i];
  624. function->param_cell_num = function->u.func->param_cell_num;
  625. function->ret_cell_num = function->u.func->ret_cell_num;
  626. function->local_cell_num = function->u.func->local_cell_num;
  627. function->param_count =
  628. (uint16)function->u.func->func_type->param_count;
  629. function->local_count = (uint16)function->u.func->local_count;
  630. function->param_types = function->u.func->func_type->types;
  631. function->local_types = function->u.func->local_types;
  632. function->local_offsets = function->u.func->local_offsets;
  633. #if WASM_ENABLE_FAST_INTERP != 0
  634. function->const_cell_num = function->u.func->const_cell_num;
  635. #endif
  636. function++;
  637. }
  638. #if WASM_ENABLE_FAST_JIT != 0
  639. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  640. #endif
  641. bh_assert((uint32)(function - functions) == function_count);
  642. (void)module_inst;
  643. return functions;
  644. }
  645. /**
  646. * Destroy global instances.
  647. */
  648. static void
  649. globals_deinstantiate(WASMGlobalInstance *globals)
  650. {
  651. if (globals)
  652. wasm_runtime_free(globals);
  653. }
  654. static bool
  655. check_global_init_expr(const WASMModule *module, uint32 global_index,
  656. char *error_buf, uint32 error_buf_size)
  657. {
  658. if (global_index >= module->import_global_count + module->global_count) {
  659. set_error_buf_v(error_buf, error_buf_size, "unknown global %d",
  660. global_index);
  661. return false;
  662. }
  663. /**
  664. * Currently, constant expressions occurring as initializers of
  665. * globals are further constrained in that contained global.get
  666. * instructions are only allowed to refer to imported globals.
  667. *
  668. * And initializer expression cannot reference a mutable global.
  669. */
  670. if (global_index >= module->import_global_count
  671. || (module->import_globals + global_index)->u.global.is_mutable) {
  672. set_error_buf(error_buf, error_buf_size,
  673. "constant expression required");
  674. return false;
  675. }
  676. return true;
  677. }
  678. /**
  679. * Instantiate globals in a module.
  680. */
  681. static WASMGlobalInstance *
  682. globals_instantiate(const WASMModule *module, WASMModuleInstance *module_inst,
  683. uint32 *p_global_data_size, char *error_buf,
  684. uint32 error_buf_size)
  685. {
  686. WASMImport *import;
  687. uint32 global_data_offset = 0;
  688. uint32 i, global_count = module->import_global_count + module->global_count;
  689. uint64 total_size = sizeof(WASMGlobalInstance) * (uint64)global_count;
  690. WASMGlobalInstance *globals, *global;
  691. if (!(globals = runtime_malloc(total_size, error_buf, error_buf_size))) {
  692. return NULL;
  693. }
  694. /* instantiate globals from import section */
  695. global = globals;
  696. import = module->import_globals;
  697. for (i = 0; i < module->import_global_count; i++, import++) {
  698. WASMGlobalImport *global_import = &import->u.global;
  699. global->type = global_import->type;
  700. global->is_mutable = global_import->is_mutable;
  701. #if WASM_ENABLE_MULTI_MODULE != 0
  702. if (global_import->import_module) {
  703. if (!(global->import_module_inst = get_sub_module_inst(
  704. module_inst, global_import->import_module))) {
  705. set_error_buf(error_buf, error_buf_size, "unknown global");
  706. return NULL;
  707. }
  708. if (!(global->import_global_inst = wasm_lookup_global(
  709. global->import_module_inst, global_import->field_name))) {
  710. set_error_buf(error_buf, error_buf_size, "unknown global");
  711. return NULL;
  712. }
  713. /* The linked global instance has been initialized, we
  714. just need to copy the value. */
  715. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  716. &(global_import->import_global_linked->init_expr),
  717. sizeof(WASMValue));
  718. }
  719. else
  720. #endif
  721. {
  722. /* native globals share their initial_values in one module */
  723. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  724. &(global_import->global_data_linked),
  725. sizeof(WASMValue));
  726. }
  727. global->data_offset = global_data_offset;
  728. global_data_offset += wasm_value_type_size(global->type);
  729. global++;
  730. }
  731. /* instantiate globals from global section */
  732. for (i = 0; i < module->global_count; i++) {
  733. InitializerExpression *init_expr = &(module->globals[i].init_expr);
  734. global->type = module->globals[i].type;
  735. global->is_mutable = module->globals[i].is_mutable;
  736. global->data_offset = global_data_offset;
  737. global_data_offset += wasm_value_type_size(global->type);
  738. if (init_expr->init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  739. if (!check_global_init_expr(module, init_expr->u.global_index,
  740. error_buf, error_buf_size)) {
  741. return NULL;
  742. }
  743. bh_memcpy_s(
  744. &(global->initial_value), sizeof(WASMValue),
  745. &(globals[init_expr->u.global_index].initial_value),
  746. sizeof(globals[init_expr->u.global_index].initial_value));
  747. }
  748. #if WASM_ENABLE_REF_TYPES != 0
  749. else if (init_expr->init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST) {
  750. global->initial_value.u32 = (uint32)NULL_REF;
  751. }
  752. #endif
  753. else {
  754. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  755. &(init_expr->u), sizeof(init_expr->u));
  756. }
  757. global++;
  758. }
  759. bh_assert((uint32)(global - globals) == global_count);
  760. *p_global_data_size = global_data_offset;
  761. (void)module_inst;
  762. return globals;
  763. }
  764. /**
  765. * Return export function count in module export section.
  766. */
  767. static uint32
  768. get_export_count(const WASMModule *module, uint8 kind)
  769. {
  770. WASMExport *export = module->exports;
  771. uint32 count = 0, i;
  772. for (i = 0; i < module->export_count; i++, export ++)
  773. if (export->kind == kind)
  774. count++;
  775. return count;
  776. }
  777. /**
  778. * Destroy export function instances.
  779. */
  780. static void
  781. export_functions_deinstantiate(WASMExportFuncInstance *functions)
  782. {
  783. if (functions)
  784. wasm_runtime_free(functions);
  785. }
  786. /**
  787. * Instantiate export functions in a module.
  788. */
  789. static WASMExportFuncInstance *
  790. export_functions_instantiate(const WASMModule *module,
  791. WASMModuleInstance *module_inst,
  792. uint32 export_func_count, char *error_buf,
  793. uint32 error_buf_size)
  794. {
  795. WASMExportFuncInstance *export_funcs, *export_func;
  796. WASMExport *export = module->exports;
  797. uint32 i;
  798. uint64 total_size =
  799. sizeof(WASMExportFuncInstance) * (uint64)export_func_count;
  800. if (!(export_func = export_funcs =
  801. runtime_malloc(total_size, error_buf, error_buf_size))) {
  802. return NULL;
  803. }
  804. for (i = 0; i < module->export_count; i++, export ++)
  805. if (export->kind == EXPORT_KIND_FUNC) {
  806. export_func->name = export->name;
  807. export_func->function = &module_inst->functions[export->index];
  808. export_func++;
  809. }
  810. bh_assert((uint32)(export_func - export_funcs) == export_func_count);
  811. return export_funcs;
  812. }
  813. #if WASM_ENABLE_MULTI_MODULE != 0
  814. static void
  815. export_globals_deinstantiate(WASMExportGlobInstance *globals)
  816. {
  817. if (globals)
  818. wasm_runtime_free(globals);
  819. }
  820. static WASMExportGlobInstance *
  821. export_globals_instantiate(const WASMModule *module,
  822. WASMModuleInstance *module_inst,
  823. uint32 export_glob_count, char *error_buf,
  824. uint32 error_buf_size)
  825. {
  826. WASMExportGlobInstance *export_globals, *export_global;
  827. WASMExport *export = module->exports;
  828. uint32 i;
  829. uint64 total_size =
  830. sizeof(WASMExportGlobInstance) * (uint64)export_glob_count;
  831. if (!(export_global = export_globals =
  832. runtime_malloc(total_size, error_buf, error_buf_size))) {
  833. return NULL;
  834. }
  835. for (i = 0; i < module->export_count; i++, export ++)
  836. if (export->kind == EXPORT_KIND_GLOBAL) {
  837. export_global->name = export->name;
  838. export_global->global = &module_inst->globals[export->index];
  839. export_global++;
  840. }
  841. bh_assert((uint32)(export_global - export_globals) == export_glob_count);
  842. return export_globals;
  843. }
  844. #endif
  845. static bool
  846. execute_post_inst_function(WASMModuleInstance *module_inst)
  847. {
  848. WASMFunctionInstance *post_inst_func = NULL;
  849. WASMType *post_inst_func_type;
  850. uint32 i;
  851. for (i = 0; i < module_inst->export_func_count; i++)
  852. if (!strcmp(module_inst->export_functions[i].name,
  853. "__post_instantiate")) {
  854. post_inst_func = module_inst->export_functions[i].function;
  855. break;
  856. }
  857. if (!post_inst_func)
  858. /* Not found */
  859. return true;
  860. post_inst_func_type = post_inst_func->u.func->func_type;
  861. if (post_inst_func_type->param_count != 0
  862. || post_inst_func_type->result_count != 0)
  863. /* Not a valid function type, ignore it */
  864. return true;
  865. return wasm_create_exec_env_and_call_function(module_inst, post_inst_func,
  866. 0, NULL, false);
  867. }
  868. #if WASM_ENABLE_BULK_MEMORY != 0
  869. static bool
  870. execute_memory_init_function(WASMModuleInstance *module_inst)
  871. {
  872. WASMFunctionInstance *memory_init_func = NULL;
  873. WASMType *memory_init_func_type;
  874. uint32 i;
  875. for (i = 0; i < module_inst->export_func_count; i++)
  876. if (!strcmp(module_inst->export_functions[i].name,
  877. "__wasm_call_ctors")) {
  878. memory_init_func = module_inst->export_functions[i].function;
  879. break;
  880. }
  881. if (!memory_init_func)
  882. /* Not found */
  883. return true;
  884. memory_init_func_type = memory_init_func->u.func->func_type;
  885. if (memory_init_func_type->param_count != 0
  886. || memory_init_func_type->result_count != 0)
  887. /* Not a valid function type, ignore it */
  888. return true;
  889. return wasm_create_exec_env_and_call_function(module_inst, memory_init_func,
  890. 0, NULL, false);
  891. }
  892. #endif
  893. static bool
  894. execute_start_function(WASMModuleInstance *module_inst)
  895. {
  896. WASMFunctionInstance *func = module_inst->start_function;
  897. if (!func)
  898. return true;
  899. bh_assert(!func->is_import_func && func->param_cell_num == 0
  900. && func->ret_cell_num == 0);
  901. return wasm_create_exec_env_and_call_function(module_inst, func, 0, NULL,
  902. false);
  903. }
  904. static bool
  905. execute_malloc_function(WASMModuleInstance *module_inst,
  906. WASMFunctionInstance *malloc_func,
  907. WASMFunctionInstance *retain_func, uint32 size,
  908. uint32 *p_result)
  909. {
  910. #ifdef OS_ENABLE_HW_BOUND_CHECK
  911. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  912. #endif
  913. uint32 argv[2], argc;
  914. bool ret;
  915. argv[0] = size;
  916. argc = 1;
  917. /* if __retain is exported, then this module is compiled by
  918. assemblyscript, the memory should be managed by as's runtime,
  919. in this case we need to call the retain function after malloc
  920. the memory */
  921. if (retain_func) {
  922. /* the malloc functino from assemblyscript is:
  923. function __new(size: usize, id: u32)
  924. id = 0 means this is an ArrayBuffer object */
  925. argv[1] = 0;
  926. argc = 2;
  927. }
  928. #ifdef OS_ENABLE_HW_BOUND_CHECK
  929. if (exec_env_tls != NULL) {
  930. bh_assert(exec_env_tls->module_inst
  931. == (WASMModuleInstanceCommon *)module_inst);
  932. ret = wasm_call_function(exec_env_tls, malloc_func, argc, argv);
  933. if (retain_func && ret) {
  934. ret = wasm_call_function(exec_env_tls, retain_func, 1, argv);
  935. }
  936. }
  937. else
  938. #endif
  939. {
  940. ret = wasm_create_exec_env_and_call_function(module_inst, malloc_func,
  941. argc, argv, false);
  942. if (retain_func && ret) {
  943. ret = wasm_create_exec_env_and_call_function(
  944. module_inst, retain_func, 1, argv, false);
  945. }
  946. }
  947. if (ret)
  948. *p_result = argv[0];
  949. return ret;
  950. }
  951. static bool
  952. execute_free_function(WASMModuleInstance *module_inst,
  953. WASMFunctionInstance *free_func, uint32 offset)
  954. {
  955. #ifdef OS_ENABLE_HW_BOUND_CHECK
  956. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  957. #endif
  958. uint32 argv[2];
  959. argv[0] = offset;
  960. #ifdef OS_ENABLE_HW_BOUND_CHECK
  961. if (exec_env_tls != NULL) {
  962. bh_assert(exec_env_tls->module_inst
  963. == (WASMModuleInstanceCommon *)module_inst);
  964. return wasm_call_function(exec_env_tls, free_func, 1, argv);
  965. }
  966. else
  967. #endif
  968. {
  969. return wasm_create_exec_env_and_call_function(module_inst, free_func, 1,
  970. argv, false);
  971. }
  972. }
  973. #if WASM_ENABLE_MULTI_MODULE != 0
  974. static bool
  975. sub_module_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
  976. uint32 stack_size, uint32 heap_size, char *error_buf,
  977. uint32 error_buf_size)
  978. {
  979. bh_list *sub_module_inst_list = module_inst->sub_module_inst_list;
  980. WASMRegisteredModule *sub_module_list_node =
  981. bh_list_first_elem(module->import_module_list);
  982. while (sub_module_list_node) {
  983. WASMSubModInstNode *sub_module_inst_list_node = NULL;
  984. WASMModule *sub_module = (WASMModule *)sub_module_list_node->module;
  985. WASMModuleInstance *sub_module_inst = NULL;
  986. sub_module_inst =
  987. wasm_instantiate(sub_module, false, stack_size, heap_size,
  988. error_buf, error_buf_size);
  989. if (!sub_module_inst) {
  990. LOG_DEBUG("instantiate %s failed",
  991. sub_module_list_node->module_name);
  992. goto failed;
  993. }
  994. sub_module_inst_list_node = runtime_malloc(sizeof(WASMSubModInstNode),
  995. error_buf, error_buf_size);
  996. if (!sub_module_inst_list_node) {
  997. LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d",
  998. sizeof(WASMSubModInstNode));
  999. goto failed;
  1000. }
  1001. sub_module_inst_list_node->module_inst = sub_module_inst;
  1002. sub_module_inst_list_node->module_name =
  1003. sub_module_list_node->module_name;
  1004. bh_list_status ret =
  1005. bh_list_insert(sub_module_inst_list, sub_module_inst_list_node);
  1006. bh_assert(BH_LIST_SUCCESS == ret);
  1007. (void)ret;
  1008. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  1009. #if WASM_ENABLE_LIBC_WASI != 0
  1010. {
  1011. /*
  1012. * reactor instances may assume that _initialize will be called by
  1013. * the environment at most once, and that none of their other
  1014. * exports are accessed before that call.
  1015. *
  1016. * let the loader decide how to act if there is no _initialize
  1017. * in a reactor
  1018. */
  1019. WASMFunctionInstance *initialize =
  1020. wasm_lookup_function(sub_module_inst, "_initialize", NULL);
  1021. if (initialize
  1022. && !wasm_create_exec_env_and_call_function(
  1023. sub_module_inst, initialize, 0, NULL, false)) {
  1024. set_error_buf(error_buf, error_buf_size,
  1025. "Call _initialize failed ");
  1026. goto failed;
  1027. }
  1028. }
  1029. #endif
  1030. continue;
  1031. failed:
  1032. if (sub_module_inst_list_node) {
  1033. bh_list_remove(sub_module_inst_list, sub_module_inst_list_node);
  1034. wasm_runtime_free(sub_module_inst_list_node);
  1035. }
  1036. if (sub_module_inst)
  1037. wasm_deinstantiate(sub_module_inst, false);
  1038. return false;
  1039. }
  1040. return true;
  1041. }
  1042. static void
  1043. sub_module_deinstantiate(WASMModuleInstance *module_inst)
  1044. {
  1045. bh_list *list = module_inst->sub_module_inst_list;
  1046. WASMSubModInstNode *node = bh_list_first_elem(list);
  1047. while (node) {
  1048. WASMSubModInstNode *next_node = bh_list_elem_next(node);
  1049. bh_list_remove(list, node);
  1050. wasm_deinstantiate(node->module_inst, false);
  1051. wasm_runtime_free(node);
  1052. node = next_node;
  1053. }
  1054. }
  1055. #endif
  1056. static bool
  1057. check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf,
  1058. uint32 error_buf_size)
  1059. {
  1060. WASMModule *module = module_inst->module;
  1061. uint32 i;
  1062. for (i = 0; i < module->import_function_count; i++) {
  1063. WASMFunctionImport *func =
  1064. &((module->import_functions + i)->u.function);
  1065. if (!func->func_ptr_linked
  1066. #if WASM_ENABLE_MULTI_MODULE != 0
  1067. && !func->import_func_linked
  1068. #endif
  1069. ) {
  1070. #if WASM_ENABLE_WAMR_COMPILER == 0
  1071. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1072. func->module_name, func->field_name);
  1073. #else
  1074. /* do nothing to avoid confused message */
  1075. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1076. }
  1077. }
  1078. for (i = 0; i < module->import_global_count; i++) {
  1079. WASMGlobalImport *global = &((module->import_globals + i)->u.global);
  1080. if (!global->is_linked) {
  1081. #if WASM_ENABLE_SPEC_TEST != 0
  1082. set_error_buf(error_buf, error_buf_size,
  1083. "unknown import or incompatible import type");
  1084. return false;
  1085. #else
  1086. #if WASM_ENABLE_WAMR_COMPILER == 0
  1087. LOG_DEBUG("warning: failed to link import global (%s, %s)",
  1088. global->module_name, global->field_name);
  1089. #else
  1090. /* do nothing to avoid confused message */
  1091. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1092. #endif /* WASM_ENABLE_SPEC_TEST != 0 */
  1093. }
  1094. }
  1095. return true;
  1096. }
  1097. /**
  1098. * Instantiate module
  1099. */
  1100. WASMModuleInstance *
  1101. wasm_instantiate(WASMModule *module, bool is_sub_inst, uint32 stack_size,
  1102. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  1103. {
  1104. WASMModuleInstance *module_inst;
  1105. WASMGlobalInstance *globals = NULL, *global;
  1106. uint32 global_count, global_data_size = 0, i;
  1107. uint32 base_offset, length;
  1108. uint8 *global_data, *global_data_end;
  1109. #if WASM_ENABLE_MULTI_MODULE != 0
  1110. bool ret = false;
  1111. #endif
  1112. if (!module)
  1113. return NULL;
  1114. #if WASM_ENABLE_DEBUG_INTERP != 0
  1115. if (!is_sub_inst) {
  1116. os_mutex_lock(&module->ref_count_lock);
  1117. if (module->ref_count != 0) {
  1118. LOG_WARNING(
  1119. "warning: multiple instances referencing the same module may "
  1120. "cause unexpected behaviour during debugging");
  1121. }
  1122. module->ref_count++;
  1123. os_mutex_unlock(&module->ref_count_lock);
  1124. }
  1125. #endif
  1126. /* Check heap size */
  1127. heap_size = align_uint(heap_size, 8);
  1128. if (heap_size > APP_HEAP_SIZE_MAX)
  1129. heap_size = APP_HEAP_SIZE_MAX;
  1130. /* Allocate the memory */
  1131. if (!(module_inst = runtime_malloc(sizeof(WASMModuleInstance), error_buf,
  1132. error_buf_size))) {
  1133. #if WASM_ENABLE_DEBUG_INTERP != 0
  1134. if (!is_sub_inst) {
  1135. os_mutex_lock(&module->ref_count_lock);
  1136. module->ref_count--;
  1137. os_mutex_unlock(&module->ref_count_lock);
  1138. }
  1139. #endif
  1140. return NULL;
  1141. }
  1142. module_inst->module = module;
  1143. #if WASM_ENABLE_MULTI_MODULE != 0
  1144. module_inst->sub_module_inst_list = &module_inst->sub_module_inst_list_head;
  1145. ret = sub_module_instantiate(module, module_inst, stack_size, heap_size,
  1146. error_buf, error_buf_size);
  1147. if (!ret) {
  1148. LOG_DEBUG("build a sub module list failed");
  1149. goto fail;
  1150. }
  1151. #endif
  1152. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1153. if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector),
  1154. error_buf, error_buf_size))) {
  1155. goto fail;
  1156. }
  1157. #endif
  1158. /* Instantiate global firstly to get the mutable data size */
  1159. global_count = module->import_global_count + module->global_count;
  1160. if (global_count
  1161. && !(globals =
  1162. globals_instantiate(module, module_inst, &global_data_size,
  1163. error_buf, error_buf_size))) {
  1164. goto fail;
  1165. }
  1166. module_inst->global_count = global_count;
  1167. module_inst->globals = globals;
  1168. module_inst->memory_count =
  1169. module->import_memory_count + module->memory_count;
  1170. module_inst->table_count = module->import_table_count + module->table_count;
  1171. module_inst->function_count =
  1172. module->import_function_count + module->function_count;
  1173. /* export */
  1174. module_inst->export_func_count = get_export_count(module, EXPORT_KIND_FUNC);
  1175. #if WASM_ENABLE_MULTI_MODULE != 0
  1176. module_inst->export_tab_count = get_export_count(module, EXPORT_KIND_TABLE);
  1177. module_inst->export_mem_count =
  1178. get_export_count(module, EXPORT_KIND_MEMORY);
  1179. module_inst->export_glob_count =
  1180. get_export_count(module, EXPORT_KIND_GLOBAL);
  1181. #endif
  1182. if (global_count > 0) {
  1183. if (!(module_inst->global_data = runtime_malloc(
  1184. global_data_size, error_buf, error_buf_size))) {
  1185. goto fail;
  1186. }
  1187. }
  1188. /* Instantiate memories/tables/functions */
  1189. if ((module_inst->memory_count > 0
  1190. && !(module_inst->memories = memories_instantiate(
  1191. module, module_inst, heap_size, error_buf, error_buf_size)))
  1192. || (module_inst->table_count > 0
  1193. && !(module_inst->tables = tables_instantiate(
  1194. module, module_inst, error_buf, error_buf_size)))
  1195. || (module_inst->function_count > 0
  1196. && !(module_inst->functions = functions_instantiate(
  1197. module, module_inst, error_buf, error_buf_size)))
  1198. || (module_inst->export_func_count > 0
  1199. && !(module_inst->export_functions = export_functions_instantiate(
  1200. module, module_inst, module_inst->export_func_count,
  1201. error_buf, error_buf_size)))
  1202. #if WASM_ENABLE_MULTI_MODULE != 0
  1203. || (module_inst->export_glob_count > 0
  1204. && !(module_inst->export_globals = export_globals_instantiate(
  1205. module, module_inst, module_inst->export_glob_count,
  1206. error_buf, error_buf_size)))
  1207. #endif
  1208. ) {
  1209. goto fail;
  1210. }
  1211. if (global_count > 0) {
  1212. /* Initialize the global data */
  1213. global_data = module_inst->global_data;
  1214. global_data_end = global_data + global_data_size;
  1215. global = globals;
  1216. for (i = 0; i < global_count; i++, global++) {
  1217. switch (global->type) {
  1218. case VALUE_TYPE_I32:
  1219. case VALUE_TYPE_F32:
  1220. #if WASM_ENABLE_REF_TYPES != 0
  1221. case VALUE_TYPE_FUNCREF:
  1222. case VALUE_TYPE_EXTERNREF:
  1223. #endif
  1224. *(int32 *)global_data = global->initial_value.i32;
  1225. global_data += sizeof(int32);
  1226. break;
  1227. case VALUE_TYPE_I64:
  1228. case VALUE_TYPE_F64:
  1229. bh_memcpy_s(global_data,
  1230. (uint32)(global_data_end - global_data),
  1231. &global->initial_value.i64, sizeof(int64));
  1232. global_data += sizeof(int64);
  1233. break;
  1234. default:
  1235. bh_assert(0);
  1236. }
  1237. }
  1238. bh_assert(global_data == global_data_end);
  1239. }
  1240. if (!check_linked_symbol(module_inst, error_buf, error_buf_size)) {
  1241. goto fail;
  1242. }
  1243. /* Initialize the memory data with data segment section */
  1244. module_inst->default_memory =
  1245. module_inst->memory_count ? module_inst->memories[0] : NULL;
  1246. for (i = 0; i < module->data_seg_count; i++) {
  1247. WASMMemoryInstance *memory = NULL;
  1248. uint8 *memory_data = NULL;
  1249. uint32 memory_size = 0;
  1250. WASMDataSeg *data_seg = module->data_segments[i];
  1251. #if WASM_ENABLE_BULK_MEMORY != 0
  1252. if (data_seg->is_passive)
  1253. continue;
  1254. #endif
  1255. /* has check it in loader */
  1256. memory = module_inst->memories[data_seg->memory_index];
  1257. bh_assert(memory);
  1258. memory_data = memory->memory_data;
  1259. memory_size = memory->num_bytes_per_page * memory->cur_page_count;
  1260. bh_assert(memory_data || memory_size == 0);
  1261. bh_assert(data_seg->base_offset.init_expr_type
  1262. == INIT_EXPR_TYPE_I32_CONST
  1263. || data_seg->base_offset.init_expr_type
  1264. == INIT_EXPR_TYPE_GET_GLOBAL);
  1265. if (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  1266. if (!check_global_init_expr(module,
  1267. data_seg->base_offset.u.global_index,
  1268. error_buf, error_buf_size)) {
  1269. goto fail;
  1270. }
  1271. if (!globals
  1272. || globals[data_seg->base_offset.u.global_index].type
  1273. != VALUE_TYPE_I32) {
  1274. set_error_buf(error_buf, error_buf_size,
  1275. "data segment does not fit");
  1276. goto fail;
  1277. }
  1278. base_offset =
  1279. globals[data_seg->base_offset.u.global_index].initial_value.i32;
  1280. }
  1281. else {
  1282. base_offset = (uint32)data_seg->base_offset.u.i32;
  1283. }
  1284. /* check offset */
  1285. if (base_offset > memory_size) {
  1286. LOG_DEBUG("base_offset(%d) > memory_size(%d)", base_offset,
  1287. memory_size);
  1288. #if WASM_ENABLE_REF_TYPES != 0
  1289. set_error_buf(error_buf, error_buf_size,
  1290. "out of bounds memory access");
  1291. #else
  1292. set_error_buf(error_buf, error_buf_size,
  1293. "data segment does not fit");
  1294. #endif
  1295. goto fail;
  1296. }
  1297. /* check offset + length(could be zero) */
  1298. length = data_seg->data_length;
  1299. if (base_offset + length > memory_size) {
  1300. LOG_DEBUG("base_offset(%d) + length(%d) > memory_size(%d)",
  1301. base_offset, length, memory_size);
  1302. #if WASM_ENABLE_REF_TYPES != 0
  1303. set_error_buf(error_buf, error_buf_size,
  1304. "out of bounds memory access");
  1305. #else
  1306. set_error_buf(error_buf, error_buf_size,
  1307. "data segment does not fit");
  1308. #endif
  1309. goto fail;
  1310. }
  1311. if (memory_data) {
  1312. bh_memcpy_s(memory_data + base_offset, memory_size - base_offset,
  1313. data_seg->data, length);
  1314. }
  1315. }
  1316. /* Initialize the table data with table segment section */
  1317. module_inst->default_table =
  1318. module_inst->table_count ? module_inst->tables[0] : NULL;
  1319. /* in case there is no table */
  1320. for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count;
  1321. i++) {
  1322. WASMTableSeg *table_seg = module->table_segments + i;
  1323. /* has check it in loader */
  1324. WASMTableInstance *table = module_inst->tables[table_seg->table_index];
  1325. bh_assert(table);
  1326. #if WASM_ENABLE_REF_TYPES != 0
  1327. if (table->elem_type != VALUE_TYPE_FUNCREF
  1328. && table->elem_type != VALUE_TYPE_EXTERNREF) {
  1329. set_error_buf(error_buf, error_buf_size,
  1330. "elements segment does not fit");
  1331. goto fail;
  1332. }
  1333. #endif
  1334. uint32 *table_data = (uint32 *)table->base_addr;
  1335. #if WASM_ENABLE_MULTI_MODULE != 0
  1336. table_data = table->table_inst_linked
  1337. ? (uint32 *)table->table_inst_linked->base_addr
  1338. : table_data;
  1339. #endif
  1340. bh_assert(table_data);
  1341. #if WASM_ENABLE_REF_TYPES != 0
  1342. if (!wasm_elem_is_active(table_seg->mode))
  1343. continue;
  1344. #endif
  1345. /* init vec(funcidx) or vec(expr) */
  1346. bh_assert(
  1347. table_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  1348. || table_seg->base_offset.init_expr_type
  1349. == INIT_EXPR_TYPE_GET_GLOBAL
  1350. #if WASM_ENABLE_REF_TYPES != 0
  1351. || table_seg->base_offset.init_expr_type
  1352. == INIT_EXPR_TYPE_FUNCREF_CONST
  1353. || table_seg->base_offset.init_expr_type
  1354. == INIT_EXPR_TYPE_REFNULL_CONST
  1355. #endif
  1356. );
  1357. if (table_seg->base_offset.init_expr_type
  1358. == INIT_EXPR_TYPE_GET_GLOBAL) {
  1359. if (!check_global_init_expr(module,
  1360. table_seg->base_offset.u.global_index,
  1361. error_buf, error_buf_size)) {
  1362. goto fail;
  1363. }
  1364. if (!globals
  1365. || globals[table_seg->base_offset.u.global_index].type
  1366. != VALUE_TYPE_I32) {
  1367. set_error_buf(error_buf, error_buf_size,
  1368. "elements segment does not fit");
  1369. goto fail;
  1370. }
  1371. table_seg->base_offset.u.i32 =
  1372. globals[table_seg->base_offset.u.global_index]
  1373. .initial_value.i32;
  1374. }
  1375. /* check offset since length might negative */
  1376. if ((uint32)table_seg->base_offset.u.i32 > table->cur_size) {
  1377. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)",
  1378. table_seg->base_offset.u.i32, table->cur_size);
  1379. #if WASM_ENABLE_REF_TYPES != 0
  1380. set_error_buf(error_buf, error_buf_size,
  1381. "out of bounds table access");
  1382. #else
  1383. set_error_buf(error_buf, error_buf_size,
  1384. "elements segment does not fit");
  1385. #endif
  1386. goto fail;
  1387. }
  1388. /* check offset + length(could be zero) */
  1389. length = table_seg->function_count;
  1390. if ((uint32)table_seg->base_offset.u.i32 + length > table->cur_size) {
  1391. LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)",
  1392. table_seg->base_offset.u.i32, length, table->cur_size);
  1393. #if WASM_ENABLE_REF_TYPES != 0
  1394. set_error_buf(error_buf, error_buf_size,
  1395. "out of bounds table access");
  1396. #else
  1397. set_error_buf(error_buf, error_buf_size,
  1398. "elements segment does not fit");
  1399. #endif
  1400. goto fail;
  1401. }
  1402. /**
  1403. * Check function index in the current module inst for now.
  1404. * will check the linked table inst owner in future.
  1405. * so loader check is enough
  1406. */
  1407. bh_memcpy_s(
  1408. table_data + table_seg->base_offset.u.i32,
  1409. (uint32)((table->cur_size - (uint32)table_seg->base_offset.u.i32)
  1410. * sizeof(uint32)),
  1411. table_seg->func_indexes, (uint32)(length * sizeof(uint32)));
  1412. }
  1413. /* module instance type */
  1414. module_inst->module_type = Wasm_Module_Bytecode;
  1415. /* Initialize the thread related data */
  1416. if (stack_size == 0)
  1417. stack_size = DEFAULT_WASM_STACK_SIZE;
  1418. #if WASM_ENABLE_SPEC_TEST != 0
  1419. if (stack_size < 128 * 1024)
  1420. stack_size = 128 * 1024;
  1421. #endif
  1422. module_inst->default_wasm_stack_size = stack_size;
  1423. if (module->malloc_function != (uint32)-1) {
  1424. module_inst->malloc_function =
  1425. &module_inst->functions[module->malloc_function];
  1426. }
  1427. if (module->free_function != (uint32)-1) {
  1428. module_inst->free_function =
  1429. &module_inst->functions[module->free_function];
  1430. }
  1431. if (module->retain_function != (uint32)-1) {
  1432. module_inst->retain_function =
  1433. &module_inst->functions[module->retain_function];
  1434. }
  1435. #if WASM_ENABLE_LIBC_WASI != 0
  1436. /* The sub-instance will get the wasi_ctx from main-instance */
  1437. if (!is_sub_inst) {
  1438. if (!wasm_runtime_init_wasi(
  1439. (WASMModuleInstanceCommon *)module_inst,
  1440. module->wasi_args.dir_list, module->wasi_args.dir_count,
  1441. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  1442. module->wasi_args.env, module->wasi_args.env_count,
  1443. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  1444. module->wasi_args.argv, module->wasi_args.argc,
  1445. module->wasi_args.stdio[0], module->wasi_args.stdio[1],
  1446. module->wasi_args.stdio[2], error_buf, error_buf_size)) {
  1447. goto fail;
  1448. }
  1449. }
  1450. #endif
  1451. if (module->start_function != (uint32)-1) {
  1452. /* TODO: fix start function can be import function issue */
  1453. if (module->start_function >= module->import_function_count)
  1454. module_inst->start_function =
  1455. &module_inst->functions[module->start_function];
  1456. }
  1457. /* Execute __post_instantiate function */
  1458. if (!execute_post_inst_function(module_inst)
  1459. || !execute_start_function(module_inst)) {
  1460. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  1461. goto fail;
  1462. }
  1463. #if WASM_ENABLE_BULK_MEMORY != 0
  1464. #if WASM_ENABLE_LIBC_WASI != 0
  1465. if (!module->import_wasi_api) {
  1466. #endif
  1467. /* Only execute the memory init function for main instance because
  1468. the data segments will be dropped once initialized.
  1469. */
  1470. if (!is_sub_inst) {
  1471. if (!execute_memory_init_function(module_inst)) {
  1472. set_error_buf(error_buf, error_buf_size,
  1473. module_inst->cur_exception);
  1474. goto fail;
  1475. }
  1476. }
  1477. #if WASM_ENABLE_LIBC_WASI != 0
  1478. }
  1479. #endif
  1480. #endif
  1481. #if WASM_ENABLE_MEMORY_TRACING != 0
  1482. wasm_runtime_dump_module_inst_mem_consumption(
  1483. (WASMModuleInstanceCommon *)module_inst);
  1484. #endif
  1485. (void)global_data_end;
  1486. return module_inst;
  1487. fail:
  1488. wasm_deinstantiate(module_inst, false);
  1489. return NULL;
  1490. }
  1491. void
  1492. wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst)
  1493. {
  1494. if (!module_inst)
  1495. return;
  1496. #if WASM_ENABLE_MULTI_MODULE != 0
  1497. sub_module_deinstantiate(module_inst);
  1498. #endif
  1499. #if WASM_ENABLE_LIBC_WASI != 0
  1500. /* Destroy wasi resource before freeing app heap, since some fields of
  1501. wasi contex are allocated from app heap, and if app heap is freed,
  1502. these fields will be set to NULL, we cannot free their internal data
  1503. which may allocated from global heap. */
  1504. /* Only destroy wasi ctx in the main module instance */
  1505. if (!is_sub_inst)
  1506. wasm_runtime_destroy_wasi((WASMModuleInstanceCommon *)module_inst);
  1507. #endif
  1508. if (module_inst->memory_count > 0)
  1509. memories_deinstantiate(module_inst, module_inst->memories,
  1510. module_inst->memory_count);
  1511. if (module_inst->import_func_ptrs) {
  1512. wasm_runtime_free(module_inst->import_func_ptrs);
  1513. }
  1514. tables_deinstantiate(module_inst->tables, module_inst->table_count);
  1515. functions_deinstantiate(module_inst->functions,
  1516. module_inst->function_count);
  1517. globals_deinstantiate(module_inst->globals);
  1518. export_functions_deinstantiate(module_inst->export_functions);
  1519. #if WASM_ENABLE_MULTI_MODULE != 0
  1520. export_globals_deinstantiate(module_inst->export_globals);
  1521. #endif
  1522. if (module_inst->global_data)
  1523. wasm_runtime_free(module_inst->global_data);
  1524. #if WASM_ENABLE_REF_TYPES != 0
  1525. wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst);
  1526. #endif
  1527. if (module_inst->exec_env_singleton)
  1528. wasm_exec_env_destroy(module_inst->exec_env_singleton);
  1529. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1530. if (module_inst->frames) {
  1531. bh_vector_destroy(module_inst->frames);
  1532. wasm_runtime_free(module_inst->frames);
  1533. module_inst->frames = NULL;
  1534. }
  1535. #endif
  1536. #if WASM_ENABLE_DEBUG_INTERP != 0
  1537. if (!is_sub_inst) {
  1538. os_mutex_lock(&module_inst->module->ref_count_lock);
  1539. module_inst->module->ref_count--;
  1540. os_mutex_unlock(&module_inst->module->ref_count_lock);
  1541. }
  1542. #endif
  1543. wasm_runtime_free(module_inst);
  1544. }
  1545. WASMFunctionInstance *
  1546. wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name,
  1547. const char *signature)
  1548. {
  1549. uint32 i;
  1550. for (i = 0; i < module_inst->export_func_count; i++)
  1551. if (!strcmp(module_inst->export_functions[i].name, name))
  1552. return module_inst->export_functions[i].function;
  1553. (void)signature;
  1554. return NULL;
  1555. }
  1556. #if WASM_ENABLE_MULTI_MODULE != 0
  1557. WASMGlobalInstance *
  1558. wasm_lookup_global(const WASMModuleInstance *module_inst, const char *name)
  1559. {
  1560. uint32 i;
  1561. for (i = 0; i < module_inst->export_glob_count; i++)
  1562. if (!strcmp(module_inst->export_globals[i].name, name))
  1563. return module_inst->export_globals[i].global;
  1564. return NULL;
  1565. }
  1566. WASMMemoryInstance *
  1567. wasm_lookup_memory(const WASMModuleInstance *module_inst, const char *name)
  1568. {
  1569. /**
  1570. * using a strong assumption that one module instance only has
  1571. * one memory instance
  1572. */
  1573. (void)module_inst->export_memories;
  1574. return module_inst->memories[0];
  1575. }
  1576. WASMTableInstance *
  1577. wasm_lookup_table(const WASMModuleInstance *module_inst, const char *name)
  1578. {
  1579. /**
  1580. * using a strong assumption that one module instance only has
  1581. * one table instance
  1582. */
  1583. (void)module_inst->export_tables;
  1584. return module_inst->tables[0];
  1585. }
  1586. #endif
  1587. static bool
  1588. clear_wasi_proc_exit_exception(WASMModuleInstance *module_inst)
  1589. {
  1590. #if WASM_ENABLE_LIBC_WASI != 0
  1591. const char *exception = wasm_get_exception(module_inst);
  1592. if (exception && !strcmp(exception, "Exception: wasi proc exit")) {
  1593. /* The "wasi proc exit" exception is thrown by native lib to
  1594. let wasm app exit, which is a normal behavior, we clear
  1595. the exception here. */
  1596. wasm_set_exception(module_inst, NULL);
  1597. return true;
  1598. }
  1599. return false;
  1600. #else
  1601. return false;
  1602. #endif
  1603. }
  1604. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1605. #ifndef BH_PLATFORM_WINDOWS
  1606. void
  1607. wasm_signal_handler(WASMSignalInfo *sig_info)
  1608. {
  1609. WASMExecEnv *exec_env_tls = sig_info->exec_env_tls;
  1610. void *sig_addr = sig_info->sig_addr;
  1611. WASMModuleInstance *module_inst;
  1612. WASMMemoryInstance *memory_inst;
  1613. WASMJmpBuf *jmpbuf_node;
  1614. uint8 *mapped_mem_start_addr = NULL;
  1615. uint8 *mapped_mem_end_addr = NULL;
  1616. uint8 *stack_min_addr;
  1617. uint32 page_size;
  1618. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  1619. /* Check whether current thread is running wasm function */
  1620. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  1621. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  1622. /* Get mapped mem info of current instance */
  1623. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  1624. /* Get the default memory instance */
  1625. memory_inst = module_inst->default_memory;
  1626. if (memory_inst) {
  1627. mapped_mem_start_addr = (uint8 *)memory_inst->memory_data;
  1628. mapped_mem_end_addr =
  1629. (uint8 *)memory_inst->memory_data + 8 * (uint64)BH_GB;
  1630. }
  1631. /* Get stack info of current thread */
  1632. page_size = os_getpagesize();
  1633. stack_min_addr = os_thread_get_stack_boundary();
  1634. if (memory_inst
  1635. && (mapped_mem_start_addr <= (uint8 *)sig_addr
  1636. && (uint8 *)sig_addr < mapped_mem_end_addr)) {
  1637. /* The address which causes segmentation fault is inside
  1638. the memory instance's guard regions */
  1639. wasm_set_exception(module_inst, "out of bounds memory access");
  1640. os_longjmp(jmpbuf_node->jmpbuf, 1);
  1641. }
  1642. else if (stack_min_addr - page_size <= (uint8 *)sig_addr
  1643. && (uint8 *)sig_addr
  1644. < stack_min_addr + page_size * guard_page_count) {
  1645. /* The address which causes segmentation fault is inside
  1646. native thread's guard page */
  1647. wasm_set_exception(module_inst, "native stack overflow");
  1648. os_longjmp(jmpbuf_node->jmpbuf, 1);
  1649. }
  1650. }
  1651. }
  1652. #else /* else of BH_PLATFORM_WINDOWS */
  1653. LONG
  1654. wasm_exception_handler(WASMSignalInfo *sig_info)
  1655. {
  1656. WASMExecEnv *exec_env_tls = sig_info->exec_env_tls;
  1657. EXCEPTION_POINTERS *exce_info = sig_info->exce_info;
  1658. PEXCEPTION_RECORD ExceptionRecord = exce_info->ExceptionRecord;
  1659. uint8 *sig_addr = (uint8 *)ExceptionRecord->ExceptionInformation[1];
  1660. WASMModuleInstance *module_inst;
  1661. WASMMemoryInstance *memory_inst;
  1662. WASMJmpBuf *jmpbuf_node;
  1663. uint8 *mapped_mem_start_addr = NULL;
  1664. uint8 *mapped_mem_end_addr = NULL;
  1665. uint32 page_size = os_getpagesize();
  1666. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  1667. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  1668. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  1669. if (ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
  1670. /* Get the default memory instance */
  1671. memory_inst = module_inst->default_memory;
  1672. if (memory_inst) {
  1673. mapped_mem_start_addr = (uint8 *)memory_inst->memory_data;
  1674. mapped_mem_end_addr =
  1675. (uint8 *)memory_inst->memory_data + 8 * (uint64)BH_GB;
  1676. if (mapped_mem_start_addr <= (uint8 *)sig_addr
  1677. && (uint8 *)sig_addr < mapped_mem_end_addr) {
  1678. /* The address which causes segmentation fault is inside
  1679. the memory instance's guard regions.
  1680. Set exception and let the wasm func continue to run, when
  1681. the wasm func returns, the caller will check whether the
  1682. exception is thrown and return to runtime. */
  1683. wasm_set_exception(module_inst,
  1684. "out of bounds memory access");
  1685. /* Skip current instruction */
  1686. return EXCEPTION_CONTINUE_SEARCH;
  1687. }
  1688. }
  1689. }
  1690. else if (ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
  1691. /* Set stack overflow exception and let the wasm func continue
  1692. to run, when the wasm func returns, the caller will check
  1693. whether the exception is thrown and return to runtime, and
  1694. the damaged stack will be recovered by _resetstkoflw(). */
  1695. wasm_set_exception(module_inst, "native stack overflow");
  1696. return EXCEPTION_CONTINUE_SEARCH;
  1697. }
  1698. }
  1699. os_printf("Unhandled exception thrown: exception code: 0x%lx, "
  1700. "exception address: %p, exception information: %p\n",
  1701. ExceptionRecord->ExceptionCode, ExceptionRecord->ExceptionAddress,
  1702. sig_addr);
  1703. return EXCEPTION_CONTINUE_SEARCH;
  1704. }
  1705. #endif /* end of BH_PLATFORM_WINDOWS */
  1706. static void
  1707. call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst,
  1708. WASMExecEnv *exec_env,
  1709. WASMFunctionInstance *function, unsigned argc,
  1710. uint32 argv[])
  1711. {
  1712. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1713. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  1714. uint32 page_size = os_getpagesize();
  1715. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  1716. #ifdef BH_PLATFORM_WINDOWS
  1717. const char *exce;
  1718. int result;
  1719. #endif
  1720. bool ret = true;
  1721. /* Check native stack overflow firstly to ensure we have enough
  1722. native stack to run the following codes before actually calling
  1723. the aot function in invokeNative function. */
  1724. if ((uint8 *)&exec_env_tls < exec_env->native_stack_boundary
  1725. + page_size * (guard_page_count + 1)) {
  1726. wasm_set_exception(module_inst, "native stack overflow");
  1727. return;
  1728. }
  1729. if (exec_env_tls && (exec_env_tls != exec_env)) {
  1730. wasm_set_exception(module_inst, "invalid exec env");
  1731. return;
  1732. }
  1733. if (!os_thread_signal_inited()) {
  1734. wasm_set_exception(module_inst, "thread signal env not inited");
  1735. return;
  1736. }
  1737. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  1738. wasm_runtime_set_exec_env_tls(exec_env);
  1739. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  1740. #ifndef BH_PLATFORM_WINDOWS
  1741. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  1742. #else
  1743. __try {
  1744. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  1745. } __except (wasm_get_exception(module_inst)
  1746. ? EXCEPTION_EXECUTE_HANDLER
  1747. : EXCEPTION_CONTINUE_SEARCH) {
  1748. /* exception was thrown in wasm_exception_handler */
  1749. ret = false;
  1750. }
  1751. if ((exce = wasm_get_exception(module_inst))
  1752. && strstr(exce, "native stack overflow")) {
  1753. /* After a stack overflow, the stack was left
  1754. in a damaged state, let the CRT repair it */
  1755. result = _resetstkoflw();
  1756. bh_assert(result != 0);
  1757. }
  1758. #endif
  1759. }
  1760. else {
  1761. /* Exception has been set in signal handler before calling longjmp */
  1762. ret = false;
  1763. }
  1764. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  1765. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  1766. if (!exec_env->jmpbuf_stack_top) {
  1767. wasm_runtime_set_exec_env_tls(NULL);
  1768. }
  1769. if (!ret) {
  1770. os_sigreturn();
  1771. os_signal_unmask();
  1772. }
  1773. (void)jmpbuf_node_pop;
  1774. }
  1775. #define interp_call_wasm call_wasm_with_hw_bound_check
  1776. #else
  1777. #define interp_call_wasm wasm_interp_call_wasm
  1778. #endif
  1779. bool
  1780. wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function,
  1781. unsigned argc, uint32 argv[])
  1782. {
  1783. WASMModuleInstance *module_inst =
  1784. (WASMModuleInstance *)exec_env->module_inst;
  1785. /* set thread handle and stack boundary */
  1786. wasm_exec_env_set_thread_info(exec_env);
  1787. interp_call_wasm(module_inst, exec_env, function, argc, argv);
  1788. (void)clear_wasi_proc_exit_exception(module_inst);
  1789. return !wasm_get_exception(module_inst) ? true : false;
  1790. }
  1791. bool
  1792. wasm_create_exec_env_and_call_function(WASMModuleInstance *module_inst,
  1793. WASMFunctionInstance *func,
  1794. unsigned argc, uint32 argv[],
  1795. bool enable_debug)
  1796. {
  1797. WASMExecEnv *exec_env, *existing_exec_env = NULL;
  1798. bool ret;
  1799. #if defined(OS_ENABLE_HW_BOUND_CHECK)
  1800. existing_exec_env = exec_env = wasm_runtime_get_exec_env_tls();
  1801. #elif WASM_ENABLE_THREAD_MGR != 0
  1802. existing_exec_env = exec_env =
  1803. wasm_clusters_search_exec_env((WASMModuleInstanceCommon *)module_inst);
  1804. #endif
  1805. if (!existing_exec_env) {
  1806. if (!(exec_env =
  1807. wasm_exec_env_create((WASMModuleInstanceCommon *)module_inst,
  1808. module_inst->default_wasm_stack_size))) {
  1809. wasm_set_exception(module_inst, "allocate memory failed");
  1810. return false;
  1811. }
  1812. #if WASM_ENABLE_THREAD_MGR != 0
  1813. #if WASM_ENABLE_DEBUG_INTERP != 0
  1814. if (enable_debug) {
  1815. wasm_runtime_start_debug_instance(exec_env);
  1816. }
  1817. #endif
  1818. #endif
  1819. }
  1820. ret = wasm_call_function(exec_env, func, argc, argv);
  1821. /* don't destroy the exec_env if it isn't created in this function */
  1822. if (!existing_exec_env)
  1823. wasm_exec_env_destroy(exec_env);
  1824. return ret;
  1825. }
  1826. bool
  1827. wasm_create_exec_env_singleton(WASMModuleInstance *module_inst)
  1828. {
  1829. WASMExecEnv *exec_env = NULL;
  1830. if (module_inst->exec_env_singleton) {
  1831. return true;
  1832. }
  1833. exec_env = wasm_exec_env_create((WASMModuleInstanceCommon *)module_inst,
  1834. module_inst->default_wasm_stack_size);
  1835. if (exec_env)
  1836. module_inst->exec_env_singleton = exec_env;
  1837. return exec_env ? true : false;
  1838. }
  1839. void
  1840. wasm_set_exception(WASMModuleInstance *module_inst, const char *exception)
  1841. {
  1842. if (exception)
  1843. snprintf(module_inst->cur_exception, sizeof(module_inst->cur_exception),
  1844. "Exception: %s", exception);
  1845. else
  1846. module_inst->cur_exception[0] = '\0';
  1847. }
  1848. const char *
  1849. wasm_get_exception(WASMModuleInstance *module_inst)
  1850. {
  1851. if (module_inst->cur_exception[0] == '\0')
  1852. return NULL;
  1853. else
  1854. return module_inst->cur_exception;
  1855. }
  1856. #if WASM_ENABLE_PERF_PROFILING != 0
  1857. void
  1858. wasm_dump_perf_profiling(const WASMModuleInstance *module_inst)
  1859. {
  1860. WASMExportFuncInstance *export_func;
  1861. WASMFunctionInstance *func_inst;
  1862. char *func_name;
  1863. uint32 i, j;
  1864. os_printf("Performance profiler data:\n");
  1865. for (i = 0; i < module_inst->function_count; i++) {
  1866. func_inst = module_inst->functions + i;
  1867. if (func_inst->is_import_func) {
  1868. func_name = func_inst->u.func_import->field_name;
  1869. }
  1870. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  1871. else if (func_inst->u.func->field_name) {
  1872. func_name = func_inst->u.func->field_name;
  1873. }
  1874. #endif
  1875. else {
  1876. func_name = NULL;
  1877. for (j = 0; j < module_inst->export_func_count; j++) {
  1878. export_func = module_inst->export_functions + j;
  1879. if (export_func->function == func_inst) {
  1880. func_name = export_func->name;
  1881. break;
  1882. }
  1883. }
  1884. }
  1885. if (func_name)
  1886. os_printf(" func %s, execution time: %.3f ms, execution count: %d "
  1887. "times\n",
  1888. func_name,
  1889. module_inst->functions[i].total_exec_time / 1000.0f,
  1890. module_inst->functions[i].total_exec_cnt);
  1891. else
  1892. os_printf(" func %d, execution time: %.3f ms, execution count: %d "
  1893. "times\n",
  1894. i, module_inst->functions[i].total_exec_time / 1000.0f,
  1895. module_inst->functions[i].total_exec_cnt);
  1896. }
  1897. }
  1898. #endif
  1899. uint32
  1900. wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size,
  1901. void **p_native_addr)
  1902. {
  1903. WASMMemoryInstance *memory = module_inst->default_memory;
  1904. uint8 *addr = NULL;
  1905. uint32 offset = 0;
  1906. if (!memory) {
  1907. wasm_set_exception(module_inst, "uninitialized memory");
  1908. return 0;
  1909. }
  1910. if (memory->heap_handle) {
  1911. addr = mem_allocator_malloc(memory->heap_handle, size);
  1912. }
  1913. else if (module_inst->malloc_function && module_inst->free_function) {
  1914. #if WASM_ENABLE_DEBUG_INTERP != 0
  1915. /* TODO: obviously, we can not create debug instance for
  1916. * module malloc here, so, just disable the engine here,
  1917. * it is strange, but we now are lack of ways to indicate
  1918. * which calls should not be debugged. And we have other
  1919. * execute_xxx_function may need to be taken care of
  1920. */
  1921. bool active = wasm_debug_get_engine_active();
  1922. wasm_debug_set_engine_active(false);
  1923. #endif
  1924. if (!execute_malloc_function(module_inst, module_inst->malloc_function,
  1925. module_inst->retain_function, size,
  1926. &offset)) {
  1927. #if WASM_ENABLE_DEBUG_INTERP != 0
  1928. wasm_debug_set_engine_active(active);
  1929. #endif
  1930. return 0;
  1931. }
  1932. #if WASM_ENABLE_DEBUG_INTERP != 0
  1933. wasm_debug_set_engine_active(active);
  1934. #endif
  1935. /* If we use app's malloc function,
  1936. the default memory may be changed while memory growing */
  1937. memory = module_inst->default_memory;
  1938. addr = offset ? memory->memory_data + offset : NULL;
  1939. }
  1940. if (!addr) {
  1941. if (memory->heap_handle
  1942. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  1943. wasm_runtime_show_app_heap_corrupted_prompt();
  1944. wasm_set_exception(module_inst, "app heap corrupted");
  1945. }
  1946. else {
  1947. LOG_WARNING("warning: allocate %u bytes memory failed", size);
  1948. }
  1949. return 0;
  1950. }
  1951. if (p_native_addr)
  1952. *p_native_addr = addr;
  1953. return (uint32)(addr - memory->memory_data);
  1954. }
  1955. uint32
  1956. wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size,
  1957. void **p_native_addr)
  1958. {
  1959. WASMMemoryInstance *memory = module_inst->default_memory;
  1960. uint8 *addr = NULL;
  1961. if (!memory) {
  1962. wasm_set_exception(module_inst, "uninitialized memory");
  1963. return 0;
  1964. }
  1965. if (memory->heap_handle) {
  1966. addr = mem_allocator_realloc(
  1967. memory->heap_handle, ptr ? memory->memory_data + ptr : NULL, size);
  1968. }
  1969. /* Only support realloc in WAMR's app heap */
  1970. if (!addr) {
  1971. if (memory->heap_handle
  1972. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  1973. wasm_set_exception(module_inst, "app heap corrupted");
  1974. }
  1975. else {
  1976. wasm_set_exception(module_inst, "out of memory");
  1977. }
  1978. return 0;
  1979. }
  1980. if (p_native_addr)
  1981. *p_native_addr = addr;
  1982. return (uint32)(addr - memory->memory_data);
  1983. }
  1984. void
  1985. wasm_module_free(WASMModuleInstance *module_inst, uint32 ptr)
  1986. {
  1987. if (ptr) {
  1988. WASMMemoryInstance *memory = module_inst->default_memory;
  1989. uint8 *addr;
  1990. if (!memory) {
  1991. return;
  1992. }
  1993. addr = memory->memory_data + ptr;
  1994. if (memory->heap_handle && memory->heap_data <= addr
  1995. && addr < memory->heap_data_end) {
  1996. mem_allocator_free(memory->heap_handle, addr);
  1997. }
  1998. else if (module_inst->malloc_function && module_inst->free_function
  1999. && memory->memory_data <= addr
  2000. && addr < memory->memory_data_end) {
  2001. #if WASM_ENABLE_DEBUG_INTERP != 0
  2002. /*TODO: obviously, we can not create debug instance for module
  2003. malloc here, so, just disable the engine here, it is strange. the
  2004. wasm's call should be marshed to its own thread */
  2005. bool active = wasm_debug_get_engine_active();
  2006. wasm_debug_set_engine_active(false);
  2007. #endif
  2008. execute_free_function(module_inst, module_inst->free_function, ptr);
  2009. #if WASM_ENABLE_DEBUG_INTERP != 0
  2010. wasm_debug_set_engine_active(active);
  2011. #endif
  2012. }
  2013. }
  2014. }
  2015. uint32
  2016. wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src,
  2017. uint32 size)
  2018. {
  2019. char *buffer;
  2020. uint32 buffer_offset =
  2021. wasm_module_malloc(module_inst, size, (void **)&buffer);
  2022. if (buffer_offset != 0) {
  2023. buffer = wasm_addr_app_to_native(module_inst, buffer_offset);
  2024. bh_memcpy_s(buffer, size, src, size);
  2025. }
  2026. return buffer_offset;
  2027. }
  2028. bool
  2029. wasm_validate_app_addr(WASMModuleInstance *module_inst, uint32 app_offset,
  2030. uint32 size)
  2031. {
  2032. WASMMemoryInstance *memory = module_inst->default_memory;
  2033. uint32 memory_data_size;
  2034. if (!memory) {
  2035. goto fail;
  2036. }
  2037. memory_data_size = memory->num_bytes_per_page * memory->cur_page_count;
  2038. /* integer overflow check */
  2039. if (app_offset > UINT32_MAX - size) {
  2040. goto fail;
  2041. }
  2042. if (app_offset + size <= memory_data_size) {
  2043. return true;
  2044. }
  2045. fail:
  2046. wasm_set_exception(module_inst, "out of bounds memory access");
  2047. return false;
  2048. }
  2049. bool
  2050. wasm_validate_native_addr(WASMModuleInstance *module_inst, void *native_ptr,
  2051. uint32 size)
  2052. {
  2053. WASMMemoryInstance *memory = module_inst->default_memory;
  2054. uint8 *addr = (uint8 *)native_ptr;
  2055. if (!memory) {
  2056. goto fail;
  2057. }
  2058. /* integer overflow check */
  2059. if ((uintptr_t)addr > UINTPTR_MAX - size) {
  2060. goto fail;
  2061. }
  2062. if (memory->memory_data <= addr && addr + size <= memory->memory_data_end) {
  2063. return true;
  2064. }
  2065. fail:
  2066. wasm_set_exception(module_inst, "out of bounds memory access");
  2067. return false;
  2068. }
  2069. void *
  2070. wasm_addr_app_to_native(WASMModuleInstance *module_inst, uint32 app_offset)
  2071. {
  2072. WASMMemoryInstance *memory = module_inst->default_memory;
  2073. uint8 *addr;
  2074. if (!memory)
  2075. return NULL;
  2076. addr = memory->memory_data + app_offset;
  2077. if (memory->memory_data <= addr && addr < memory->memory_data_end)
  2078. return addr;
  2079. return NULL;
  2080. }
  2081. uint32
  2082. wasm_addr_native_to_app(WASMModuleInstance *module_inst, void *native_ptr)
  2083. {
  2084. WASMMemoryInstance *memory = module_inst->default_memory;
  2085. uint8 *addr = (uint8 *)native_ptr;
  2086. if (!memory)
  2087. return 0;
  2088. if (memory->memory_data <= addr && addr < memory->memory_data_end)
  2089. return (uint32)(addr - memory->memory_data);
  2090. return 0;
  2091. }
  2092. bool
  2093. wasm_get_app_addr_range(WASMModuleInstance *module_inst, uint32 app_offset,
  2094. uint32 *p_app_start_offset, uint32 *p_app_end_offset)
  2095. {
  2096. WASMMemoryInstance *memory = module_inst->default_memory;
  2097. uint32 memory_data_size;
  2098. if (!memory)
  2099. return false;
  2100. memory_data_size = memory->num_bytes_per_page * memory->cur_page_count;
  2101. if (app_offset < memory_data_size) {
  2102. if (p_app_start_offset)
  2103. *p_app_start_offset = 0;
  2104. if (p_app_end_offset)
  2105. *p_app_end_offset = memory_data_size;
  2106. return true;
  2107. }
  2108. return false;
  2109. }
  2110. bool
  2111. wasm_get_native_addr_range(WASMModuleInstance *module_inst, uint8 *native_ptr,
  2112. uint8 **p_native_start_addr,
  2113. uint8 **p_native_end_addr)
  2114. {
  2115. WASMMemoryInstance *memory = module_inst->default_memory;
  2116. uint8 *addr = (uint8 *)native_ptr;
  2117. if (!memory)
  2118. return false;
  2119. if (memory->memory_data <= addr && addr < memory->memory_data_end) {
  2120. if (p_native_start_addr)
  2121. *p_native_start_addr = memory->memory_data;
  2122. if (p_native_end_addr)
  2123. *p_native_end_addr = memory->memory_data_end;
  2124. return true;
  2125. }
  2126. return false;
  2127. }
  2128. #ifndef OS_ENABLE_HW_BOUND_CHECK
  2129. bool
  2130. wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count)
  2131. {
  2132. WASMMemoryInstance *memory = module->default_memory;
  2133. uint8 *new_memory_data, *memory_data, *heap_data_old;
  2134. uint32 heap_size, total_size_old, total_page_count;
  2135. uint64 total_size;
  2136. bool ret = true;
  2137. if (!memory)
  2138. return false;
  2139. memory_data = memory->memory_data;
  2140. heap_size = (uint32)(memory->heap_data_end - memory->heap_data);
  2141. total_size_old = (uint32)(memory->memory_data_end - memory_data);
  2142. total_page_count = inc_page_count + memory->cur_page_count;
  2143. total_size = memory->num_bytes_per_page * (uint64)total_page_count;
  2144. heap_data_old = memory->heap_data;
  2145. if (inc_page_count <= 0)
  2146. /* No need to enlarge memory */
  2147. return true;
  2148. if (total_page_count < memory->cur_page_count /* integer overflow */
  2149. || total_page_count > memory->max_page_count) {
  2150. return false;
  2151. }
  2152. if (total_size >= UINT32_MAX) {
  2153. return false;
  2154. }
  2155. #if WASM_ENABLE_SHARED_MEMORY != 0
  2156. if (memory->is_shared) {
  2157. /* For shared memory, we have reserved the maximum spaces during
  2158. instantiate, only change the cur_page_count here */
  2159. memory->cur_page_count = total_page_count;
  2160. return true;
  2161. }
  2162. #endif
  2163. if (heap_size > 0) {
  2164. if (mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  2165. wasm_runtime_show_app_heap_corrupted_prompt();
  2166. return false;
  2167. }
  2168. }
  2169. if (!(new_memory_data =
  2170. wasm_runtime_realloc(memory_data, (uint32)total_size))) {
  2171. if (!(new_memory_data = wasm_runtime_malloc((uint32)total_size))) {
  2172. return false;
  2173. }
  2174. if (memory_data) {
  2175. bh_memcpy_s(new_memory_data, (uint32)total_size, memory_data,
  2176. total_size_old);
  2177. wasm_runtime_free(memory_data);
  2178. }
  2179. }
  2180. memset(new_memory_data + total_size_old, 0,
  2181. (uint32)total_size - total_size_old);
  2182. if (heap_size > 0) {
  2183. if (mem_allocator_migrate(memory->heap_handle,
  2184. (char *)heap_data_old
  2185. + (new_memory_data - memory_data),
  2186. heap_size)
  2187. != 0) {
  2188. /* Don't return here as memory->memory_data is obsolete and
  2189. must be updated to be correctly used later. */
  2190. ret = false;
  2191. }
  2192. }
  2193. memory->memory_data = new_memory_data;
  2194. memory->cur_page_count = total_page_count;
  2195. memory->heap_data = new_memory_data + (heap_data_old - memory_data);
  2196. memory->heap_data_end = memory->heap_data + heap_size;
  2197. memory->memory_data_end =
  2198. memory->memory_data + memory->num_bytes_per_page * total_page_count;
  2199. #if WASM_ENABLE_FAST_JIT != 0
  2200. #if UINTPTR_MAX == UINT64_MAX
  2201. memory->mem_bound_check_1byte = total_size - 1;
  2202. memory->mem_bound_check_2bytes = total_size - 2;
  2203. memory->mem_bound_check_4bytes = total_size - 4;
  2204. memory->mem_bound_check_8bytes = total_size - 8;
  2205. memory->mem_bound_check_16bytes = total_size - 16;
  2206. #else
  2207. memory->mem_bound_check_1byte = (uint32)total_size - 1;
  2208. memory->mem_bound_check_2bytes = (uint32)total_size - 2;
  2209. memory->mem_bound_check_4bytes = (uint32)total_size - 4;
  2210. memory->mem_bound_check_8bytes = (uint32)total_size - 8;
  2211. memory->mem_bound_check_16bytes = (uint32)total_size - 16;
  2212. #endif
  2213. #endif
  2214. return ret;
  2215. }
  2216. #else
  2217. bool
  2218. wasm_enlarge_memory(WASMModuleInstance *module, uint32 inc_page_count)
  2219. {
  2220. WASMMemoryInstance *memory = module->default_memory;
  2221. uint32 num_bytes_per_page, total_page_count;
  2222. if (!memory)
  2223. return false;
  2224. total_page_count = inc_page_count + memory->cur_page_count;
  2225. if (inc_page_count <= 0)
  2226. /* No need to enlarge memory */
  2227. return true;
  2228. if (total_page_count < memory->cur_page_count /* integer overflow */
  2229. || total_page_count > memory->max_page_count) {
  2230. return false;
  2231. }
  2232. num_bytes_per_page = memory->num_bytes_per_page;
  2233. #ifdef BH_PLATFORM_WINDOWS
  2234. if (!os_mem_commit(memory->memory_data_end,
  2235. num_bytes_per_page * inc_page_count,
  2236. MMAP_PROT_READ | MMAP_PROT_WRITE)) {
  2237. return false;
  2238. }
  2239. #endif
  2240. if (os_mprotect(memory->memory_data_end,
  2241. num_bytes_per_page * inc_page_count,
  2242. MMAP_PROT_READ | MMAP_PROT_WRITE)
  2243. != 0) {
  2244. #ifdef BH_PLATFORM_WINDOWS
  2245. os_mem_decommit(memory->memory_data_end,
  2246. num_bytes_per_page * inc_page_count);
  2247. #endif
  2248. return false;
  2249. }
  2250. /* The increased pages are filled with zero by the OS when os_mmap,
  2251. no need to memset it again here */
  2252. memory->cur_page_count = total_page_count;
  2253. memory->memory_data_end =
  2254. memory->memory_data + num_bytes_per_page * total_page_count;
  2255. return true;
  2256. }
  2257. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  2258. #if WASM_ENABLE_REF_TYPES != 0
  2259. bool
  2260. wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx,
  2261. uint32 inc_entries, uint32 init_val)
  2262. {
  2263. uint32 entry_count, *new_table_data_start, i;
  2264. WASMTableInstance *table_inst;
  2265. if (!inc_entries) {
  2266. return true;
  2267. }
  2268. bh_assert(table_idx < module_inst->table_count);
  2269. table_inst = wasm_get_table_inst(module_inst, table_idx);
  2270. if (!table_inst) {
  2271. return false;
  2272. }
  2273. if (inc_entries > UINT32_MAX - table_inst->cur_size) {
  2274. return false;
  2275. }
  2276. entry_count = table_inst->cur_size + inc_entries;
  2277. if (entry_count > table_inst->max_size) {
  2278. return false;
  2279. }
  2280. /* fill in */
  2281. new_table_data_start =
  2282. (uint32 *)((uint8 *)table_inst + offsetof(WASMTableInstance, base_addr))
  2283. + table_inst->cur_size;
  2284. for (i = 0; i < inc_entries; ++i) {
  2285. new_table_data_start[i] = init_val;
  2286. }
  2287. table_inst->cur_size = entry_count;
  2288. return true;
  2289. }
  2290. #endif /* WASM_ENABLE_REF_TYPES != 0 */
  2291. static bool
  2292. call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2293. uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx)
  2294. {
  2295. WASMModuleInstance *module_inst = NULL;
  2296. WASMTableInstance *table_inst = NULL;
  2297. uint32 func_idx = 0;
  2298. WASMFunctionInstance *func_inst = NULL;
  2299. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  2300. bh_assert(module_inst);
  2301. table_inst = module_inst->tables[tbl_idx];
  2302. if (!table_inst) {
  2303. wasm_set_exception(module_inst, "unknown table");
  2304. goto got_exception;
  2305. }
  2306. if (elem_idx >= table_inst->cur_size) {
  2307. wasm_set_exception(module_inst, "undefined element");
  2308. goto got_exception;
  2309. }
  2310. /**
  2311. * please be aware that table_inst->base_addr may point
  2312. * to another module's table
  2313. **/
  2314. func_idx = ((uint32 *)table_inst->base_addr)[elem_idx];
  2315. if (func_idx == NULL_REF) {
  2316. wasm_set_exception(module_inst, "uninitialized element");
  2317. goto got_exception;
  2318. }
  2319. /**
  2320. * we insist to call functions owned by the module itself
  2321. **/
  2322. if (func_idx >= module_inst->function_count) {
  2323. wasm_set_exception(module_inst, "unknown function");
  2324. goto got_exception;
  2325. }
  2326. func_inst = module_inst->functions + func_idx;
  2327. if (check_type_idx) {
  2328. WASMType *cur_type = module_inst->module->types[type_idx];
  2329. WASMType *cur_func_type;
  2330. if (func_inst->is_import_func)
  2331. cur_func_type = func_inst->u.func_import->func_type;
  2332. else
  2333. cur_func_type = func_inst->u.func->func_type;
  2334. if (!wasm_type_equal(cur_type, cur_func_type)) {
  2335. wasm_set_exception(module_inst, "indirect call type mismatch");
  2336. goto got_exception;
  2337. }
  2338. }
  2339. interp_call_wasm(module_inst, exec_env, func_inst, argc, argv);
  2340. (void)clear_wasi_proc_exit_exception(module_inst);
  2341. return !wasm_get_exception(module_inst) ? true : false;
  2342. got_exception:
  2343. return false;
  2344. }
  2345. bool
  2346. wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2347. uint32 argc, uint32 argv[])
  2348. {
  2349. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  2350. }
  2351. #if WASM_ENABLE_FAST_JIT != 0
  2352. bool
  2353. jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2354. uint32 type_idx, uint32 argc, uint32 argv[])
  2355. {
  2356. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, true,
  2357. type_idx);
  2358. }
  2359. #endif
  2360. #if WASM_ENABLE_THREAD_MGR != 0
  2361. bool
  2362. wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size)
  2363. {
  2364. WASMModuleInstance *module_inst =
  2365. (WASMModuleInstance *)exec_env->module_inst;
  2366. uint32 stack_top_idx = module_inst->module->aux_stack_top_global_index;
  2367. uint32 data_end = module_inst->module->aux_data_end;
  2368. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2369. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  2370. /* Check the aux stack space, currently we don't allocate space in heap */
  2371. if ((is_stack_before_data && (size > start_offset))
  2372. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  2373. return false;
  2374. if (stack_top_idx != (uint32)-1) {
  2375. /* The aux stack top is a wasm global,
  2376. set the initial value for the global */
  2377. uint8 *global_addr = module_inst->global_data
  2378. + module_inst->globals[stack_top_idx].data_offset;
  2379. *(int32 *)global_addr = start_offset;
  2380. /* The aux stack boundary is a constant value,
  2381. set the value to exec_env */
  2382. exec_env->aux_stack_boundary.boundary = start_offset - size;
  2383. exec_env->aux_stack_bottom.bottom = start_offset;
  2384. return true;
  2385. }
  2386. return false;
  2387. }
  2388. bool
  2389. wasm_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size)
  2390. {
  2391. WASMModuleInstance *module_inst =
  2392. (WASMModuleInstance *)exec_env->module_inst;
  2393. /* The aux stack information is resolved in loader
  2394. and store in module */
  2395. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2396. uint32 total_aux_stack_size = module_inst->module->aux_stack_size;
  2397. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  2398. if (start_offset)
  2399. *start_offset = stack_bottom;
  2400. if (size)
  2401. *size = total_aux_stack_size;
  2402. return true;
  2403. }
  2404. return false;
  2405. }
  2406. #endif
  2407. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  2408. void
  2409. wasm_get_module_mem_consumption(const WASMModule *module,
  2410. WASMModuleMemConsumption *mem_conspn)
  2411. {
  2412. uint32 i, size;
  2413. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2414. mem_conspn->module_struct_size = sizeof(WASMModule);
  2415. mem_conspn->types_size = sizeof(WASMType *) * module->type_count;
  2416. for (i = 0; i < module->type_count; i++) {
  2417. WASMType *type = module->types[i];
  2418. size = offsetof(WASMType, types)
  2419. + sizeof(uint8) * (type->param_count + type->result_count);
  2420. mem_conspn->types_size += size;
  2421. }
  2422. mem_conspn->imports_size = sizeof(WASMImport) * module->import_count;
  2423. mem_conspn->functions_size =
  2424. sizeof(WASMFunction *) * module->function_count;
  2425. for (i = 0; i < module->function_count; i++) {
  2426. WASMFunction *func = module->functions[i];
  2427. WASMType *type = func->func_type;
  2428. size = sizeof(WASMFunction) + func->local_count
  2429. + sizeof(uint16) * (type->param_count + func->local_count);
  2430. #if WASM_ENABLE_FAST_INTERP != 0
  2431. size +=
  2432. func->code_compiled_size + sizeof(uint32) * func->const_cell_num;
  2433. #endif
  2434. mem_conspn->functions_size += size;
  2435. }
  2436. mem_conspn->tables_size = sizeof(WASMTable) * module->table_count;
  2437. mem_conspn->memories_size = sizeof(WASMMemory) * module->memory_count;
  2438. mem_conspn->globals_size = sizeof(WASMGlobal) * module->global_count;
  2439. mem_conspn->exports_size = sizeof(WASMExport) * module->export_count;
  2440. mem_conspn->table_segs_size =
  2441. sizeof(WASMTableSeg) * module->table_seg_count;
  2442. for (i = 0; i < module->table_seg_count; i++) {
  2443. WASMTableSeg *table_seg = &module->table_segments[i];
  2444. mem_conspn->tables_size += sizeof(uint32) * table_seg->function_count;
  2445. }
  2446. mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count;
  2447. for (i = 0; i < module->data_seg_count; i++) {
  2448. mem_conspn->data_segs_size += sizeof(WASMDataSeg);
  2449. }
  2450. if (module->const_str_list) {
  2451. StringNode *node = module->const_str_list, *node_next;
  2452. while (node) {
  2453. node_next = node->next;
  2454. mem_conspn->const_strs_size +=
  2455. sizeof(StringNode) + strlen(node->str) + 1;
  2456. node = node_next;
  2457. }
  2458. }
  2459. mem_conspn->total_size += mem_conspn->module_struct_size;
  2460. mem_conspn->total_size += mem_conspn->types_size;
  2461. mem_conspn->total_size += mem_conspn->imports_size;
  2462. mem_conspn->total_size += mem_conspn->functions_size;
  2463. mem_conspn->total_size += mem_conspn->tables_size;
  2464. mem_conspn->total_size += mem_conspn->memories_size;
  2465. mem_conspn->total_size += mem_conspn->globals_size;
  2466. mem_conspn->total_size += mem_conspn->exports_size;
  2467. mem_conspn->total_size += mem_conspn->table_segs_size;
  2468. mem_conspn->total_size += mem_conspn->data_segs_size;
  2469. mem_conspn->total_size += mem_conspn->const_strs_size;
  2470. }
  2471. void
  2472. wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst,
  2473. WASMModuleInstMemConsumption *mem_conspn)
  2474. {
  2475. uint32 i, size;
  2476. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2477. mem_conspn->module_inst_struct_size = sizeof(WASMModuleInstance);
  2478. mem_conspn->memories_size =
  2479. sizeof(WASMMemoryInstance *) * module_inst->memory_count;
  2480. for (i = 0; i < module_inst->memory_count; i++) {
  2481. WASMMemoryInstance *memory = module_inst->memories[i];
  2482. size = sizeof(WASMMemoryInstance)
  2483. + memory->num_bytes_per_page * memory->cur_page_count;
  2484. mem_conspn->memories_size += size;
  2485. mem_conspn->app_heap_size += memory->heap_data_end - memory->heap_data;
  2486. /* size of app heap structure */
  2487. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  2488. }
  2489. mem_conspn->tables_size =
  2490. sizeof(WASMTableInstance *) * module_inst->table_count;
  2491. for (i = 0; i < module_inst->table_count; i++) {
  2492. WASMTableInstance *table = module_inst->tables[i];
  2493. #if WASM_ENABLE_MULTI_MODULE != 0
  2494. if (table->table_inst_linked) {
  2495. size = offsetof(WASMTableInstance, base_addr);
  2496. }
  2497. else
  2498. #endif
  2499. {
  2500. size = offsetof(WASMTableInstance, base_addr)
  2501. + sizeof(uint32) * table->cur_size;
  2502. }
  2503. mem_conspn->tables_size += size;
  2504. }
  2505. mem_conspn->functions_size =
  2506. sizeof(WASMFunctionInstance) * module_inst->function_count;
  2507. mem_conspn->globals_size =
  2508. sizeof(WASMGlobalInstance) * module_inst->global_count;
  2509. if (module_inst->global_count > 0) {
  2510. WASMGlobalInstance *global =
  2511. &module_inst->globals[module_inst->global_count - 1];
  2512. mem_conspn->globals_size +=
  2513. global->data_offset + wasm_value_type_size(global->type);
  2514. }
  2515. mem_conspn->exports_size =
  2516. sizeof(WASMExportFuncInstance) * module_inst->export_func_count;
  2517. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  2518. mem_conspn->total_size += mem_conspn->memories_size;
  2519. mem_conspn->total_size += mem_conspn->functions_size;
  2520. mem_conspn->total_size += mem_conspn->tables_size;
  2521. mem_conspn->total_size += mem_conspn->globals_size;
  2522. mem_conspn->total_size += mem_conspn->exports_size;
  2523. }
  2524. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  2525. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  2526. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2527. bool
  2528. wasm_interp_create_call_stack(struct WASMExecEnv *exec_env)
  2529. {
  2530. WASMModuleInstance *module_inst =
  2531. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2532. WASMInterpFrame *first_frame,
  2533. *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  2534. uint32 n = 0;
  2535. /* count frames includes a function */
  2536. first_frame = cur_frame;
  2537. while (cur_frame) {
  2538. if (cur_frame->function) {
  2539. n++;
  2540. }
  2541. cur_frame = cur_frame->prev_frame;
  2542. }
  2543. /* release previous stack frames and create new ones */
  2544. if (!bh_vector_destroy(module_inst->frames)
  2545. || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame),
  2546. false)) {
  2547. return false;
  2548. }
  2549. cur_frame = first_frame;
  2550. n = 0;
  2551. while (cur_frame) {
  2552. WASMCApiFrame frame = { 0 };
  2553. WASMFunctionInstance *func_inst = cur_frame->function;
  2554. const char *func_name = NULL;
  2555. const uint8 *func_code_base = NULL;
  2556. if (!func_inst) {
  2557. cur_frame = cur_frame->prev_frame;
  2558. continue;
  2559. }
  2560. /* place holder, will overwrite it in wasm_c_api */
  2561. frame.instance = module_inst;
  2562. frame.module_offset = 0;
  2563. frame.func_index = (uint32)(func_inst - module_inst->functions);
  2564. func_code_base = wasm_get_func_code(func_inst);
  2565. if (!cur_frame->ip || !func_code_base) {
  2566. frame.func_offset = 0;
  2567. }
  2568. else {
  2569. frame.func_offset = (uint32)(cur_frame->ip - func_code_base);
  2570. }
  2571. /* look for the function name */
  2572. if (func_inst->is_import_func) {
  2573. func_name = func_inst->u.func_import->field_name;
  2574. }
  2575. else {
  2576. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2577. func_name = func_inst->u.func->field_name;
  2578. #endif
  2579. /* if custom name section is not generated,
  2580. search symbols from export table */
  2581. if (!func_name) {
  2582. uint32 i;
  2583. for (i = 0; i < module_inst->export_func_count; i++) {
  2584. WASMExportFuncInstance *export_func =
  2585. module_inst->export_functions + i;
  2586. if (export_func->function == func_inst) {
  2587. func_name = export_func->name;
  2588. break;
  2589. }
  2590. }
  2591. }
  2592. }
  2593. frame.func_name_wp = func_name;
  2594. if (!bh_vector_append(module_inst->frames, &frame)) {
  2595. bh_vector_destroy(module_inst->frames);
  2596. return false;
  2597. }
  2598. cur_frame = cur_frame->prev_frame;
  2599. n++;
  2600. }
  2601. return true;
  2602. }
  2603. #define PRINT_OR_DUMP() \
  2604. do { \
  2605. total_len += \
  2606. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  2607. if ((!print) && buf && (len == 0)) { \
  2608. return total_len; \
  2609. } \
  2610. } while (0)
  2611. uint32
  2612. wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf,
  2613. uint32 len)
  2614. {
  2615. WASMModuleInstance *module_inst =
  2616. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2617. uint32 n = 0, total_len = 0, total_frames;
  2618. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  2619. * will be truncated */
  2620. char line_buf[256];
  2621. if (!module_inst->frames) {
  2622. return 0;
  2623. }
  2624. total_frames = bh_vector_size(module_inst->frames);
  2625. if (total_frames == 0) {
  2626. return 0;
  2627. }
  2628. snprintf(line_buf, sizeof(line_buf), "\n");
  2629. PRINT_OR_DUMP();
  2630. while (n < total_frames) {
  2631. WASMCApiFrame frame = { 0 };
  2632. uint32 line_length, i;
  2633. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  2634. return 0;
  2635. }
  2636. /* function name not exported, print number instead */
  2637. if (frame.func_name_wp == NULL) {
  2638. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d $f%d\n",
  2639. n, frame.func_index);
  2640. }
  2641. else {
  2642. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d %s\n", n,
  2643. frame.func_name_wp);
  2644. }
  2645. if (line_length >= sizeof(line_buf)) {
  2646. uint32 line_buffer_len = sizeof(line_buf);
  2647. /* If line too long, ensure the last character is '\n' */
  2648. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  2649. line_buf[i] = '.';
  2650. }
  2651. line_buf[line_buffer_len - 2] = '\n';
  2652. }
  2653. PRINT_OR_DUMP();
  2654. n++;
  2655. }
  2656. snprintf(line_buf, sizeof(line_buf), "\n");
  2657. PRINT_OR_DUMP();
  2658. return total_len + 1;
  2659. }
  2660. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */