wasm_runtime.c 114 KB

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