wasm_runtime.c 113 KB

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