wasm_runtime.c 104 KB

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