wasm_runtime.c 98 KB

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