wasm_runtime.c 113 KB

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