wasm_runtime.c 115 KB

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