wasm_runtime.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444
  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)
  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. #ifdef OS_ENABLE_HW_BOUND_CHECK
  900. WASMModuleInstanceCommon *module_inst_main = NULL;
  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. #ifdef OS_ENABLE_HW_BOUND_CHECK
  940. if (is_sub_inst) {
  941. exec_env = exec_env_tls = wasm_runtime_get_exec_env_tls();
  942. if (exec_env_tls) {
  943. /* Temporarily replace exec_env_tls's module inst to current
  944. module inst to avoid checking failure when calling the
  945. wasm functions, and ensure that the exec_env's module inst
  946. is the correct one. */
  947. module_inst_main = exec_env_tls->module_inst;
  948. exec_env_tls->module_inst = (WASMModuleInstanceCommon *)module_inst;
  949. }
  950. }
  951. #endif
  952. if (!exec_env
  953. && !(exec_env =
  954. wasm_exec_env_create((WASMModuleInstanceCommon *)module_inst,
  955. module_inst->default_wasm_stack_size))) {
  956. wasm_set_exception(module_inst, "allocate memory failed");
  957. return false;
  958. }
  959. /* Execute start function for both main insance and sub instance */
  960. if (start_func && !wasm_call_function(exec_env, start_func, 0, NULL)) {
  961. goto fail;
  962. }
  963. if (initialize_func
  964. && !wasm_call_function(exec_env, initialize_func, 0, NULL)) {
  965. goto fail;
  966. }
  967. if (post_inst_func
  968. && !wasm_call_function(exec_env, post_inst_func, 0, NULL)) {
  969. goto fail;
  970. }
  971. if (call_ctors_func
  972. && !wasm_call_function(exec_env, call_ctors_func, 0, NULL)) {
  973. goto fail;
  974. }
  975. ret = true;
  976. fail:
  977. #ifdef OS_ENABLE_HW_BOUND_CHECK
  978. if (is_sub_inst && exec_env_tls) {
  979. bh_assert(exec_env == exec_env_tls);
  980. /* Restore the exec_env_tls's module inst */
  981. exec_env_tls->module_inst = module_inst_main;
  982. }
  983. else
  984. wasm_exec_env_destroy(exec_env);
  985. #else
  986. wasm_exec_env_destroy(exec_env);
  987. #endif
  988. return ret;
  989. }
  990. static bool
  991. execute_malloc_function(WASMModuleInstance *module_inst,
  992. WASMFunctionInstance *malloc_func,
  993. WASMFunctionInstance *retain_func, uint32 size,
  994. uint32 *p_result)
  995. {
  996. #ifdef OS_ENABLE_HW_BOUND_CHECK
  997. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  998. #endif
  999. uint32 argv[2], argc;
  1000. bool ret;
  1001. argv[0] = size;
  1002. argc = 1;
  1003. /* if __retain is exported, then this module is compiled by
  1004. assemblyscript, the memory should be managed by as's runtime,
  1005. in this case we need to call the retain function after malloc
  1006. the memory */
  1007. if (retain_func) {
  1008. /* the malloc functino from assemblyscript is:
  1009. function __new(size: usize, id: u32)
  1010. id = 0 means this is an ArrayBuffer object */
  1011. argv[1] = 0;
  1012. argc = 2;
  1013. }
  1014. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1015. if (exec_env_tls != NULL) {
  1016. bh_assert(exec_env_tls->module_inst
  1017. == (WASMModuleInstanceCommon *)module_inst);
  1018. ret = wasm_call_function(exec_env_tls, malloc_func, argc, argv);
  1019. if (retain_func && ret) {
  1020. ret = wasm_call_function(exec_env_tls, retain_func, 1, argv);
  1021. }
  1022. }
  1023. else
  1024. #endif
  1025. {
  1026. ret = wasm_create_exec_env_and_call_function(module_inst, malloc_func,
  1027. argc, argv);
  1028. if (retain_func && ret) {
  1029. ret = wasm_create_exec_env_and_call_function(module_inst,
  1030. retain_func, 1, argv);
  1031. }
  1032. }
  1033. if (ret)
  1034. *p_result = argv[0];
  1035. return ret;
  1036. }
  1037. static bool
  1038. execute_free_function(WASMModuleInstance *module_inst,
  1039. WASMFunctionInstance *free_func, uint32 offset)
  1040. {
  1041. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1042. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1043. #endif
  1044. uint32 argv[2];
  1045. argv[0] = offset;
  1046. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1047. if (exec_env_tls != NULL) {
  1048. bh_assert(exec_env_tls->module_inst
  1049. == (WASMModuleInstanceCommon *)module_inst);
  1050. return wasm_call_function(exec_env_tls, free_func, 1, argv);
  1051. }
  1052. else
  1053. #endif
  1054. {
  1055. return wasm_create_exec_env_and_call_function(module_inst, free_func, 1,
  1056. argv);
  1057. }
  1058. }
  1059. #if WASM_ENABLE_MULTI_MODULE != 0
  1060. static bool
  1061. sub_module_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
  1062. uint32 stack_size, uint32 heap_size, char *error_buf,
  1063. uint32 error_buf_size)
  1064. {
  1065. bh_list *sub_module_inst_list = module_inst->e->sub_module_inst_list;
  1066. WASMRegisteredModule *sub_module_list_node =
  1067. bh_list_first_elem(module->import_module_list);
  1068. while (sub_module_list_node) {
  1069. WASMSubModInstNode *sub_module_inst_list_node = NULL;
  1070. WASMModule *sub_module = (WASMModule *)sub_module_list_node->module;
  1071. WASMModuleInstance *sub_module_inst = NULL;
  1072. sub_module_inst =
  1073. wasm_instantiate(sub_module, false, stack_size, heap_size,
  1074. error_buf, error_buf_size);
  1075. if (!sub_module_inst) {
  1076. LOG_DEBUG("instantiate %s failed",
  1077. sub_module_list_node->module_name);
  1078. goto failed;
  1079. }
  1080. sub_module_inst_list_node = runtime_malloc(sizeof(WASMSubModInstNode),
  1081. error_buf, error_buf_size);
  1082. if (!sub_module_inst_list_node) {
  1083. LOG_DEBUG("Malloc WASMSubModInstNode failed, SZ:%d",
  1084. sizeof(WASMSubModInstNode));
  1085. goto failed;
  1086. }
  1087. sub_module_inst_list_node->module_inst = sub_module_inst;
  1088. sub_module_inst_list_node->module_name =
  1089. sub_module_list_node->module_name;
  1090. bh_list_status ret =
  1091. bh_list_insert(sub_module_inst_list, sub_module_inst_list_node);
  1092. bh_assert(BH_LIST_SUCCESS == ret);
  1093. (void)ret;
  1094. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  1095. continue;
  1096. failed:
  1097. if (sub_module_inst_list_node) {
  1098. bh_list_remove(sub_module_inst_list, sub_module_inst_list_node);
  1099. wasm_runtime_free(sub_module_inst_list_node);
  1100. }
  1101. if (sub_module_inst)
  1102. wasm_deinstantiate(sub_module_inst, false);
  1103. return false;
  1104. }
  1105. return true;
  1106. }
  1107. static void
  1108. sub_module_deinstantiate(WASMModuleInstance *module_inst)
  1109. {
  1110. bh_list *list = module_inst->e->sub_module_inst_list;
  1111. WASMSubModInstNode *node = bh_list_first_elem(list);
  1112. while (node) {
  1113. WASMSubModInstNode *next_node = bh_list_elem_next(node);
  1114. bh_list_remove(list, node);
  1115. wasm_deinstantiate(node->module_inst, false);
  1116. wasm_runtime_free(node);
  1117. node = next_node;
  1118. }
  1119. }
  1120. #endif
  1121. static bool
  1122. check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf,
  1123. uint32 error_buf_size)
  1124. {
  1125. WASMModule *module = module_inst->module;
  1126. uint32 i;
  1127. for (i = 0; i < module->import_function_count; i++) {
  1128. WASMFunctionImport *func =
  1129. &((module->import_functions + i)->u.function);
  1130. if (!func->func_ptr_linked
  1131. #if WASM_ENABLE_MULTI_MODULE != 0
  1132. && !func->import_func_linked
  1133. #endif
  1134. ) {
  1135. #if WASM_ENABLE_WAMR_COMPILER == 0
  1136. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1137. func->module_name, func->field_name);
  1138. /* will throw exception only if calling */
  1139. #else
  1140. /* do nothing to avoid confused message */
  1141. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1142. }
  1143. }
  1144. for (i = 0; i < module->import_global_count; i++) {
  1145. WASMGlobalImport *global = &((module->import_globals + i)->u.global);
  1146. if (!global->is_linked) {
  1147. #if WASM_ENABLE_SPEC_TEST != 0
  1148. set_error_buf(error_buf, error_buf_size,
  1149. "unknown import or incompatible import type");
  1150. return false;
  1151. #else
  1152. #if WASM_ENABLE_WAMR_COMPILER == 0
  1153. set_error_buf_v(error_buf, error_buf_size,
  1154. "failed to link import global (%s, %s)",
  1155. global->module_name, global->field_name);
  1156. return false;
  1157. #else
  1158. /* do nothing to avoid confused message */
  1159. #endif /* WASM_ENABLE_WAMR_COMPILER == 0 */
  1160. #endif /* WASM_ENABLE_SPEC_TEST != 0 */
  1161. }
  1162. }
  1163. return true;
  1164. }
  1165. #if WASM_ENABLE_JIT != 0
  1166. static bool
  1167. init_func_ptrs(WASMModuleInstance *module_inst, WASMModule *module,
  1168. char *error_buf, uint32 error_buf_size)
  1169. {
  1170. uint32 i;
  1171. void **func_ptrs;
  1172. uint64 total_size = (uint64)sizeof(void *) * module_inst->e->function_count;
  1173. /* Allocate memory */
  1174. if (!(func_ptrs = module_inst->func_ptrs =
  1175. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1176. return false;
  1177. }
  1178. /* Set import function pointers */
  1179. for (i = 0; i < module->import_function_count; i++, func_ptrs++) {
  1180. WASMFunctionImport *import_func =
  1181. &module->import_functions[i].u.function;
  1182. /* TODO: handle multi module */
  1183. *func_ptrs = import_func->func_ptr_linked;
  1184. }
  1185. /* The defined function pointers will be set in
  1186. wasm_runtime_set_running_mode, no need to set them here */
  1187. return true;
  1188. }
  1189. #endif /* end of WASM_ENABLE_JIT != 0 */
  1190. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1191. static uint32
  1192. get_smallest_type_idx(WASMModule *module, WASMType *func_type)
  1193. {
  1194. uint32 i;
  1195. for (i = 0; i < module->type_count; i++) {
  1196. if (func_type == module->types[i])
  1197. return i;
  1198. }
  1199. bh_assert(0);
  1200. return -1;
  1201. }
  1202. static bool
  1203. init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf,
  1204. uint32 error_buf_size)
  1205. {
  1206. uint32 i;
  1207. uint64 total_size = (uint64)sizeof(uint32) * module_inst->e->function_count;
  1208. /* Allocate memory */
  1209. if (!(module_inst->func_type_indexes =
  1210. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1211. return false;
  1212. }
  1213. for (i = 0; i < module_inst->e->function_count; i++) {
  1214. WASMFunctionInstance *func_inst = module_inst->e->functions + i;
  1215. WASMType *func_type = func_inst->is_import_func
  1216. ? func_inst->u.func_import->func_type
  1217. : func_inst->u.func->func_type;
  1218. module_inst->func_type_indexes[i] =
  1219. get_smallest_type_idx(module_inst->module, func_type);
  1220. }
  1221. return true;
  1222. }
  1223. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 */
  1224. static bool
  1225. set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode,
  1226. bool first_time_set)
  1227. {
  1228. WASMModule *module = module_inst->module;
  1229. if (running_mode == Mode_Default) {
  1230. #if WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT == 0
  1231. running_mode = Mode_Interp;
  1232. #elif WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT == 0
  1233. running_mode = Mode_Fast_JIT;
  1234. #elif WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT != 0
  1235. running_mode = Mode_LLVM_JIT;
  1236. #else /* WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 */
  1237. #if WASM_ENABLE_LAZY_JIT == 0
  1238. running_mode = Mode_LLVM_JIT;
  1239. #else
  1240. running_mode = Mode_Multi_Tier_JIT;
  1241. #endif
  1242. #endif
  1243. }
  1244. if (!wasm_runtime_is_running_mode_supported(running_mode))
  1245. return false;
  1246. #if !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1247. && WASM_ENABLE_LAZY_JIT != 0) /* No possible multi-tier JIT */
  1248. module_inst->e->running_mode = running_mode;
  1249. if (running_mode == Mode_Interp) {
  1250. /* Do nothing for Mode_Interp */
  1251. }
  1252. else if (running_mode == Mode_Fast_JIT) {
  1253. /* Do nothing for Mode_Fast_JIT since
  1254. module_inst->fast_jit_func_ptrs is same as
  1255. module->fast_jit_func_ptrs */
  1256. }
  1257. #if WASM_ENABLE_JIT != 0
  1258. else if (running_mode == Mode_LLVM_JIT) {
  1259. /* Set defined function pointers */
  1260. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  1261. sizeof(void *) * module->function_count, module->func_ptrs,
  1262. sizeof(void *) * module->function_count);
  1263. }
  1264. #endif
  1265. else {
  1266. bh_assert(0);
  1267. }
  1268. #else /* Possible multi-tier JIT */
  1269. os_mutex_lock(&module->instance_list_lock);
  1270. module_inst->e->running_mode = running_mode;
  1271. if (running_mode == Mode_Interp) {
  1272. /* Do nothing for Mode_Interp */
  1273. }
  1274. #if WASM_ENABLE_FAST_JIT != 0
  1275. else if (running_mode == Mode_Fast_JIT) {
  1276. JitGlobals *jit_globals = jit_compiler_get_jit_globals();
  1277. uint32 i;
  1278. /* Allocate memory for fast_jit_func_ptrs if needed */
  1279. if (!module_inst->fast_jit_func_ptrs
  1280. || module_inst->fast_jit_func_ptrs == module->fast_jit_func_ptrs) {
  1281. uint64 total_size = (uint64)sizeof(void *) * module->function_count;
  1282. if (!(module_inst->fast_jit_func_ptrs =
  1283. runtime_malloc(total_size, NULL, 0))) {
  1284. os_mutex_unlock(&module->instance_list_lock);
  1285. return false;
  1286. }
  1287. }
  1288. for (i = 0; i < module->function_count; i++) {
  1289. if (module->functions[i]->fast_jit_jitted_code) {
  1290. /* current fast jit function has been compiled */
  1291. module_inst->fast_jit_func_ptrs[i] =
  1292. module->functions[i]->fast_jit_jitted_code;
  1293. }
  1294. else {
  1295. module_inst->fast_jit_func_ptrs[i] =
  1296. jit_globals->compile_fast_jit_and_then_call;
  1297. }
  1298. }
  1299. }
  1300. #endif
  1301. #if WASM_ENABLE_JIT != 0
  1302. else if (running_mode == Mode_LLVM_JIT) {
  1303. void **llvm_jit_func_ptrs;
  1304. uint32 i;
  1305. /* Notify backend threads to start llvm jit compilation */
  1306. module->enable_llvm_jit_compilation = true;
  1307. /* Wait until llvm jit finishes initialization */
  1308. os_mutex_lock(&module->tierup_wait_lock);
  1309. while (!module->llvm_jit_inited) {
  1310. os_cond_reltimedwait(&module->tierup_wait_cond,
  1311. &module->tierup_wait_lock, 10);
  1312. if (module->orcjit_stop_compiling) {
  1313. /* init_llvm_jit_functions_stage2 failed */
  1314. os_mutex_unlock(&module->tierup_wait_lock);
  1315. os_mutex_unlock(&module->instance_list_lock);
  1316. return false;
  1317. }
  1318. }
  1319. os_mutex_unlock(&module->tierup_wait_lock);
  1320. llvm_jit_func_ptrs =
  1321. module_inst->func_ptrs + module->import_function_count;
  1322. for (i = 0; i < module->function_count; i++) {
  1323. llvm_jit_func_ptrs[i] = module->functions[i]->llvm_jit_func_ptr;
  1324. }
  1325. }
  1326. #endif
  1327. else if (running_mode == Mode_Multi_Tier_JIT) {
  1328. /* Notify backend threads to start llvm jit compilation */
  1329. module->enable_llvm_jit_compilation = true;
  1330. /* Free fast_jit_func_ptrs if it is allocated before */
  1331. if (module_inst->fast_jit_func_ptrs
  1332. && module_inst->fast_jit_func_ptrs != module->fast_jit_func_ptrs) {
  1333. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  1334. }
  1335. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  1336. /* Copy all llvm jit func ptrs from the module */
  1337. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  1338. sizeof(void *) * module->function_count, module->func_ptrs,
  1339. sizeof(void *) * module->function_count);
  1340. }
  1341. else {
  1342. bh_assert(0);
  1343. }
  1344. /* Add module instance into module's instance list if not added */
  1345. if (first_time_set) {
  1346. bool found = false;
  1347. WASMModuleInstance *node = module->instance_list;
  1348. while (node) {
  1349. if (node == module_inst) {
  1350. found = true;
  1351. break;
  1352. }
  1353. node = node->e->next;
  1354. }
  1355. if (!found) {
  1356. module_inst->e->next = module->instance_list;
  1357. module->instance_list = module_inst;
  1358. }
  1359. }
  1360. os_mutex_unlock(&module->instance_list_lock);
  1361. #endif /* end of !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1362. && WASM_ENABLE_LAZY_JIT != 0) */
  1363. (void)module;
  1364. return true;
  1365. }
  1366. bool
  1367. wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode)
  1368. {
  1369. return set_running_mode(module_inst, running_mode, false);
  1370. }
  1371. /**
  1372. * Instantiate module
  1373. */
  1374. WASMModuleInstance *
  1375. wasm_instantiate(WASMModule *module, bool is_sub_inst, uint32 stack_size,
  1376. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  1377. {
  1378. WASMModuleInstance *module_inst;
  1379. WASMGlobalInstance *globals = NULL, *global;
  1380. WASMTableInstance *first_table;
  1381. uint32 global_count, i;
  1382. uint32 base_offset, length, extra_info_offset;
  1383. uint32 module_inst_struct_size =
  1384. offsetof(WASMModuleInstance, global_table_data.bytes);
  1385. uint64 module_inst_mem_inst_size;
  1386. uint64 total_size, table_size = 0;
  1387. uint8 *global_data, *global_data_end;
  1388. #if WASM_ENABLE_MULTI_MODULE != 0
  1389. bool ret = false;
  1390. #endif
  1391. if (!module)
  1392. return NULL;
  1393. /* Check the heap size */
  1394. heap_size = align_uint(heap_size, 8);
  1395. if (heap_size > APP_HEAP_SIZE_MAX)
  1396. heap_size = APP_HEAP_SIZE_MAX;
  1397. module_inst_mem_inst_size =
  1398. (uint64)sizeof(WASMMemoryInstance)
  1399. * (module->import_memory_count + module->memory_count);
  1400. #if WASM_ENABLE_JIT != 0
  1401. /* If the module dosen't have memory, reserve one mem_info space
  1402. with empty content to align with llvm jit compiler */
  1403. if (module_inst_mem_inst_size == 0)
  1404. module_inst_mem_inst_size = (uint64)sizeof(WASMMemoryInstance);
  1405. #endif
  1406. /* Size of module inst, memory instances and global data */
  1407. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  1408. + module->global_data_size;
  1409. /* Calculate the size of table data */
  1410. for (i = 0; i < module->import_table_count; i++) {
  1411. WASMTableImport *import_table = &module->import_tables[i].u.table;
  1412. table_size += offsetof(WASMTableInstance, elems);
  1413. #if WASM_ENABLE_MULTI_MODULE != 0
  1414. table_size += (uint64)sizeof(uint32) * import_table->max_size;
  1415. #else
  1416. table_size += (uint64)sizeof(uint32)
  1417. * (import_table->possible_grow ? import_table->max_size
  1418. : import_table->init_size);
  1419. #endif
  1420. }
  1421. for (i = 0; i < module->table_count; i++) {
  1422. WASMTable *table = module->tables + i;
  1423. table_size += offsetof(WASMTableInstance, elems);
  1424. #if WASM_ENABLE_MULTI_MODULE != 0
  1425. table_size += (uint64)sizeof(uint32) * table->max_size;
  1426. #else
  1427. table_size +=
  1428. (uint64)sizeof(uint32)
  1429. * (table->possible_grow ? table->max_size : table->init_size);
  1430. #endif
  1431. }
  1432. total_size += table_size;
  1433. /* The offset of WASMModuleInstanceExtra, make it 8-byte aligned */
  1434. total_size = (total_size + 7LL) & ~7LL;
  1435. extra_info_offset = (uint32)total_size;
  1436. total_size += sizeof(WASMModuleInstanceExtra);
  1437. /* Allocate the memory for module instance with memory instances,
  1438. global data, table data appended at the end */
  1439. if (!(module_inst =
  1440. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1441. return NULL;
  1442. }
  1443. module_inst->module_type = Wasm_Module_Bytecode;
  1444. module_inst->module = module;
  1445. module_inst->e =
  1446. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  1447. #if WASM_ENABLE_MULTI_MODULE != 0
  1448. module_inst->e->sub_module_inst_list =
  1449. &module_inst->e->sub_module_inst_list_head;
  1450. ret = sub_module_instantiate(module, module_inst, stack_size, heap_size,
  1451. error_buf, error_buf_size);
  1452. if (!ret) {
  1453. LOG_DEBUG("build a sub module list failed");
  1454. goto fail;
  1455. }
  1456. #endif
  1457. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1458. if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector),
  1459. error_buf, error_buf_size))) {
  1460. goto fail;
  1461. }
  1462. #endif
  1463. /* Instantiate global firstly to get the mutable data size */
  1464. global_count = module->import_global_count + module->global_count;
  1465. if (global_count
  1466. && !(globals = globals_instantiate(module, module_inst, error_buf,
  1467. error_buf_size))) {
  1468. goto fail;
  1469. }
  1470. module_inst->e->global_count = global_count;
  1471. module_inst->e->globals = globals;
  1472. module_inst->global_data = (uint8 *)module_inst + module_inst_struct_size
  1473. + module_inst_mem_inst_size;
  1474. module_inst->global_data_size = module->global_data_size;
  1475. first_table = (WASMTableInstance *)(module_inst->global_data
  1476. + module->global_data_size);
  1477. module_inst->memory_count =
  1478. module->import_memory_count + module->memory_count;
  1479. module_inst->table_count = module->import_table_count + module->table_count;
  1480. module_inst->e->function_count =
  1481. module->import_function_count + module->function_count;
  1482. /* export */
  1483. module_inst->export_func_count = get_export_count(module, EXPORT_KIND_FUNC);
  1484. #if WASM_ENABLE_MULTI_MODULE != 0
  1485. module_inst->export_table_count =
  1486. get_export_count(module, EXPORT_KIND_TABLE);
  1487. module_inst->export_memory_count =
  1488. get_export_count(module, EXPORT_KIND_MEMORY);
  1489. module_inst->export_global_count =
  1490. get_export_count(module, EXPORT_KIND_GLOBAL);
  1491. #endif
  1492. /* Instantiate memories/tables/functions */
  1493. if ((module_inst->memory_count > 0
  1494. && !(module_inst->memories = memories_instantiate(
  1495. module, module_inst, heap_size, error_buf, error_buf_size)))
  1496. || (module_inst->table_count > 0
  1497. && !(module_inst->tables =
  1498. tables_instantiate(module, module_inst, first_table,
  1499. error_buf, error_buf_size)))
  1500. || (module_inst->e->function_count > 0
  1501. && !(module_inst->e->functions = functions_instantiate(
  1502. module, module_inst, error_buf, error_buf_size)))
  1503. || (module_inst->export_func_count > 0
  1504. && !(module_inst->export_functions = export_functions_instantiate(
  1505. module, module_inst, module_inst->export_func_count,
  1506. error_buf, error_buf_size)))
  1507. #if WASM_ENABLE_MULTI_MODULE != 0
  1508. || (module_inst->export_global_count > 0
  1509. && !(module_inst->export_globals = export_globals_instantiate(
  1510. module, module_inst, module_inst->export_global_count,
  1511. error_buf, error_buf_size)))
  1512. #endif
  1513. #if WASM_ENABLE_JIT != 0
  1514. || (module_inst->e->function_count > 0
  1515. && !init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  1516. #endif
  1517. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1518. || (module_inst->e->function_count > 0
  1519. && !init_func_type_indexes(module_inst, error_buf, error_buf_size))
  1520. #endif
  1521. ) {
  1522. goto fail;
  1523. }
  1524. if (global_count > 0) {
  1525. /* Initialize the global data */
  1526. global_data = module_inst->global_data;
  1527. global_data_end = global_data + module->global_data_size;
  1528. global = globals;
  1529. for (i = 0; i < global_count; i++, global++) {
  1530. switch (global->type) {
  1531. case VALUE_TYPE_I32:
  1532. case VALUE_TYPE_F32:
  1533. #if WASM_ENABLE_REF_TYPES != 0
  1534. case VALUE_TYPE_FUNCREF:
  1535. case VALUE_TYPE_EXTERNREF:
  1536. #endif
  1537. *(int32 *)global_data = global->initial_value.i32;
  1538. global_data += sizeof(int32);
  1539. break;
  1540. case VALUE_TYPE_I64:
  1541. case VALUE_TYPE_F64:
  1542. bh_memcpy_s(global_data,
  1543. (uint32)(global_data_end - global_data),
  1544. &global->initial_value.i64, sizeof(int64));
  1545. global_data += sizeof(int64);
  1546. break;
  1547. #if WASM_ENABLE_SIMD != 0
  1548. case VALUE_TYPE_V128:
  1549. bh_memcpy_s(global_data, (uint32)sizeof(V128),
  1550. &global->initial_value.v128, sizeof(V128));
  1551. global_data += sizeof(V128);
  1552. break;
  1553. #endif
  1554. default:
  1555. bh_assert(0);
  1556. }
  1557. }
  1558. bh_assert(global_data == global_data_end);
  1559. }
  1560. if (!check_linked_symbol(module_inst, error_buf, error_buf_size)) {
  1561. goto fail;
  1562. }
  1563. /* Initialize the memory data with data segment section */
  1564. for (i = 0; i < module->data_seg_count; i++) {
  1565. WASMMemoryInstance *memory = NULL;
  1566. uint8 *memory_data = NULL;
  1567. uint32 memory_size = 0;
  1568. WASMDataSeg *data_seg = module->data_segments[i];
  1569. #if WASM_ENABLE_BULK_MEMORY != 0
  1570. if (data_seg->is_passive)
  1571. continue;
  1572. #endif
  1573. /* has check it in loader */
  1574. memory = module_inst->memories[data_seg->memory_index];
  1575. bh_assert(memory);
  1576. memory_data = memory->memory_data;
  1577. memory_size = memory->num_bytes_per_page * memory->cur_page_count;
  1578. bh_assert(memory_data || memory_size == 0);
  1579. bh_assert(data_seg->base_offset.init_expr_type
  1580. == INIT_EXPR_TYPE_I32_CONST
  1581. || data_seg->base_offset.init_expr_type
  1582. == INIT_EXPR_TYPE_GET_GLOBAL);
  1583. if (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  1584. if (!check_global_init_expr(module,
  1585. data_seg->base_offset.u.global_index,
  1586. error_buf, error_buf_size)) {
  1587. goto fail;
  1588. }
  1589. if (!globals
  1590. || globals[data_seg->base_offset.u.global_index].type
  1591. != VALUE_TYPE_I32) {
  1592. set_error_buf(error_buf, error_buf_size,
  1593. "data segment does not fit");
  1594. goto fail;
  1595. }
  1596. base_offset =
  1597. globals[data_seg->base_offset.u.global_index].initial_value.i32;
  1598. }
  1599. else {
  1600. base_offset = (uint32)data_seg->base_offset.u.i32;
  1601. }
  1602. /* check offset */
  1603. if (base_offset > memory_size) {
  1604. LOG_DEBUG("base_offset(%d) > memory_size(%d)", base_offset,
  1605. memory_size);
  1606. #if WASM_ENABLE_REF_TYPES != 0
  1607. set_error_buf(error_buf, error_buf_size,
  1608. "out of bounds memory access");
  1609. #else
  1610. set_error_buf(error_buf, error_buf_size,
  1611. "data segment does not fit");
  1612. #endif
  1613. goto fail;
  1614. }
  1615. /* check offset + length(could be zero) */
  1616. length = data_seg->data_length;
  1617. if (base_offset + length > memory_size) {
  1618. LOG_DEBUG("base_offset(%d) + length(%d) > memory_size(%d)",
  1619. base_offset, length, memory_size);
  1620. #if WASM_ENABLE_REF_TYPES != 0
  1621. set_error_buf(error_buf, error_buf_size,
  1622. "out of bounds memory access");
  1623. #else
  1624. set_error_buf(error_buf, error_buf_size,
  1625. "data segment does not fit");
  1626. #endif
  1627. goto fail;
  1628. }
  1629. if (memory_data) {
  1630. bh_memcpy_s(memory_data + base_offset, memory_size - base_offset,
  1631. data_seg->data, length);
  1632. }
  1633. }
  1634. /* Initialize the table data with table segment section */
  1635. for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count;
  1636. i++) {
  1637. WASMTableSeg *table_seg = module->table_segments + i;
  1638. /* has check it in loader */
  1639. WASMTableInstance *table = module_inst->tables[table_seg->table_index];
  1640. uint32 *table_data;
  1641. #if WASM_ENABLE_REF_TYPES != 0
  1642. uint8 tbl_elem_type;
  1643. uint32 tbl_init_size, tbl_max_size;
  1644. #endif
  1645. bh_assert(table);
  1646. #if WASM_ENABLE_REF_TYPES != 0
  1647. (void)wasm_runtime_get_table_inst_elem_type(
  1648. (WASMModuleInstanceCommon *)module_inst, table_seg->table_index,
  1649. &tbl_elem_type, &tbl_init_size, &tbl_max_size);
  1650. if (tbl_elem_type != VALUE_TYPE_FUNCREF
  1651. && tbl_elem_type != VALUE_TYPE_EXTERNREF) {
  1652. set_error_buf(error_buf, error_buf_size,
  1653. "elements segment does not fit");
  1654. goto fail;
  1655. }
  1656. (void)tbl_init_size;
  1657. (void)tbl_max_size;
  1658. #endif
  1659. table_data = table->elems;
  1660. #if WASM_ENABLE_MULTI_MODULE != 0
  1661. if (table_seg->table_index < module->import_table_count
  1662. && module_inst->e->table_insts_linked[table_seg->table_index]) {
  1663. table_data =
  1664. module_inst->e->table_insts_linked[table_seg->table_index]
  1665. ->elems;
  1666. }
  1667. #endif
  1668. bh_assert(table_data);
  1669. #if WASM_ENABLE_REF_TYPES != 0
  1670. if (!wasm_elem_is_active(table_seg->mode))
  1671. continue;
  1672. #endif
  1673. #if WASM_ENABLE_REF_TYPES != 0
  1674. bh_assert(table_seg->base_offset.init_expr_type
  1675. == INIT_EXPR_TYPE_I32_CONST
  1676. || table_seg->base_offset.init_expr_type
  1677. == INIT_EXPR_TYPE_GET_GLOBAL
  1678. || table_seg->base_offset.init_expr_type
  1679. == INIT_EXPR_TYPE_FUNCREF_CONST
  1680. || table_seg->base_offset.init_expr_type
  1681. == INIT_EXPR_TYPE_REFNULL_CONST);
  1682. #else
  1683. bh_assert(table_seg->base_offset.init_expr_type
  1684. == INIT_EXPR_TYPE_I32_CONST
  1685. || table_seg->base_offset.init_expr_type
  1686. == INIT_EXPR_TYPE_GET_GLOBAL);
  1687. #endif
  1688. /* init vec(funcidx) or vec(expr) */
  1689. if (table_seg->base_offset.init_expr_type
  1690. == INIT_EXPR_TYPE_GET_GLOBAL) {
  1691. if (!check_global_init_expr(module,
  1692. table_seg->base_offset.u.global_index,
  1693. error_buf, error_buf_size)) {
  1694. goto fail;
  1695. }
  1696. if (!globals
  1697. || globals[table_seg->base_offset.u.global_index].type
  1698. != VALUE_TYPE_I32) {
  1699. set_error_buf(error_buf, error_buf_size,
  1700. "elements segment does not fit");
  1701. goto fail;
  1702. }
  1703. table_seg->base_offset.u.i32 =
  1704. globals[table_seg->base_offset.u.global_index]
  1705. .initial_value.i32;
  1706. }
  1707. /* check offset since length might negative */
  1708. if ((uint32)table_seg->base_offset.u.i32 > table->cur_size) {
  1709. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)",
  1710. table_seg->base_offset.u.i32, table->cur_size);
  1711. #if WASM_ENABLE_REF_TYPES != 0
  1712. set_error_buf(error_buf, error_buf_size,
  1713. "out of bounds table access");
  1714. #else
  1715. set_error_buf(error_buf, error_buf_size,
  1716. "elements segment does not fit");
  1717. #endif
  1718. goto fail;
  1719. }
  1720. /* check offset + length(could be zero) */
  1721. length = table_seg->function_count;
  1722. if ((uint32)table_seg->base_offset.u.i32 + length > table->cur_size) {
  1723. LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)",
  1724. table_seg->base_offset.u.i32, length, table->cur_size);
  1725. #if WASM_ENABLE_REF_TYPES != 0
  1726. set_error_buf(error_buf, error_buf_size,
  1727. "out of bounds table access");
  1728. #else
  1729. set_error_buf(error_buf, error_buf_size,
  1730. "elements segment does not fit");
  1731. #endif
  1732. goto fail;
  1733. }
  1734. /**
  1735. * Check function index in the current module inst for now.
  1736. * will check the linked table inst owner in future.
  1737. * so loader check is enough
  1738. */
  1739. bh_memcpy_s(
  1740. table_data + table_seg->base_offset.u.i32,
  1741. (uint32)((table->cur_size - (uint32)table_seg->base_offset.u.i32)
  1742. * sizeof(uint32)),
  1743. table_seg->func_indexes, (uint32)(length * sizeof(uint32)));
  1744. }
  1745. /* Initialize the thread related data */
  1746. if (stack_size == 0)
  1747. stack_size = DEFAULT_WASM_STACK_SIZE;
  1748. #if WASM_ENABLE_SPEC_TEST != 0
  1749. if (stack_size < 128 * 1024)
  1750. stack_size = 128 * 1024;
  1751. #endif
  1752. module_inst->default_wasm_stack_size = stack_size;
  1753. if (module->malloc_function != (uint32)-1) {
  1754. module_inst->e->malloc_function =
  1755. &module_inst->e->functions[module->malloc_function];
  1756. }
  1757. if (module->free_function != (uint32)-1) {
  1758. module_inst->e->free_function =
  1759. &module_inst->e->functions[module->free_function];
  1760. }
  1761. if (module->retain_function != (uint32)-1) {
  1762. module_inst->e->retain_function =
  1763. &module_inst->e->functions[module->retain_function];
  1764. }
  1765. #if WASM_ENABLE_LIBC_WASI != 0
  1766. /* The sub-instance will get the wasi_ctx from main-instance */
  1767. if (!is_sub_inst) {
  1768. if (!wasm_runtime_init_wasi(
  1769. (WASMModuleInstanceCommon *)module_inst,
  1770. module->wasi_args.dir_list, module->wasi_args.dir_count,
  1771. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  1772. module->wasi_args.env, module->wasi_args.env_count,
  1773. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  1774. module->wasi_args.ns_lookup_pool,
  1775. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  1776. module->wasi_args.argc, module->wasi_args.stdio[0],
  1777. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  1778. error_buf, error_buf_size)) {
  1779. goto fail;
  1780. }
  1781. }
  1782. #endif
  1783. #if WASM_ENABLE_WASI_NN != 0
  1784. if (!is_sub_inst) {
  1785. if (!(module_inst->e->wasi_nn_ctx = wasi_nn_initialize())) {
  1786. set_error_buf(error_buf, error_buf_size,
  1787. "wasi nn initialization failed");
  1788. goto fail;
  1789. }
  1790. }
  1791. #endif
  1792. #if WASM_ENABLE_DEBUG_INTERP != 0
  1793. if (!is_sub_inst) {
  1794. /* Add module instance into module's instance list */
  1795. os_mutex_lock(&module->instance_list_lock);
  1796. if (module->instance_list) {
  1797. LOG_WARNING(
  1798. "warning: multiple instances referencing to the same module "
  1799. "may cause unexpected behaviour during debugging");
  1800. }
  1801. module_inst->e->next = module->instance_list;
  1802. module->instance_list = module_inst;
  1803. os_mutex_unlock(&module->instance_list_lock);
  1804. }
  1805. #endif
  1806. /* Set running mode before executing wasm functions */
  1807. if (!set_running_mode(module_inst, wasm_runtime_get_default_running_mode(),
  1808. true)) {
  1809. set_error_buf(error_buf, error_buf_size,
  1810. "set instance running mode failed");
  1811. goto fail;
  1812. }
  1813. if (module->start_function != (uint32)-1) {
  1814. /* TODO: fix start function can be import function issue */
  1815. if (module->start_function >= module->import_function_count)
  1816. module_inst->e->start_function =
  1817. &module_inst->e->functions[module->start_function];
  1818. }
  1819. if (!execute_post_instantiate_functions(module_inst, is_sub_inst)) {
  1820. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  1821. goto fail;
  1822. }
  1823. #if WASM_ENABLE_MEMORY_TRACING != 0
  1824. wasm_runtime_dump_module_inst_mem_consumption(
  1825. (WASMModuleInstanceCommon *)module_inst);
  1826. #endif
  1827. (void)global_data_end;
  1828. return module_inst;
  1829. fail:
  1830. wasm_deinstantiate(module_inst, false);
  1831. return NULL;
  1832. }
  1833. void
  1834. wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst)
  1835. {
  1836. if (!module_inst)
  1837. return;
  1838. #if WASM_ENABLE_DEBUG_INTERP != 0 \
  1839. || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1840. && WASM_ENABLE_LAZY_JIT != 0)
  1841. /* Remove instance from module's instance list before freeing
  1842. func_ptrs and fast_jit_func_ptrs of the instance, to avoid
  1843. accessing the freed memory in the jit backend compilation
  1844. threads */
  1845. if (!is_sub_inst) {
  1846. WASMModule *module = module_inst->module;
  1847. WASMModuleInstance *instance_prev = NULL, *instance;
  1848. os_mutex_lock(&module->instance_list_lock);
  1849. instance = module->instance_list;
  1850. while (instance) {
  1851. if (instance == module_inst) {
  1852. if (!instance_prev)
  1853. module->instance_list = instance->e->next;
  1854. else
  1855. instance_prev->e->next = instance->e->next;
  1856. break;
  1857. }
  1858. instance_prev = instance;
  1859. instance = instance->e->next;
  1860. }
  1861. os_mutex_unlock(&module->instance_list_lock);
  1862. }
  1863. #endif
  1864. #if WASM_ENABLE_JIT != 0
  1865. if (module_inst->func_ptrs)
  1866. wasm_runtime_free(module_inst->func_ptrs);
  1867. #endif
  1868. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1869. && WASM_ENABLE_LAZY_JIT != 0
  1870. if (module_inst->fast_jit_func_ptrs
  1871. && module_inst->fast_jit_func_ptrs
  1872. != module_inst->module->fast_jit_func_ptrs)
  1873. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  1874. #endif
  1875. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1876. if (module_inst->func_type_indexes)
  1877. wasm_runtime_free(module_inst->func_type_indexes);
  1878. #endif
  1879. #if WASM_ENABLE_MULTI_MODULE != 0
  1880. sub_module_deinstantiate(module_inst);
  1881. #endif
  1882. #if WASM_ENABLE_LIBC_WASI != 0
  1883. /* Destroy wasi resource before freeing app heap, since some fields of
  1884. wasi contex are allocated from app heap, and if app heap is freed,
  1885. these fields will be set to NULL, we cannot free their internal data
  1886. which may allocated from global heap. */
  1887. /* Only destroy wasi ctx in the main module instance */
  1888. if (!is_sub_inst)
  1889. wasm_runtime_destroy_wasi((WASMModuleInstanceCommon *)module_inst);
  1890. #endif
  1891. if (module_inst->memory_count > 0)
  1892. memories_deinstantiate(module_inst, module_inst->memories,
  1893. module_inst->memory_count);
  1894. if (module_inst->import_func_ptrs) {
  1895. wasm_runtime_free(module_inst->import_func_ptrs);
  1896. }
  1897. tables_deinstantiate(module_inst);
  1898. functions_deinstantiate(module_inst->e->functions,
  1899. module_inst->e->function_count);
  1900. globals_deinstantiate(module_inst->e->globals);
  1901. export_functions_deinstantiate(module_inst->export_functions);
  1902. #if WASM_ENABLE_MULTI_MODULE != 0
  1903. export_globals_deinstantiate(module_inst->export_globals);
  1904. #endif
  1905. #if WASM_ENABLE_REF_TYPES != 0
  1906. wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst);
  1907. #endif
  1908. if (module_inst->exec_env_singleton)
  1909. wasm_exec_env_destroy(module_inst->exec_env_singleton);
  1910. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1911. if (module_inst->frames) {
  1912. bh_vector_destroy(module_inst->frames);
  1913. wasm_runtime_free(module_inst->frames);
  1914. module_inst->frames = NULL;
  1915. }
  1916. #endif
  1917. if (module_inst->e->c_api_func_imports)
  1918. wasm_runtime_free(module_inst->e->c_api_func_imports);
  1919. #if WASM_ENABLE_WASI_NN != 0
  1920. if (!is_sub_inst) {
  1921. WASINNContext *wasi_nn_ctx = module_inst->e->wasi_nn_ctx;
  1922. if (wasi_nn_ctx)
  1923. wasi_nn_destroy(wasi_nn_ctx);
  1924. }
  1925. #endif
  1926. wasm_runtime_free(module_inst);
  1927. }
  1928. WASMFunctionInstance *
  1929. wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name,
  1930. const char *signature)
  1931. {
  1932. uint32 i;
  1933. for (i = 0; i < module_inst->export_func_count; i++)
  1934. if (!strcmp(module_inst->export_functions[i].name, name))
  1935. return module_inst->export_functions[i].function;
  1936. (void)signature;
  1937. return NULL;
  1938. }
  1939. #if WASM_ENABLE_MULTI_MODULE != 0
  1940. WASMGlobalInstance *
  1941. wasm_lookup_global(const WASMModuleInstance *module_inst, const char *name)
  1942. {
  1943. uint32 i;
  1944. for (i = 0; i < module_inst->export_global_count; i++)
  1945. if (!strcmp(module_inst->export_globals[i].name, name))
  1946. return module_inst->export_globals[i].global;
  1947. return NULL;
  1948. }
  1949. WASMMemoryInstance *
  1950. wasm_lookup_memory(const WASMModuleInstance *module_inst, const char *name)
  1951. {
  1952. /**
  1953. * using a strong assumption that one module instance only has
  1954. * one memory instance
  1955. */
  1956. (void)module_inst->export_memories;
  1957. return module_inst->memories[0];
  1958. }
  1959. WASMTableInstance *
  1960. wasm_lookup_table(const WASMModuleInstance *module_inst, const char *name)
  1961. {
  1962. /**
  1963. * using a strong assumption that one module instance only has
  1964. * one table instance
  1965. */
  1966. (void)module_inst->export_tables;
  1967. return module_inst->tables[0];
  1968. }
  1969. #endif
  1970. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1971. static void
  1972. call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst,
  1973. WASMExecEnv *exec_env,
  1974. WASMFunctionInstance *function, unsigned argc,
  1975. uint32 argv[])
  1976. {
  1977. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1978. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  1979. uint32 page_size = os_getpagesize();
  1980. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  1981. WASMRuntimeFrame *prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  1982. uint8 *prev_top = exec_env->wasm_stack.s.top;
  1983. #ifdef BH_PLATFORM_WINDOWS
  1984. const char *exce;
  1985. int result;
  1986. #endif
  1987. bool ret = true;
  1988. /* Check native stack overflow firstly to ensure we have enough
  1989. native stack to run the following codes before actually calling
  1990. the aot function in invokeNative function. */
  1991. RECORD_STACK_USAGE(exec_env, (uint8 *)&exec_env_tls);
  1992. if ((uint8 *)&exec_env_tls < exec_env->native_stack_boundary
  1993. + page_size * (guard_page_count + 1)) {
  1994. wasm_set_exception(module_inst, "native stack overflow");
  1995. return;
  1996. }
  1997. if (exec_env_tls && (exec_env_tls != exec_env)) {
  1998. wasm_set_exception(module_inst, "invalid exec env");
  1999. return;
  2000. }
  2001. if (!os_thread_signal_inited()) {
  2002. wasm_set_exception(module_inst, "thread signal env not inited");
  2003. return;
  2004. }
  2005. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  2006. wasm_runtime_set_exec_env_tls(exec_env);
  2007. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  2008. #ifndef BH_PLATFORM_WINDOWS
  2009. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2010. #else
  2011. __try {
  2012. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2013. } __except (wasm_get_exception(module_inst)
  2014. ? EXCEPTION_EXECUTE_HANDLER
  2015. : EXCEPTION_CONTINUE_SEARCH) {
  2016. /* exception was thrown in wasm_exception_handler */
  2017. ret = false;
  2018. }
  2019. if ((exce = wasm_get_exception(module_inst))
  2020. && strstr(exce, "native stack overflow")) {
  2021. /* After a stack overflow, the stack was left
  2022. in a damaged state, let the CRT repair it */
  2023. result = _resetstkoflw();
  2024. bh_assert(result != 0);
  2025. }
  2026. #endif
  2027. }
  2028. else {
  2029. /* Exception has been set in signal handler before calling longjmp */
  2030. ret = false;
  2031. }
  2032. /* Note: can't check wasm_get_exception(module_inst) here, there may be
  2033. * exception which is not caught by hardware (e.g. uninitialized elements),
  2034. * then the stack-frame is already freed inside wasm_interp_call_wasm */
  2035. if (!ret) {
  2036. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2037. if (wasm_interp_create_call_stack(exec_env)) {
  2038. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  2039. }
  2040. #endif
  2041. /* Restore operand frames */
  2042. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  2043. exec_env->wasm_stack.s.top = prev_top;
  2044. }
  2045. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  2046. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  2047. if (!exec_env->jmpbuf_stack_top) {
  2048. wasm_runtime_set_exec_env_tls(NULL);
  2049. }
  2050. if (!ret) {
  2051. os_sigreturn();
  2052. os_signal_unmask();
  2053. }
  2054. (void)jmpbuf_node_pop;
  2055. }
  2056. #define interp_call_wasm call_wasm_with_hw_bound_check
  2057. #else
  2058. #define interp_call_wasm wasm_interp_call_wasm
  2059. #endif
  2060. bool
  2061. wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function,
  2062. unsigned argc, uint32 argv[])
  2063. {
  2064. WASMModuleInstance *module_inst =
  2065. (WASMModuleInstance *)exec_env->module_inst;
  2066. /* set thread handle and stack boundary */
  2067. wasm_exec_env_set_thread_info(exec_env);
  2068. interp_call_wasm(module_inst, exec_env, function, argc, argv);
  2069. return !wasm_get_exception(module_inst) ? true : false;
  2070. }
  2071. bool
  2072. wasm_create_exec_env_and_call_function(WASMModuleInstance *module_inst,
  2073. WASMFunctionInstance *func,
  2074. unsigned argc, uint32 argv[])
  2075. {
  2076. WASMExecEnv *exec_env = NULL, *existing_exec_env = NULL;
  2077. bool ret;
  2078. #if defined(OS_ENABLE_HW_BOUND_CHECK)
  2079. existing_exec_env = exec_env = wasm_runtime_get_exec_env_tls();
  2080. #elif WASM_ENABLE_THREAD_MGR != 0
  2081. existing_exec_env = exec_env =
  2082. wasm_clusters_search_exec_env((WASMModuleInstanceCommon *)module_inst);
  2083. #endif
  2084. if (!existing_exec_env) {
  2085. if (!(exec_env =
  2086. wasm_exec_env_create((WASMModuleInstanceCommon *)module_inst,
  2087. module_inst->default_wasm_stack_size))) {
  2088. wasm_set_exception(module_inst, "allocate memory failed");
  2089. return false;
  2090. }
  2091. }
  2092. ret = wasm_runtime_call_wasm(exec_env, func, argc, argv);
  2093. /* don't destroy the exec_env if it isn't created in this function */
  2094. if (!existing_exec_env)
  2095. wasm_exec_env_destroy(exec_env);
  2096. return ret;
  2097. }
  2098. #if WASM_ENABLE_PERF_PROFILING != 0
  2099. void
  2100. wasm_dump_perf_profiling(const WASMModuleInstance *module_inst)
  2101. {
  2102. WASMExportFuncInstance *export_func;
  2103. WASMFunctionInstance *func_inst;
  2104. char *func_name;
  2105. uint32 i, j;
  2106. os_printf("Performance profiler data:\n");
  2107. for (i = 0; i < module_inst->e->function_count; i++) {
  2108. func_inst = module_inst->e->functions + i;
  2109. if (func_inst->is_import_func) {
  2110. func_name = func_inst->u.func_import->field_name;
  2111. }
  2112. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2113. else if (func_inst->u.func->field_name) {
  2114. func_name = func_inst->u.func->field_name;
  2115. }
  2116. #endif
  2117. else {
  2118. func_name = NULL;
  2119. for (j = 0; j < module_inst->export_func_count; j++) {
  2120. export_func = module_inst->export_functions + j;
  2121. if (export_func->function == func_inst) {
  2122. func_name = export_func->name;
  2123. break;
  2124. }
  2125. }
  2126. }
  2127. if (func_name)
  2128. os_printf(" func %s, execution time: %.3f ms, execution count: %d "
  2129. "times\n",
  2130. func_name,
  2131. module_inst->e->functions[i].total_exec_time / 1000.0f,
  2132. module_inst->e->functions[i].total_exec_cnt);
  2133. else
  2134. os_printf(" func %d, execution time: %.3f ms, execution count: %d "
  2135. "times\n",
  2136. i, module_inst->e->functions[i].total_exec_time / 1000.0f,
  2137. module_inst->e->functions[i].total_exec_cnt);
  2138. }
  2139. }
  2140. #endif
  2141. uint32
  2142. wasm_module_malloc(WASMModuleInstance *module_inst, uint32 size,
  2143. void **p_native_addr)
  2144. {
  2145. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2146. uint8 *addr = NULL;
  2147. uint32 offset = 0;
  2148. if (!memory) {
  2149. wasm_set_exception(module_inst, "uninitialized memory");
  2150. return 0;
  2151. }
  2152. if (memory->heap_handle) {
  2153. addr = mem_allocator_malloc(memory->heap_handle, size);
  2154. }
  2155. else if (module_inst->e->malloc_function && module_inst->e->free_function) {
  2156. if (!execute_malloc_function(
  2157. module_inst, module_inst->e->malloc_function,
  2158. module_inst->e->retain_function, size, &offset)) {
  2159. return 0;
  2160. }
  2161. /* If we use app's malloc function,
  2162. the default memory may be changed while memory growing */
  2163. memory = wasm_get_default_memory(module_inst);
  2164. addr = offset ? memory->memory_data + offset : NULL;
  2165. }
  2166. if (!addr) {
  2167. if (memory->heap_handle
  2168. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  2169. wasm_runtime_show_app_heap_corrupted_prompt();
  2170. wasm_set_exception(module_inst, "app heap corrupted");
  2171. }
  2172. else {
  2173. LOG_WARNING("warning: allocate %u bytes memory failed", size);
  2174. }
  2175. return 0;
  2176. }
  2177. if (p_native_addr)
  2178. *p_native_addr = addr;
  2179. return (uint32)(addr - memory->memory_data);
  2180. }
  2181. uint32
  2182. wasm_module_realloc(WASMModuleInstance *module_inst, uint32 ptr, uint32 size,
  2183. void **p_native_addr)
  2184. {
  2185. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2186. uint8 *addr = NULL;
  2187. if (!memory) {
  2188. wasm_set_exception(module_inst, "uninitialized memory");
  2189. return 0;
  2190. }
  2191. if (memory->heap_handle) {
  2192. addr = mem_allocator_realloc(
  2193. memory->heap_handle, ptr ? memory->memory_data + ptr : NULL, size);
  2194. }
  2195. /* Only support realloc in WAMR's app heap */
  2196. if (!addr) {
  2197. if (memory->heap_handle
  2198. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  2199. wasm_set_exception(module_inst, "app heap corrupted");
  2200. }
  2201. else {
  2202. wasm_set_exception(module_inst, "out of memory");
  2203. }
  2204. return 0;
  2205. }
  2206. if (p_native_addr)
  2207. *p_native_addr = addr;
  2208. return (uint32)(addr - memory->memory_data);
  2209. }
  2210. void
  2211. wasm_module_free(WASMModuleInstance *module_inst, uint32 ptr)
  2212. {
  2213. if (ptr) {
  2214. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  2215. uint8 *addr;
  2216. if (!memory) {
  2217. return;
  2218. }
  2219. addr = memory->memory_data + ptr;
  2220. if (memory->heap_handle && memory->heap_data <= addr
  2221. && addr < memory->heap_data_end) {
  2222. mem_allocator_free(memory->heap_handle, addr);
  2223. }
  2224. else if (module_inst->e->malloc_function
  2225. && module_inst->e->free_function && memory->memory_data <= addr
  2226. && addr < memory->memory_data_end) {
  2227. execute_free_function(module_inst, module_inst->e->free_function,
  2228. ptr);
  2229. }
  2230. }
  2231. }
  2232. uint32
  2233. wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src,
  2234. uint32 size)
  2235. {
  2236. char *buffer;
  2237. uint32 buffer_offset =
  2238. wasm_module_malloc(module_inst, size, (void **)&buffer);
  2239. if (buffer_offset != 0) {
  2240. buffer = wasm_runtime_addr_app_to_native(
  2241. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  2242. bh_memcpy_s(buffer, size, src, size);
  2243. }
  2244. return buffer_offset;
  2245. }
  2246. #if WASM_ENABLE_REF_TYPES != 0
  2247. bool
  2248. wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx,
  2249. uint32 inc_size, uint32 init_val)
  2250. {
  2251. uint32 total_size, *new_table_data_start, i;
  2252. WASMTableInstance *table_inst;
  2253. if (!inc_size) {
  2254. return true;
  2255. }
  2256. bh_assert(table_idx < module_inst->table_count);
  2257. table_inst = wasm_get_table_inst(module_inst, table_idx);
  2258. if (!table_inst) {
  2259. return false;
  2260. }
  2261. if (inc_size > UINT32_MAX - table_inst->cur_size) {
  2262. return false;
  2263. }
  2264. total_size = table_inst->cur_size + inc_size;
  2265. if (total_size > table_inst->max_size) {
  2266. return false;
  2267. }
  2268. /* fill in */
  2269. new_table_data_start = table_inst->elems + table_inst->cur_size;
  2270. for (i = 0; i < inc_size; ++i) {
  2271. new_table_data_start[i] = init_val;
  2272. }
  2273. table_inst->cur_size = total_size;
  2274. return true;
  2275. }
  2276. #endif /* WASM_ENABLE_REF_TYPES != 0 */
  2277. static bool
  2278. call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2279. uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx)
  2280. {
  2281. WASMModuleInstance *module_inst = NULL;
  2282. WASMTableInstance *table_inst = NULL;
  2283. uint32 func_idx = 0;
  2284. WASMFunctionInstance *func_inst = NULL;
  2285. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  2286. bh_assert(module_inst);
  2287. table_inst = module_inst->tables[tbl_idx];
  2288. if (!table_inst) {
  2289. wasm_set_exception(module_inst, "unknown table");
  2290. goto got_exception;
  2291. }
  2292. if (elem_idx >= table_inst->cur_size) {
  2293. wasm_set_exception(module_inst, "undefined element");
  2294. goto got_exception;
  2295. }
  2296. func_idx = table_inst->elems[elem_idx];
  2297. if (func_idx == NULL_REF) {
  2298. wasm_set_exception(module_inst, "uninitialized element");
  2299. goto got_exception;
  2300. }
  2301. /**
  2302. * we insist to call functions owned by the module itself
  2303. **/
  2304. if (func_idx >= module_inst->e->function_count) {
  2305. wasm_set_exception(module_inst, "unknown function");
  2306. goto got_exception;
  2307. }
  2308. func_inst = module_inst->e->functions + func_idx;
  2309. if (check_type_idx) {
  2310. WASMType *cur_type = module_inst->module->types[type_idx];
  2311. WASMType *cur_func_type;
  2312. if (func_inst->is_import_func)
  2313. cur_func_type = func_inst->u.func_import->func_type;
  2314. else
  2315. cur_func_type = func_inst->u.func->func_type;
  2316. if (cur_type != cur_func_type) {
  2317. wasm_set_exception(module_inst, "indirect call type mismatch");
  2318. goto got_exception;
  2319. }
  2320. }
  2321. interp_call_wasm(module_inst, exec_env, func_inst, argc, argv);
  2322. return !wasm_get_exception(module_inst) ? true : false;
  2323. got_exception:
  2324. return false;
  2325. }
  2326. bool
  2327. wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2328. uint32 argc, uint32 argv[])
  2329. {
  2330. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  2331. }
  2332. #if WASM_ENABLE_THREAD_MGR != 0
  2333. bool
  2334. wasm_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size)
  2335. {
  2336. WASMModuleInstance *module_inst =
  2337. (WASMModuleInstance *)exec_env->module_inst;
  2338. uint32 stack_top_idx = module_inst->module->aux_stack_top_global_index;
  2339. #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0
  2340. /* Check the aux stack space */
  2341. uint32 data_end = module_inst->module->aux_data_end;
  2342. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2343. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  2344. if ((is_stack_before_data && (size > start_offset))
  2345. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  2346. return false;
  2347. #endif
  2348. if (stack_top_idx != (uint32)-1) {
  2349. /* The aux stack top is a wasm global,
  2350. set the initial value for the global */
  2351. uint8 *global_addr =
  2352. module_inst->global_data
  2353. + module_inst->e->globals[stack_top_idx].data_offset;
  2354. *(int32 *)global_addr = start_offset;
  2355. /* The aux stack boundary is a constant value,
  2356. set the value to exec_env */
  2357. exec_env->aux_stack_boundary.boundary = start_offset - size;
  2358. exec_env->aux_stack_bottom.bottom = start_offset;
  2359. return true;
  2360. }
  2361. return false;
  2362. }
  2363. bool
  2364. wasm_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size)
  2365. {
  2366. WASMModuleInstance *module_inst =
  2367. (WASMModuleInstance *)exec_env->module_inst;
  2368. /* The aux stack information is resolved in loader
  2369. and store in module */
  2370. uint32 stack_bottom = module_inst->module->aux_stack_bottom;
  2371. uint32 total_aux_stack_size = module_inst->module->aux_stack_size;
  2372. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  2373. if (start_offset)
  2374. *start_offset = stack_bottom;
  2375. if (size)
  2376. *size = total_aux_stack_size;
  2377. return true;
  2378. }
  2379. return false;
  2380. }
  2381. #endif
  2382. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  2383. void
  2384. wasm_get_module_mem_consumption(const WASMModule *module,
  2385. WASMModuleMemConsumption *mem_conspn)
  2386. {
  2387. uint32 i, size;
  2388. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2389. mem_conspn->module_struct_size = sizeof(WASMModule);
  2390. mem_conspn->types_size = sizeof(WASMType *) * module->type_count;
  2391. for (i = 0; i < module->type_count; i++) {
  2392. WASMType *type = module->types[i];
  2393. size = offsetof(WASMType, types)
  2394. + sizeof(uint8) * (type->param_count + type->result_count);
  2395. mem_conspn->types_size += size;
  2396. }
  2397. mem_conspn->imports_size = sizeof(WASMImport) * module->import_count;
  2398. mem_conspn->functions_size =
  2399. sizeof(WASMFunction *) * module->function_count;
  2400. for (i = 0; i < module->function_count; i++) {
  2401. WASMFunction *func = module->functions[i];
  2402. WASMType *type = func->func_type;
  2403. size = sizeof(WASMFunction) + func->local_count
  2404. + sizeof(uint16) * (type->param_count + func->local_count);
  2405. #if WASM_ENABLE_FAST_INTERP != 0
  2406. size +=
  2407. func->code_compiled_size + sizeof(uint32) * func->const_cell_num;
  2408. #endif
  2409. mem_conspn->functions_size += size;
  2410. }
  2411. mem_conspn->tables_size = sizeof(WASMTable) * module->table_count;
  2412. mem_conspn->memories_size = sizeof(WASMMemory) * module->memory_count;
  2413. mem_conspn->globals_size = sizeof(WASMGlobal) * module->global_count;
  2414. mem_conspn->exports_size = sizeof(WASMExport) * module->export_count;
  2415. mem_conspn->table_segs_size =
  2416. sizeof(WASMTableSeg) * module->table_seg_count;
  2417. for (i = 0; i < module->table_seg_count; i++) {
  2418. WASMTableSeg *table_seg = &module->table_segments[i];
  2419. mem_conspn->tables_size += sizeof(uint32) * table_seg->function_count;
  2420. }
  2421. mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count;
  2422. for (i = 0; i < module->data_seg_count; i++) {
  2423. mem_conspn->data_segs_size += sizeof(WASMDataSeg);
  2424. }
  2425. if (module->const_str_list) {
  2426. StringNode *node = module->const_str_list, *node_next;
  2427. while (node) {
  2428. node_next = node->next;
  2429. mem_conspn->const_strs_size +=
  2430. sizeof(StringNode) + strlen(node->str) + 1;
  2431. node = node_next;
  2432. }
  2433. }
  2434. mem_conspn->total_size += mem_conspn->module_struct_size;
  2435. mem_conspn->total_size += mem_conspn->types_size;
  2436. mem_conspn->total_size += mem_conspn->imports_size;
  2437. mem_conspn->total_size += mem_conspn->functions_size;
  2438. mem_conspn->total_size += mem_conspn->tables_size;
  2439. mem_conspn->total_size += mem_conspn->memories_size;
  2440. mem_conspn->total_size += mem_conspn->globals_size;
  2441. mem_conspn->total_size += mem_conspn->exports_size;
  2442. mem_conspn->total_size += mem_conspn->table_segs_size;
  2443. mem_conspn->total_size += mem_conspn->data_segs_size;
  2444. mem_conspn->total_size += mem_conspn->const_strs_size;
  2445. }
  2446. void
  2447. wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst,
  2448. WASMModuleInstMemConsumption *mem_conspn)
  2449. {
  2450. uint32 i, size;
  2451. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2452. mem_conspn->module_inst_struct_size = (uint8 *)module_inst->e
  2453. - (uint8 *)module_inst
  2454. + sizeof(WASMModuleInstanceExtra);
  2455. mem_conspn->memories_size =
  2456. sizeof(WASMMemoryInstance *) * module_inst->memory_count;
  2457. for (i = 0; i < module_inst->memory_count; i++) {
  2458. WASMMemoryInstance *memory = module_inst->memories[i];
  2459. size = memory->num_bytes_per_page * memory->cur_page_count;
  2460. mem_conspn->memories_size += size;
  2461. mem_conspn->app_heap_size += memory->heap_data_end - memory->heap_data;
  2462. /* size of app heap structure */
  2463. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  2464. /* Module instance structures have been appened into the end of
  2465. module instance */
  2466. }
  2467. mem_conspn->tables_size =
  2468. sizeof(WASMTableInstance *) * module_inst->table_count;
  2469. /* Table instance structures and table elements have been appened into
  2470. the end of module instance */
  2471. mem_conspn->functions_size =
  2472. sizeof(WASMFunctionInstance) * module_inst->e->function_count;
  2473. mem_conspn->globals_size =
  2474. sizeof(WASMGlobalInstance) * module_inst->e->global_count;
  2475. /* Global data has been appened into the end of module instance */
  2476. mem_conspn->exports_size =
  2477. sizeof(WASMExportFuncInstance) * module_inst->export_func_count;
  2478. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  2479. mem_conspn->total_size += mem_conspn->memories_size;
  2480. mem_conspn->total_size += mem_conspn->functions_size;
  2481. mem_conspn->total_size += mem_conspn->tables_size;
  2482. mem_conspn->total_size += mem_conspn->globals_size;
  2483. mem_conspn->total_size += mem_conspn->exports_size;
  2484. }
  2485. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  2486. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  2487. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2488. bool
  2489. wasm_interp_create_call_stack(struct WASMExecEnv *exec_env)
  2490. {
  2491. WASMModuleInstance *module_inst =
  2492. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2493. WASMInterpFrame *first_frame,
  2494. *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  2495. uint32 n = 0;
  2496. /* count frames includes a function */
  2497. first_frame = cur_frame;
  2498. while (cur_frame) {
  2499. if (cur_frame->function) {
  2500. n++;
  2501. }
  2502. cur_frame = cur_frame->prev_frame;
  2503. }
  2504. /* release previous stack frames and create new ones */
  2505. if (!bh_vector_destroy(module_inst->frames)
  2506. || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame),
  2507. false)) {
  2508. return false;
  2509. }
  2510. cur_frame = first_frame;
  2511. n = 0;
  2512. while (cur_frame) {
  2513. WASMCApiFrame frame = { 0 };
  2514. WASMFunctionInstance *func_inst = cur_frame->function;
  2515. const char *func_name = NULL;
  2516. const uint8 *func_code_base = NULL;
  2517. if (!func_inst) {
  2518. cur_frame = cur_frame->prev_frame;
  2519. continue;
  2520. }
  2521. /* place holder, will overwrite it in wasm_c_api */
  2522. frame.instance = module_inst;
  2523. frame.module_offset = 0;
  2524. frame.func_index = (uint32)(func_inst - module_inst->e->functions);
  2525. func_code_base = wasm_get_func_code(func_inst);
  2526. if (!cur_frame->ip || !func_code_base) {
  2527. frame.func_offset = 0;
  2528. }
  2529. else {
  2530. frame.func_offset = (uint32)(cur_frame->ip - func_code_base);
  2531. }
  2532. /* look for the function name */
  2533. if (func_inst->is_import_func) {
  2534. func_name = func_inst->u.func_import->field_name;
  2535. }
  2536. else {
  2537. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2538. func_name = func_inst->u.func->field_name;
  2539. #endif
  2540. /* if custom name section is not generated,
  2541. search symbols from export table */
  2542. if (!func_name) {
  2543. uint32 i;
  2544. for (i = 0; i < module_inst->export_func_count; i++) {
  2545. WASMExportFuncInstance *export_func =
  2546. module_inst->export_functions + i;
  2547. if (export_func->function == func_inst) {
  2548. func_name = export_func->name;
  2549. break;
  2550. }
  2551. }
  2552. }
  2553. }
  2554. frame.func_name_wp = func_name;
  2555. if (!bh_vector_append(module_inst->frames, &frame)) {
  2556. bh_vector_destroy(module_inst->frames);
  2557. return false;
  2558. }
  2559. cur_frame = cur_frame->prev_frame;
  2560. n++;
  2561. }
  2562. return true;
  2563. }
  2564. #define PRINT_OR_DUMP() \
  2565. do { \
  2566. total_len += \
  2567. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  2568. if ((!print) && buf && (len == 0)) { \
  2569. return total_len; \
  2570. } \
  2571. } while (0)
  2572. uint32
  2573. wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf,
  2574. uint32 len)
  2575. {
  2576. WASMModuleInstance *module_inst =
  2577. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  2578. uint32 n = 0, total_len = 0, total_frames;
  2579. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  2580. * will be truncated */
  2581. char line_buf[256];
  2582. if (!module_inst->frames) {
  2583. return 0;
  2584. }
  2585. total_frames = (uint32)bh_vector_size(module_inst->frames);
  2586. if (total_frames == 0) {
  2587. return 0;
  2588. }
  2589. snprintf(line_buf, sizeof(line_buf), "\n");
  2590. PRINT_OR_DUMP();
  2591. while (n < total_frames) {
  2592. WASMCApiFrame frame = { 0 };
  2593. uint32 line_length, i;
  2594. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  2595. return 0;
  2596. }
  2597. /* function name not exported, print number instead */
  2598. if (frame.func_name_wp == NULL) {
  2599. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d $f%d\n",
  2600. n, frame.func_index);
  2601. }
  2602. else {
  2603. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d %s\n", n,
  2604. frame.func_name_wp);
  2605. }
  2606. if (line_length >= sizeof(line_buf)) {
  2607. uint32 line_buffer_len = sizeof(line_buf);
  2608. /* If line too long, ensure the last character is '\n' */
  2609. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  2610. line_buf[i] = '.';
  2611. }
  2612. line_buf[line_buffer_len - 2] = '\n';
  2613. }
  2614. PRINT_OR_DUMP();
  2615. n++;
  2616. }
  2617. snprintf(line_buf, sizeof(line_buf), "\n");
  2618. PRINT_OR_DUMP();
  2619. return total_len + 1;
  2620. }
  2621. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  2622. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  2623. || WASM_ENABLE_WAMR_COMPILER != 0
  2624. void
  2625. jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  2626. {
  2627. if (id != EXCE_ALREADY_THROWN)
  2628. wasm_set_exception_with_id(module_inst, id);
  2629. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2630. wasm_runtime_access_exce_check_guard_page();
  2631. #endif
  2632. }
  2633. bool
  2634. jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str,
  2635. uint32 app_buf_addr, uint32 app_buf_size,
  2636. void **p_native_addr)
  2637. {
  2638. bool ret = wasm_check_app_addr_and_convert(
  2639. module_inst, is_str, app_buf_addr, app_buf_size, p_native_addr);
  2640. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2641. if (!ret)
  2642. wasm_runtime_access_exce_check_guard_page();
  2643. #endif
  2644. return ret;
  2645. }
  2646. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  2647. || WASM_ENABLE_WAMR_COMPILER != 0 */
  2648. #if WASM_ENABLE_FAST_JIT != 0
  2649. bool
  2650. fast_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2651. uint32 type_idx, uint32 argc, uint32 *argv)
  2652. {
  2653. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, true,
  2654. type_idx);
  2655. }
  2656. #endif /* end of WASM_ENABLE_FAST_JIT != 0 */
  2657. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  2658. bool
  2659. llvm_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  2660. uint32 argc, uint32 *argv)
  2661. {
  2662. bool ret;
  2663. #if WASM_ENABLE_JIT != 0
  2664. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  2665. return aot_call_indirect(exec_env, tbl_idx, elem_idx, argc, argv);
  2666. }
  2667. #endif
  2668. ret = call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  2669. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2670. if (!ret)
  2671. wasm_runtime_access_exce_check_guard_page();
  2672. #endif
  2673. return ret;
  2674. }
  2675. bool
  2676. llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  2677. uint32 *argv)
  2678. {
  2679. WASMModuleInstance *module_inst;
  2680. WASMModule *module;
  2681. uint32 *func_type_indexes;
  2682. uint32 func_type_idx;
  2683. WASMType *func_type;
  2684. void *func_ptr;
  2685. WASMFunctionImport *import_func;
  2686. CApiFuncImport *c_api_func_import = NULL;
  2687. const char *signature;
  2688. void *attachment;
  2689. char buf[96];
  2690. bool ret = false;
  2691. #if WASM_ENABLE_JIT != 0
  2692. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  2693. return aot_invoke_native(exec_env, func_idx, argc, argv);
  2694. }
  2695. #endif
  2696. module_inst = (WASMModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  2697. module = module_inst->module;
  2698. func_type_indexes = module_inst->func_type_indexes;
  2699. func_type_idx = func_type_indexes[func_idx];
  2700. func_type = module->types[func_type_idx];
  2701. func_ptr = module_inst->func_ptrs[func_idx];
  2702. bh_assert(func_idx < module->import_function_count);
  2703. import_func = &module->import_functions[func_idx].u.function;
  2704. if (import_func->call_conv_wasm_c_api) {
  2705. if (module_inst->e->c_api_func_imports) {
  2706. c_api_func_import = module_inst->e->c_api_func_imports + func_idx;
  2707. func_ptr = c_api_func_import->func_ptr_linked;
  2708. }
  2709. else {
  2710. c_api_func_import = NULL;
  2711. func_ptr = NULL;
  2712. }
  2713. }
  2714. if (!func_ptr) {
  2715. snprintf(buf, sizeof(buf),
  2716. "failed to call unlinked import function (%s, %s)",
  2717. import_func->module_name, import_func->field_name);
  2718. wasm_set_exception(module_inst, buf);
  2719. goto fail;
  2720. }
  2721. attachment = import_func->attachment;
  2722. if (import_func->call_conv_wasm_c_api) {
  2723. ret = wasm_runtime_invoke_c_api_native(
  2724. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  2725. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  2726. }
  2727. else if (!import_func->call_conv_raw) {
  2728. signature = import_func->signature;
  2729. ret =
  2730. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  2731. attachment, argv, argc, argv);
  2732. }
  2733. else {
  2734. signature = import_func->signature;
  2735. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  2736. signature, attachment, argv, argc,
  2737. argv);
  2738. }
  2739. fail:
  2740. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2741. if (!ret)
  2742. wasm_runtime_access_exce_check_guard_page();
  2743. #endif
  2744. return ret;
  2745. }
  2746. #if WASM_ENABLE_BULK_MEMORY != 0
  2747. bool
  2748. llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index,
  2749. uint32 offset, uint32 len, uint32 dst)
  2750. {
  2751. WASMMemoryInstance *memory_inst;
  2752. WASMModule *module;
  2753. uint8 *data = NULL;
  2754. uint8 *maddr;
  2755. uint64 seg_len = 0;
  2756. #if WASM_ENABLE_JIT != 0
  2757. if (Wasm_Module_AoT == module_inst->module_type) {
  2758. return aot_memory_init(module_inst, seg_index, offset, len, dst);
  2759. }
  2760. #endif
  2761. memory_inst = wasm_get_default_memory(module_inst);
  2762. module = module_inst->module;
  2763. seg_len = module->data_segments[seg_index]->data_length;
  2764. data = module->data_segments[seg_index]->data;
  2765. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  2766. dst, len))
  2767. return false;
  2768. if ((uint64)offset + (uint64)len > seg_len) {
  2769. wasm_set_exception(module_inst, "out of bounds memory access");
  2770. return false;
  2771. }
  2772. maddr = wasm_runtime_addr_app_to_native(
  2773. (WASMModuleInstanceCommon *)module_inst, dst);
  2774. bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len);
  2775. return true;
  2776. }
  2777. bool
  2778. llvm_jit_data_drop(WASMModuleInstance *module_inst, uint32 seg_index)
  2779. {
  2780. #if WASM_ENABLE_JIT != 0
  2781. if (Wasm_Module_AoT == module_inst->module_type) {
  2782. return aot_data_drop(module_inst, seg_index);
  2783. }
  2784. #endif
  2785. module_inst->module->data_segments[seg_index]->data_length = 0;
  2786. /* Currently we can't free the dropped data segment
  2787. as they are stored in wasm bytecode */
  2788. return true;
  2789. }
  2790. #endif /* end of WASM_ENABLE_BULK_MEMORY != 0 */
  2791. #if WASM_ENABLE_REF_TYPES != 0
  2792. void
  2793. llvm_jit_drop_table_seg(WASMModuleInstance *module_inst, uint32 tbl_seg_idx)
  2794. {
  2795. WASMTableSeg *tbl_segs;
  2796. #if WASM_ENABLE_JIT != 0
  2797. if (Wasm_Module_AoT == module_inst->module_type) {
  2798. return aot_drop_table_seg(module_inst, tbl_seg_idx);
  2799. }
  2800. #endif
  2801. tbl_segs = module_inst->module->table_segments;
  2802. tbl_segs[tbl_seg_idx].is_dropped = true;
  2803. }
  2804. void
  2805. llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx,
  2806. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  2807. uint32 dst_offset)
  2808. {
  2809. WASMTableInstance *tbl_inst;
  2810. WASMTableSeg *tbl_seg;
  2811. #if WASM_ENABLE_JIT != 0
  2812. if (Wasm_Module_AoT == module_inst->module_type) {
  2813. return aot_table_init(module_inst, tbl_idx, tbl_seg_idx, length,
  2814. src_offset, dst_offset);
  2815. }
  2816. #endif
  2817. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  2818. tbl_seg = module_inst->module->table_segments + tbl_seg_idx;
  2819. bh_assert(tbl_inst);
  2820. bh_assert(tbl_seg);
  2821. if (!length) {
  2822. return;
  2823. }
  2824. if (length + src_offset > tbl_seg->function_count
  2825. || dst_offset + length > tbl_inst->cur_size) {
  2826. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2827. return;
  2828. }
  2829. if (tbl_seg->is_dropped) {
  2830. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2831. return;
  2832. }
  2833. if (!wasm_elem_is_passive(tbl_seg->mode)) {
  2834. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2835. return;
  2836. }
  2837. bh_memcpy_s((uint8 *)tbl_inst + offsetof(WASMTableInstance, elems)
  2838. + dst_offset * sizeof(uint32),
  2839. (uint32)sizeof(uint32) * (tbl_inst->cur_size - dst_offset),
  2840. tbl_seg->func_indexes + src_offset,
  2841. (uint32)(length * sizeof(uint32)));
  2842. }
  2843. void
  2844. llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx,
  2845. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  2846. uint32 dst_offset)
  2847. {
  2848. WASMTableInstance *src_tbl_inst;
  2849. WASMTableInstance *dst_tbl_inst;
  2850. #if WASM_ENABLE_JIT != 0
  2851. if (Wasm_Module_AoT == module_inst->module_type) {
  2852. aot_table_copy(module_inst, src_tbl_idx, dst_tbl_idx, length,
  2853. src_offset, dst_offset);
  2854. return;
  2855. }
  2856. #endif
  2857. src_tbl_inst = wasm_get_table_inst(module_inst, src_tbl_idx);
  2858. dst_tbl_inst = wasm_get_table_inst(module_inst, dst_tbl_idx);
  2859. bh_assert(src_tbl_inst);
  2860. bh_assert(dst_tbl_inst);
  2861. if ((uint64)dst_offset + length > dst_tbl_inst->cur_size
  2862. || (uint64)src_offset + length > src_tbl_inst->cur_size) {
  2863. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2864. return;
  2865. }
  2866. /* if src_offset >= dst_offset, copy from front to back */
  2867. /* if src_offset < dst_offset, copy from back to front */
  2868. /* merge all together */
  2869. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems)
  2870. + sizeof(uint32) * dst_offset,
  2871. (uint32)sizeof(uint32) * (dst_tbl_inst->cur_size - dst_offset),
  2872. (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems)
  2873. + sizeof(uint32) * src_offset,
  2874. (uint32)sizeof(uint32) * length);
  2875. }
  2876. void
  2877. llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx,
  2878. uint32 length, uint32 val, uint32 data_offset)
  2879. {
  2880. WASMTableInstance *tbl_inst;
  2881. #if WASM_ENABLE_JIT != 0
  2882. if (Wasm_Module_AoT == module_inst->module_type) {
  2883. aot_table_fill(module_inst, tbl_idx, length, val, data_offset);
  2884. return;
  2885. }
  2886. #endif
  2887. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  2888. bh_assert(tbl_inst);
  2889. if (data_offset + length > tbl_inst->cur_size) {
  2890. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2891. return;
  2892. }
  2893. for (; length != 0; data_offset++, length--) {
  2894. tbl_inst->elems[data_offset] = val;
  2895. }
  2896. }
  2897. uint32
  2898. llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx,
  2899. uint32 inc_size, uint32 init_val)
  2900. {
  2901. WASMTableInstance *tbl_inst;
  2902. uint32 i, orig_size, total_size;
  2903. #if WASM_ENABLE_JIT != 0
  2904. if (Wasm_Module_AoT == module_inst->module_type) {
  2905. return aot_table_grow(module_inst, tbl_idx, inc_size, init_val);
  2906. }
  2907. #endif
  2908. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  2909. if (!tbl_inst) {
  2910. return (uint32)-1;
  2911. }
  2912. orig_size = tbl_inst->cur_size;
  2913. if (!inc_size) {
  2914. return orig_size;
  2915. }
  2916. if (tbl_inst->cur_size > UINT32_MAX - inc_size) { /* integer overflow */
  2917. return (uint32)-1;
  2918. }
  2919. total_size = tbl_inst->cur_size + inc_size;
  2920. if (total_size > tbl_inst->max_size) {
  2921. return (uint32)-1;
  2922. }
  2923. /* fill in */
  2924. for (i = 0; i < inc_size; ++i) {
  2925. tbl_inst->elems[tbl_inst->cur_size + i] = init_val;
  2926. }
  2927. tbl_inst->cur_size = total_size;
  2928. return orig_size;
  2929. }
  2930. #endif /* end of WASM_ENABLE_REF_TYPES != 0 */
  2931. #if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0
  2932. bool
  2933. llvm_jit_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  2934. {
  2935. WASMModuleInstance *module_inst;
  2936. WASMInterpFrame *frame;
  2937. uint32 size;
  2938. #if WASM_ENABLE_JIT != 0
  2939. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  2940. return aot_alloc_frame(exec_env, func_index);
  2941. }
  2942. #endif
  2943. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  2944. size = wasm_interp_interp_frame_size(0);
  2945. frame = wasm_exec_env_alloc_wasm_frame(exec_env, size);
  2946. if (!frame) {
  2947. wasm_set_exception(module_inst, "wasm operand stack overflow");
  2948. return false;
  2949. }
  2950. frame->function = module_inst->e->functions + func_index;
  2951. frame->ip = NULL;
  2952. frame->sp = frame->lp;
  2953. #if WASM_ENABLE_PERF_PROFILING != 0
  2954. frame->time_started = os_time_get_boot_microsecond();
  2955. #endif
  2956. frame->prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  2957. wasm_exec_env_set_cur_frame(exec_env, frame);
  2958. return true;
  2959. }
  2960. void
  2961. llvm_jit_free_frame(WASMExecEnv *exec_env)
  2962. {
  2963. WASMInterpFrame *frame;
  2964. WASMInterpFrame *prev_frame;
  2965. #if WASM_ENABLE_JIT != 0
  2966. if (Wasm_Module_AoT == exec_env->module_inst->module_type) {
  2967. aot_free_frame(exec_env);
  2968. return;
  2969. }
  2970. #endif
  2971. frame = wasm_exec_env_get_cur_frame(exec_env);
  2972. prev_frame = frame->prev_frame;
  2973. #if WASM_ENABLE_PERF_PROFILING != 0
  2974. if (frame->function) {
  2975. frame->function->total_exec_time +=
  2976. os_time_get_boot_microsecond() - frame->time_started;
  2977. frame->function->total_exec_cnt++;
  2978. }
  2979. #endif
  2980. wasm_exec_env_free_wasm_frame(exec_env, frame);
  2981. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  2982. }
  2983. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 \
  2984. || WASM_ENABLE_PERF_PROFILING != 0 */
  2985. #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
  2986. #if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
  2987. void
  2988. wasm_propagate_wasi_args(WASMModule *module)
  2989. {
  2990. if (!module->import_count)
  2991. return;
  2992. bh_assert(&module->import_module_list_head);
  2993. WASMRegisteredModule *node =
  2994. bh_list_first_elem(&module->import_module_list_head);
  2995. while (node) {
  2996. WASIArguments *wasi_args_impt_mod =
  2997. &((WASMModule *)(node->module))->wasi_args;
  2998. bh_assert(wasi_args_impt_mod);
  2999. bh_memcpy_s(wasi_args_impt_mod, sizeof(WASIArguments),
  3000. &module->wasi_args, sizeof(WASIArguments));
  3001. node = bh_list_elem_next(node);
  3002. }
  3003. }
  3004. #endif