wasm_runtime.c 113 KB

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