wasm_runtime.c 115 KB

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