aot_runtime.c 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "aot_runtime.h"
  6. #include "bh_log.h"
  7. #include "mem_alloc.h"
  8. #include "../common/wasm_runtime_common.h"
  9. #include "../interpreter/wasm_runtime.h"
  10. #if WASM_ENABLE_SHARED_MEMORY != 0
  11. #include "../common/wasm_shared_memory.h"
  12. #endif
  13. #if WASM_ENABLE_THREAD_MGR != 0
  14. #include "../libraries/thread-mgr/thread_manager.h"
  15. #endif
  16. /*
  17. * Note: These offsets need to match the values hardcoded in
  18. * AoT compilation code: aot_create_func_context, check_suspend_flags.
  19. */
  20. bh_static_assert(offsetof(WASMExecEnv, module_inst) == 2 * sizeof(uintptr_t));
  21. bh_static_assert(offsetof(WASMExecEnv, argv_buf) == 3 * sizeof(uintptr_t));
  22. bh_static_assert(offsetof(WASMExecEnv, native_stack_boundary)
  23. == 4 * sizeof(uintptr_t));
  24. bh_static_assert(offsetof(WASMExecEnv, suspend_flags) == 5 * sizeof(uintptr_t));
  25. bh_static_assert(offsetof(WASMExecEnv, aux_stack_boundary)
  26. == 6 * sizeof(uintptr_t));
  27. bh_static_assert(offsetof(WASMExecEnv, aux_stack_bottom)
  28. == 7 * sizeof(uintptr_t));
  29. bh_static_assert(offsetof(WASMExecEnv, native_symbol) == 8 * sizeof(uintptr_t));
  30. bh_static_assert(offsetof(WASMExecEnv, native_stack_top_min)
  31. == 9 * sizeof(uintptr_t));
  32. bh_static_assert(offsetof(AOTModuleInstance, memories) == 1 * sizeof(uint64));
  33. bh_static_assert(offsetof(AOTModuleInstance, func_ptrs) == 5 * sizeof(uint64));
  34. bh_static_assert(offsetof(AOTModuleInstance, func_type_indexes)
  35. == 6 * sizeof(uint64));
  36. bh_static_assert(offsetof(AOTModuleInstance, cur_exception)
  37. == 13 * sizeof(uint64));
  38. bh_static_assert(offsetof(AOTModuleInstance, global_table_data)
  39. == 13 * sizeof(uint64) + 128 + 11 * sizeof(uint64));
  40. static void
  41. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  42. {
  43. if (error_buf != NULL) {
  44. snprintf(error_buf, error_buf_size, "AOT module instantiate failed: %s",
  45. string);
  46. }
  47. }
  48. static void
  49. set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...)
  50. {
  51. va_list args;
  52. char buf[128];
  53. if (error_buf != NULL) {
  54. va_start(args, format);
  55. vsnprintf(buf, sizeof(buf), format, args);
  56. va_end(args);
  57. snprintf(error_buf, error_buf_size, "AOT module instantiate failed: %s",
  58. buf);
  59. }
  60. }
  61. static void *
  62. runtime_malloc(uint64 size, char *error_buf, uint32 error_buf_size)
  63. {
  64. void *mem;
  65. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  66. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  67. return NULL;
  68. }
  69. memset(mem, 0, (uint32)size);
  70. return mem;
  71. }
  72. static bool
  73. check_global_init_expr(const AOTModule *module, uint32 global_index,
  74. char *error_buf, uint32 error_buf_size)
  75. {
  76. if (global_index >= module->import_global_count + module->global_count) {
  77. set_error_buf_v(error_buf, error_buf_size, "unknown global %d",
  78. global_index);
  79. return false;
  80. }
  81. /**
  82. * Currently, constant expressions occurring as initializers of
  83. * globals are further constrained in that contained global.get
  84. * instructions are only allowed to refer to imported globals.
  85. *
  86. * And initializer expression cannot reference a mutable global.
  87. */
  88. if (global_index >= module->import_global_count
  89. || module->import_globals->is_mutable) {
  90. set_error_buf(error_buf, error_buf_size,
  91. "constant expression required");
  92. return false;
  93. }
  94. return true;
  95. }
  96. static void
  97. init_global_data(uint8 *global_data, uint8 type, WASMValue *initial_value)
  98. {
  99. switch (type) {
  100. case VALUE_TYPE_I32:
  101. case VALUE_TYPE_F32:
  102. #if WASM_ENABLE_REF_TYPES != 0
  103. case VALUE_TYPE_FUNCREF:
  104. case VALUE_TYPE_EXTERNREF:
  105. #endif
  106. *(int32 *)global_data = initial_value->i32;
  107. break;
  108. case VALUE_TYPE_I64:
  109. case VALUE_TYPE_F64:
  110. bh_memcpy_s(global_data, sizeof(int64), &initial_value->i64,
  111. sizeof(int64));
  112. break;
  113. #if WASM_ENABLE_SIMD != 0
  114. case VALUE_TYPE_V128:
  115. bh_memcpy_s(global_data, sizeof(V128), &initial_value->v128,
  116. sizeof(V128));
  117. break;
  118. #endif
  119. default:
  120. bh_assert(0);
  121. }
  122. }
  123. static bool
  124. global_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  125. char *error_buf, uint32 error_buf_size)
  126. {
  127. uint32 i;
  128. InitializerExpression *init_expr;
  129. uint8 *p = module_inst->global_data;
  130. AOTImportGlobal *import_global = module->import_globals;
  131. AOTGlobal *global = module->globals;
  132. /* Initialize import global data */
  133. for (i = 0; i < module->import_global_count; i++, import_global++) {
  134. bh_assert(import_global->data_offset
  135. == (uint32)(p - module_inst->global_data));
  136. init_global_data(p, import_global->type,
  137. &import_global->global_data_linked);
  138. p += import_global->size;
  139. }
  140. /* Initialize defined global data */
  141. for (i = 0; i < module->global_count; i++, global++) {
  142. bh_assert(global->data_offset
  143. == (uint32)(p - module_inst->global_data));
  144. init_expr = &global->init_expr;
  145. switch (init_expr->init_expr_type) {
  146. case INIT_EXPR_TYPE_GET_GLOBAL:
  147. {
  148. if (!check_global_init_expr(module, init_expr->u.global_index,
  149. error_buf, error_buf_size)) {
  150. return false;
  151. }
  152. init_global_data(
  153. p, global->type,
  154. &module->import_globals[init_expr->u.global_index]
  155. .global_data_linked);
  156. break;
  157. }
  158. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  159. case INIT_EXPR_TYPE_REFNULL_CONST:
  160. {
  161. *(uint32 *)p = NULL_REF;
  162. break;
  163. }
  164. #endif
  165. default:
  166. {
  167. init_global_data(p, global->type, &init_expr->u);
  168. break;
  169. }
  170. }
  171. p += global->size;
  172. }
  173. bh_assert(module_inst->global_data_size
  174. == (uint32)(p - module_inst->global_data));
  175. return true;
  176. }
  177. static bool
  178. tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  179. AOTTableInstance *first_tbl_inst, char *error_buf,
  180. uint32 error_buf_size)
  181. {
  182. uint32 i, global_index, global_data_offset, base_offset, length;
  183. uint64 total_size;
  184. AOTTableInitData *table_seg;
  185. AOTTableInstance *tbl_inst = first_tbl_inst;
  186. total_size = (uint64)sizeof(WASMTableInstance *) * module_inst->table_count;
  187. if (total_size > 0
  188. && !(module_inst->tables =
  189. runtime_malloc(total_size, error_buf, error_buf_size))) {
  190. return false;
  191. }
  192. /*
  193. * treat import table like a local one until we enable module linking
  194. * in AOT mode
  195. */
  196. for (i = 0; i != module_inst->table_count; ++i) {
  197. if (i < module->import_table_count) {
  198. AOTImportTable *import_table = module->import_tables + i;
  199. tbl_inst->cur_size = import_table->table_init_size;
  200. tbl_inst->max_size =
  201. aot_get_imp_tbl_data_slots(import_table, false);
  202. }
  203. else {
  204. AOTTable *table = module->tables + (i - module->import_table_count);
  205. tbl_inst->cur_size = table->table_init_size;
  206. tbl_inst->max_size = aot_get_tbl_data_slots(table, false);
  207. }
  208. /* Set all elements to -1 to mark them as uninitialized elements */
  209. memset(tbl_inst->elems, 0xff, sizeof(uint32) * tbl_inst->max_size);
  210. module_inst->tables[i] = tbl_inst;
  211. tbl_inst = (AOTTableInstance *)((uint8 *)tbl_inst
  212. + offsetof(AOTTableInstance, elems)
  213. + sizeof(uint32) * tbl_inst->max_size);
  214. }
  215. /* fill table with element segment content */
  216. for (i = 0; i < module->table_init_data_count; i++) {
  217. table_seg = module->table_init_data_list[i];
  218. #if WASM_ENABLE_REF_TYPES != 0
  219. if (!wasm_elem_is_active(table_seg->mode))
  220. continue;
  221. #endif
  222. bh_assert(table_seg->table_index < module_inst->table_count);
  223. tbl_inst = module_inst->tables[table_seg->table_index];
  224. bh_assert(tbl_inst);
  225. #if WASM_ENABLE_REF_TYPES != 0
  226. bh_assert(
  227. table_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  228. || table_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL
  229. || table_seg->offset.init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST
  230. || table_seg->offset.init_expr_type
  231. == INIT_EXPR_TYPE_REFNULL_CONST);
  232. #else
  233. bh_assert(table_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  234. || table_seg->offset.init_expr_type
  235. == INIT_EXPR_TYPE_GET_GLOBAL);
  236. #endif
  237. /* Resolve table data base offset */
  238. if (table_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  239. global_index = table_seg->offset.u.global_index;
  240. if (!check_global_init_expr(module, global_index, error_buf,
  241. error_buf_size)) {
  242. return false;
  243. }
  244. if (global_index < module->import_global_count)
  245. global_data_offset =
  246. module->import_globals[global_index].data_offset;
  247. else
  248. global_data_offset =
  249. module->globals[global_index - module->import_global_count]
  250. .data_offset;
  251. base_offset =
  252. *(uint32 *)(module_inst->global_data + global_data_offset);
  253. }
  254. else
  255. base_offset = (uint32)table_seg->offset.u.i32;
  256. /* Copy table data */
  257. /* base_offset only since length might negative */
  258. if (base_offset > tbl_inst->cur_size) {
  259. #if WASM_ENABLE_REF_TYPES != 0
  260. set_error_buf(error_buf, error_buf_size,
  261. "out of bounds table access");
  262. #else
  263. set_error_buf(error_buf, error_buf_size,
  264. "elements segment does not fit");
  265. #endif
  266. return false;
  267. }
  268. /* base_offset + length(could be zero) */
  269. length = table_seg->func_index_count;
  270. if (base_offset + length > tbl_inst->cur_size) {
  271. #if WASM_ENABLE_REF_TYPES != 0
  272. set_error_buf(error_buf, error_buf_size,
  273. "out of bounds table access");
  274. #else
  275. set_error_buf(error_buf, error_buf_size,
  276. "elements segment does not fit");
  277. #endif
  278. return false;
  279. }
  280. /**
  281. * Check function index in the current module inst for now.
  282. * will check the linked table inst owner in future
  283. */
  284. bh_memcpy_s(tbl_inst->elems + base_offset,
  285. (tbl_inst->max_size - base_offset) * sizeof(uint32),
  286. table_seg->func_indexes, length * sizeof(uint32));
  287. }
  288. return true;
  289. }
  290. static void
  291. memories_deinstantiate(AOTModuleInstance *module_inst)
  292. {
  293. uint32 i;
  294. AOTMemoryInstance *memory_inst;
  295. for (i = 0; i < module_inst->memory_count; i++) {
  296. memory_inst = module_inst->memories[i];
  297. if (memory_inst) {
  298. #if WASM_ENABLE_SHARED_MEMORY != 0
  299. if (memory_inst->is_shared) {
  300. int32 ref_count = shared_memory_dec_reference(
  301. (WASMModuleCommon *)module_inst->module);
  302. bh_assert(ref_count >= 0);
  303. /* if the reference count is not zero,
  304. don't free the memory */
  305. if (ref_count > 0)
  306. continue;
  307. }
  308. #endif
  309. if (memory_inst->heap_handle) {
  310. mem_allocator_destroy(memory_inst->heap_handle);
  311. wasm_runtime_free(memory_inst->heap_handle);
  312. }
  313. if (memory_inst->memory_data) {
  314. #ifndef OS_ENABLE_HW_BOUND_CHECK
  315. wasm_runtime_free(memory_inst->memory_data);
  316. #else
  317. #ifdef BH_PLATFORM_WINDOWS
  318. os_mem_decommit(memory_inst->memory_data,
  319. memory_inst->num_bytes_per_page
  320. * memory_inst->cur_page_count);
  321. #endif
  322. os_munmap(memory_inst->memory_data, 8 * (uint64)BH_GB);
  323. #endif
  324. }
  325. }
  326. }
  327. wasm_runtime_free(module_inst->memories);
  328. }
  329. static AOTMemoryInstance *
  330. memory_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  331. AOTMemoryInstance *memory_inst, AOTMemory *memory,
  332. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  333. {
  334. void *heap_handle;
  335. uint32 num_bytes_per_page = memory->num_bytes_per_page;
  336. uint32 init_page_count = memory->mem_init_page_count;
  337. uint32 max_page_count = memory->mem_max_page_count;
  338. uint32 inc_page_count, aux_heap_base, global_idx;
  339. uint32 bytes_of_last_page, bytes_to_page_end;
  340. uint32 heap_offset = num_bytes_per_page * init_page_count;
  341. uint64 total_size;
  342. uint8 *p = NULL, *global_addr;
  343. #ifdef OS_ENABLE_HW_BOUND_CHECK
  344. uint8 *mapped_mem;
  345. uint64 map_size = 8 * (uint64)BH_GB;
  346. uint64 page_size = os_getpagesize();
  347. #endif
  348. #if WASM_ENABLE_SHARED_MEMORY != 0
  349. bool is_shared_memory = memory->memory_flags & 0x02 ? true : false;
  350. /* Shared memory */
  351. if (is_shared_memory) {
  352. AOTMemoryInstance *shared_memory_instance;
  353. WASMSharedMemNode *node =
  354. wasm_module_get_shared_memory((WASMModuleCommon *)module);
  355. /* If the memory of this module has been instantiated,
  356. return the memory instance directly */
  357. if (node) {
  358. uint32 ref_count;
  359. ref_count = shared_memory_inc_reference((WASMModuleCommon *)module);
  360. bh_assert(ref_count > 0);
  361. shared_memory_instance =
  362. (AOTMemoryInstance *)shared_memory_get_memory_inst(node);
  363. bh_assert(shared_memory_instance);
  364. (void)ref_count;
  365. return shared_memory_instance;
  366. }
  367. }
  368. #endif
  369. if (heap_size > 0 && module->malloc_func_index != (uint32)-1
  370. && module->free_func_index != (uint32)-1) {
  371. /* Disable app heap, use malloc/free function exported
  372. by wasm app to allocate/free memory instead */
  373. heap_size = 0;
  374. }
  375. if (init_page_count == max_page_count && init_page_count == 1) {
  376. /* If only one page and at most one page, we just append
  377. the app heap to the end of linear memory, enlarge the
  378. num_bytes_per_page, and don't change the page count */
  379. heap_offset = num_bytes_per_page;
  380. num_bytes_per_page += heap_size;
  381. if (num_bytes_per_page < heap_size) {
  382. set_error_buf(error_buf, error_buf_size,
  383. "failed to insert app heap into linear memory, "
  384. "try using `--heap_size=0` option");
  385. return NULL;
  386. }
  387. }
  388. else if (heap_size > 0) {
  389. if (init_page_count == max_page_count && init_page_count == 0) {
  390. /* If the memory data size is always 0, we resize it to
  391. one page for app heap */
  392. num_bytes_per_page = heap_size;
  393. heap_offset = 0;
  394. inc_page_count = 1;
  395. }
  396. else if (module->aux_heap_base_global_index != (uint32)-1
  397. && module->aux_heap_base
  398. < num_bytes_per_page * init_page_count) {
  399. /* Insert app heap before __heap_base */
  400. aux_heap_base = module->aux_heap_base;
  401. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  402. if (bytes_of_last_page == 0)
  403. bytes_of_last_page = num_bytes_per_page;
  404. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  405. inc_page_count =
  406. (heap_size - bytes_to_page_end + num_bytes_per_page - 1)
  407. / num_bytes_per_page;
  408. heap_offset = aux_heap_base;
  409. aux_heap_base += heap_size;
  410. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  411. if (bytes_of_last_page == 0)
  412. bytes_of_last_page = num_bytes_per_page;
  413. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  414. if (bytes_to_page_end < 1 * BH_KB) {
  415. aux_heap_base += 1 * BH_KB;
  416. inc_page_count++;
  417. }
  418. /* Adjust __heap_base global value */
  419. global_idx = module->aux_heap_base_global_index
  420. - module->import_global_count;
  421. global_addr = module_inst->global_data
  422. + module->globals[global_idx].data_offset;
  423. *(uint32 *)global_addr = aux_heap_base;
  424. LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base);
  425. }
  426. else {
  427. /* Insert app heap before new page */
  428. inc_page_count =
  429. (heap_size + num_bytes_per_page - 1) / num_bytes_per_page;
  430. heap_offset = num_bytes_per_page * init_page_count;
  431. heap_size = num_bytes_per_page * inc_page_count;
  432. if (heap_size > 0)
  433. heap_size -= 1 * BH_KB;
  434. }
  435. init_page_count += inc_page_count;
  436. max_page_count += inc_page_count;
  437. if (init_page_count > DEFAULT_MAX_PAGES) {
  438. set_error_buf(error_buf, error_buf_size,
  439. "failed to insert app heap into linear memory, "
  440. "try using `--heap_size=0` option");
  441. return NULL;
  442. }
  443. else if (init_page_count == DEFAULT_MAX_PAGES) {
  444. num_bytes_per_page = UINT32_MAX;
  445. init_page_count = max_page_count = 1;
  446. }
  447. if (max_page_count > DEFAULT_MAX_PAGES)
  448. max_page_count = DEFAULT_MAX_PAGES;
  449. }
  450. LOG_VERBOSE("Memory instantiate:");
  451. LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u",
  452. num_bytes_per_page, init_page_count, max_page_count);
  453. LOG_VERBOSE(" data offset: %u, stack size: %d", module->aux_data_end,
  454. module->aux_stack_size);
  455. LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size);
  456. total_size = (uint64)num_bytes_per_page * init_page_count;
  457. #if WASM_ENABLE_SHARED_MEMORY != 0
  458. if (is_shared_memory) {
  459. /* Allocate max page for shared memory */
  460. total_size = (uint64)num_bytes_per_page * max_page_count;
  461. }
  462. #endif
  463. bh_assert(total_size <= UINT32_MAX);
  464. #ifndef OS_ENABLE_HW_BOUND_CHECK
  465. /* Allocate memory */
  466. if (total_size > 0
  467. && !(p = runtime_malloc(total_size, error_buf, error_buf_size))) {
  468. return NULL;
  469. }
  470. #else
  471. total_size = (total_size + page_size - 1) & ~(page_size - 1);
  472. /* Totally 8G is mapped, the opcode load/store address range is 0 to 8G:
  473. * ea = i + memarg.offset
  474. * both i and memarg.offset are u32 in range 0 to 4G
  475. * so the range of ea is 0 to 8G
  476. */
  477. if (!(p = mapped_mem =
  478. os_mmap(NULL, map_size, MMAP_PROT_NONE, MMAP_MAP_NONE))) {
  479. set_error_buf(error_buf, error_buf_size, "mmap memory failed");
  480. return NULL;
  481. }
  482. #ifdef BH_PLATFORM_WINDOWS
  483. if (!os_mem_commit(p, total_size, MMAP_PROT_READ | MMAP_PROT_WRITE)) {
  484. set_error_buf(error_buf, error_buf_size, "commit memory failed");
  485. os_munmap(mapped_mem, map_size);
  486. return NULL;
  487. }
  488. #endif
  489. if (os_mprotect(p, total_size, MMAP_PROT_READ | MMAP_PROT_WRITE) != 0) {
  490. set_error_buf(error_buf, error_buf_size, "mprotect memory failed");
  491. #ifdef BH_PLATFORM_WINDOWS
  492. os_mem_decommit(p, total_size);
  493. #endif
  494. os_munmap(mapped_mem, map_size);
  495. return NULL;
  496. }
  497. /* Newly allocated pages are filled with zero by the OS, we don't fill it
  498. * again here */
  499. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  500. if (total_size > UINT32_MAX)
  501. total_size = UINT32_MAX;
  502. memory_inst->module_type = Wasm_Module_AoT;
  503. memory_inst->num_bytes_per_page = num_bytes_per_page;
  504. memory_inst->cur_page_count = init_page_count;
  505. memory_inst->max_page_count = max_page_count;
  506. memory_inst->memory_data_size = (uint32)total_size;
  507. /* Init memory info */
  508. memory_inst->memory_data = p;
  509. memory_inst->memory_data_end = p + (uint32)total_size;
  510. /* Initialize heap info */
  511. memory_inst->heap_data = p + heap_offset;
  512. memory_inst->heap_data_end = p + heap_offset + heap_size;
  513. if (heap_size > 0) {
  514. uint32 heap_struct_size = mem_allocator_get_heap_struct_size();
  515. if (!(heap_handle = runtime_malloc((uint64)heap_struct_size, error_buf,
  516. error_buf_size))) {
  517. goto fail1;
  518. }
  519. memory_inst->heap_handle = heap_handle;
  520. if (!mem_allocator_create_with_struct_and_pool(
  521. heap_handle, heap_struct_size, memory_inst->heap_data,
  522. heap_size)) {
  523. set_error_buf(error_buf, error_buf_size, "init app heap failed");
  524. goto fail2;
  525. }
  526. }
  527. if (total_size > 0) {
  528. #if UINTPTR_MAX == UINT64_MAX
  529. memory_inst->mem_bound_check_1byte.u64 = total_size - 1;
  530. memory_inst->mem_bound_check_2bytes.u64 = total_size - 2;
  531. memory_inst->mem_bound_check_4bytes.u64 = total_size - 4;
  532. memory_inst->mem_bound_check_8bytes.u64 = total_size - 8;
  533. memory_inst->mem_bound_check_16bytes.u64 = total_size - 16;
  534. #else
  535. memory_inst->mem_bound_check_1byte.u32[0] = (uint32)total_size - 1;
  536. memory_inst->mem_bound_check_2bytes.u32[0] = (uint32)total_size - 2;
  537. memory_inst->mem_bound_check_4bytes.u32[0] = (uint32)total_size - 4;
  538. memory_inst->mem_bound_check_8bytes.u32[0] = (uint32)total_size - 8;
  539. memory_inst->mem_bound_check_16bytes.u32[0] = (uint32)total_size - 16;
  540. #endif
  541. }
  542. #if WASM_ENABLE_SHARED_MEMORY != 0
  543. if (is_shared_memory) {
  544. memory_inst->is_shared = true;
  545. if (!shared_memory_set_memory_inst(
  546. (WASMModuleCommon *)module,
  547. (WASMMemoryInstanceCommon *)memory_inst)) {
  548. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  549. goto fail3;
  550. }
  551. }
  552. #endif
  553. return memory_inst;
  554. #if WASM_ENABLE_SHARED_MEMORY != 0
  555. fail3:
  556. if (heap_size > 0)
  557. mem_allocator_destroy(memory_inst->heap_handle);
  558. #endif
  559. fail2:
  560. if (heap_size > 0)
  561. wasm_runtime_free(memory_inst->heap_handle);
  562. fail1:
  563. #ifndef OS_ENABLE_HW_BOUND_CHECK
  564. if (memory_inst->memory_data)
  565. wasm_runtime_free(memory_inst->memory_data);
  566. #else
  567. #ifdef BH_PLATFORM_WINDOWS
  568. if (memory_inst->memory_data)
  569. os_mem_decommit(p, total_size);
  570. #endif
  571. os_munmap(mapped_mem, map_size);
  572. #endif
  573. memory_inst->memory_data = NULL;
  574. return NULL;
  575. }
  576. static AOTMemoryInstance *
  577. aot_get_default_memory(AOTModuleInstance *module_inst)
  578. {
  579. if (module_inst->memories)
  580. return module_inst->memories[0];
  581. else
  582. return NULL;
  583. }
  584. static bool
  585. memories_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  586. uint32 heap_size, char *error_buf, uint32 error_buf_size)
  587. {
  588. uint32 global_index, global_data_offset, base_offset, length;
  589. uint32 i, memory_count = module->memory_count;
  590. AOTMemoryInstance *memories, *memory_inst;
  591. AOTMemInitData *data_seg;
  592. uint64 total_size;
  593. module_inst->memory_count = memory_count;
  594. total_size = sizeof(AOTMemoryInstance *) * (uint64)memory_count;
  595. if (!(module_inst->memories =
  596. runtime_malloc(total_size, error_buf, error_buf_size))) {
  597. return false;
  598. }
  599. memories = module_inst->global_table_data.memory_instances;
  600. for (i = 0; i < memory_count; i++, memories++) {
  601. memory_inst = memory_instantiate(module_inst, module, memories,
  602. &module->memories[i], heap_size,
  603. error_buf, error_buf_size);
  604. if (!memory_inst) {
  605. return false;
  606. }
  607. module_inst->memories[i] = memory_inst;
  608. }
  609. /* Get default memory instance */
  610. memory_inst = aot_get_default_memory(module_inst);
  611. if (!memory_inst) {
  612. /* Ignore setting memory init data if no memory inst is created */
  613. return true;
  614. }
  615. for (i = 0; i < module->mem_init_data_count; i++) {
  616. data_seg = module->mem_init_data_list[i];
  617. #if WASM_ENABLE_BULK_MEMORY != 0
  618. if (data_seg->is_passive)
  619. continue;
  620. #endif
  621. bh_assert(data_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  622. || data_seg->offset.init_expr_type
  623. == INIT_EXPR_TYPE_GET_GLOBAL);
  624. /* Resolve memory data base offset */
  625. if (data_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  626. global_index = data_seg->offset.u.global_index;
  627. if (!check_global_init_expr(module, global_index, error_buf,
  628. error_buf_size)) {
  629. return false;
  630. }
  631. if (global_index < module->import_global_count)
  632. global_data_offset =
  633. module->import_globals[global_index].data_offset;
  634. else
  635. global_data_offset =
  636. module->globals[global_index - module->import_global_count]
  637. .data_offset;
  638. base_offset =
  639. *(uint32 *)(module_inst->global_data + global_data_offset);
  640. }
  641. else {
  642. base_offset = (uint32)data_seg->offset.u.i32;
  643. }
  644. /* Copy memory data */
  645. bh_assert(memory_inst->memory_data
  646. || memory_inst->memory_data_size == 0);
  647. /* Check memory data */
  648. /* check offset since length might negative */
  649. if (base_offset > memory_inst->memory_data_size) {
  650. LOG_DEBUG("base_offset(%d) > memory_data_size(%d)", base_offset,
  651. memory_inst->memory_data_size);
  652. #if WASM_ENABLE_REF_TYPES != 0
  653. set_error_buf(error_buf, error_buf_size,
  654. "out of bounds memory access");
  655. #else
  656. set_error_buf(error_buf, error_buf_size,
  657. "data segment does not fit");
  658. #endif
  659. return false;
  660. }
  661. /* check offset + length(could be zero) */
  662. length = data_seg->byte_count;
  663. if (base_offset + length > memory_inst->memory_data_size) {
  664. LOG_DEBUG("base_offset(%d) + length(%d) > memory_data_size(%d)",
  665. base_offset, length, memory_inst->memory_data_size);
  666. #if WASM_ENABLE_REF_TYPES != 0
  667. set_error_buf(error_buf, error_buf_size,
  668. "out of bounds memory access");
  669. #else
  670. set_error_buf(error_buf, error_buf_size,
  671. "data segment does not fit");
  672. #endif
  673. return false;
  674. }
  675. if (memory_inst->memory_data) {
  676. bh_memcpy_s((uint8 *)memory_inst->memory_data + base_offset,
  677. memory_inst->memory_data_size - base_offset,
  678. data_seg->bytes, length);
  679. }
  680. }
  681. return true;
  682. }
  683. static bool
  684. init_func_ptrs(AOTModuleInstance *module_inst, AOTModule *module,
  685. char *error_buf, uint32 error_buf_size)
  686. {
  687. uint32 i;
  688. void **func_ptrs;
  689. uint64 total_size = ((uint64)module->import_func_count + module->func_count)
  690. * sizeof(void *);
  691. if (module->import_func_count + module->func_count == 0)
  692. return true;
  693. /* Allocate memory */
  694. if (!(module_inst->func_ptrs =
  695. runtime_malloc(total_size, error_buf, error_buf_size))) {
  696. return false;
  697. }
  698. /* Set import function pointers */
  699. func_ptrs = (void **)module_inst->func_ptrs;
  700. for (i = 0; i < module->import_func_count; i++, func_ptrs++) {
  701. *func_ptrs = (void *)module->import_funcs[i].func_ptr_linked;
  702. if (!*func_ptrs) {
  703. const char *module_name = module->import_funcs[i].module_name;
  704. const char *field_name = module->import_funcs[i].func_name;
  705. LOG_WARNING("warning: failed to link import function (%s, %s)",
  706. module_name, field_name);
  707. }
  708. }
  709. /* Set defined function pointers */
  710. bh_memcpy_s(func_ptrs, sizeof(void *) * module->func_count,
  711. module->func_ptrs, sizeof(void *) * module->func_count);
  712. return true;
  713. }
  714. static bool
  715. init_func_type_indexes(AOTModuleInstance *module_inst, AOTModule *module,
  716. char *error_buf, uint32 error_buf_size)
  717. {
  718. uint32 i;
  719. uint32 *func_type_index;
  720. uint64 total_size = ((uint64)module->import_func_count + module->func_count)
  721. * sizeof(uint32);
  722. if (module->import_func_count + module->func_count == 0)
  723. return true;
  724. /* Allocate memory */
  725. if (!(module_inst->func_type_indexes =
  726. runtime_malloc(total_size, error_buf, error_buf_size))) {
  727. return false;
  728. }
  729. /* Set import function type indexes */
  730. func_type_index = module_inst->func_type_indexes;
  731. for (i = 0; i < module->import_func_count; i++, func_type_index++)
  732. *func_type_index = module->import_funcs[i].func_type_index;
  733. bh_memcpy_s(func_type_index, sizeof(uint32) * module->func_count,
  734. module->func_type_indexes, sizeof(uint32) * module->func_count);
  735. return true;
  736. }
  737. static bool
  738. create_export_funcs(AOTModuleInstance *module_inst, AOTModule *module,
  739. char *error_buf, uint32 error_buf_size)
  740. {
  741. AOTExport *exports = module->exports;
  742. AOTFunctionInstance *export_func;
  743. uint64 size;
  744. uint32 i, func_index, ftype_index;
  745. if (module_inst->export_func_count > 0) {
  746. /* Allocate memory */
  747. size = sizeof(AOTFunctionInstance)
  748. * (uint64)module_inst->export_func_count;
  749. if (!(export_func = runtime_malloc(size, error_buf, error_buf_size))) {
  750. return false;
  751. }
  752. module_inst->export_functions = (void *)export_func;
  753. for (i = 0; i < module->export_count; i++) {
  754. if (exports[i].kind == EXPORT_KIND_FUNC) {
  755. export_func->func_name = exports[i].name;
  756. export_func->func_index = exports[i].index;
  757. if (export_func->func_index < module->import_func_count) {
  758. export_func->is_import_func = true;
  759. export_func->u.func_import =
  760. &module->import_funcs[export_func->func_index];
  761. }
  762. else {
  763. export_func->is_import_func = false;
  764. func_index =
  765. export_func->func_index - module->import_func_count;
  766. ftype_index = module->func_type_indexes[func_index];
  767. export_func->u.func.func_type =
  768. module->func_types[ftype_index];
  769. export_func->u.func.func_ptr =
  770. module->func_ptrs[func_index];
  771. }
  772. export_func++;
  773. }
  774. }
  775. }
  776. return true;
  777. }
  778. static bool
  779. create_exports(AOTModuleInstance *module_inst, AOTModule *module,
  780. char *error_buf, uint32 error_buf_size)
  781. {
  782. AOTExport *exports = module->exports;
  783. uint32 i;
  784. for (i = 0; i < module->export_count; i++) {
  785. switch (exports[i].kind) {
  786. case EXPORT_KIND_FUNC:
  787. module_inst->export_func_count++;
  788. break;
  789. case EXPORT_KIND_GLOBAL:
  790. module_inst->export_global_count++;
  791. break;
  792. case EXPORT_KIND_TABLE:
  793. module_inst->export_table_count++;
  794. break;
  795. case EXPORT_KIND_MEMORY:
  796. module_inst->export_memory_count++;
  797. break;
  798. default:
  799. return false;
  800. }
  801. }
  802. return create_export_funcs(module_inst, module, error_buf, error_buf_size);
  803. }
  804. static AOTFunctionInstance *
  805. lookup_post_instantiate_func(AOTModuleInstance *module_inst,
  806. const char *func_name)
  807. {
  808. AOTFunctionInstance *func;
  809. AOTFuncType *func_type;
  810. if (!(func = aot_lookup_function(module_inst, func_name, NULL)))
  811. /* Not found */
  812. return NULL;
  813. func_type = func->u.func.func_type;
  814. if (!(func_type->param_count == 0 && func_type->result_count == 0))
  815. /* Not a valid function type, ignore it */
  816. return NULL;
  817. return func;
  818. }
  819. static bool
  820. execute_post_instantiate_functions(AOTModuleInstance *module_inst,
  821. bool is_sub_inst, WASMExecEnv *exec_env_main)
  822. {
  823. AOTModule *module = (AOTModule *)module_inst->module;
  824. AOTFunctionInstance *initialize_func = NULL;
  825. AOTFunctionInstance *post_inst_func = NULL;
  826. AOTFunctionInstance *call_ctors_func = NULL;
  827. WASMModuleInstanceCommon *module_inst_main = NULL;
  828. #ifdef OS_ENABLE_HW_BOUND_CHECK
  829. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  830. #endif
  831. WASMExecEnv *exec_env = NULL, *exec_env_created = NULL;
  832. bool ret = false;
  833. #if WASM_ENABLE_LIBC_WASI != 0
  834. /*
  835. * WASI reactor instances may assume that _initialize will be called by
  836. * the environment at most once, and that none of their other exports
  837. * are accessed before that call.
  838. */
  839. if (!is_sub_inst && module->import_wasi_api) {
  840. initialize_func =
  841. lookup_post_instantiate_func(module_inst, "_initialize");
  842. }
  843. #endif
  844. /* Execute possible "__post_instantiate" function if wasm app is
  845. compiled by emsdk's early version */
  846. if (!is_sub_inst) {
  847. post_inst_func =
  848. lookup_post_instantiate_func(module_inst, "__post_instantiate");
  849. }
  850. #if WASM_ENABLE_BULK_MEMORY != 0
  851. /* Only execute the memory init function for main instance since
  852. the data segments will be dropped once initialized */
  853. if (!is_sub_inst
  854. #if WASM_ENABLE_LIBC_WASI != 0
  855. && !module->import_wasi_api
  856. #endif
  857. ) {
  858. call_ctors_func =
  859. lookup_post_instantiate_func(module_inst, "__wasm_call_ctors");
  860. }
  861. #endif
  862. if (!module->start_function && !initialize_func && !post_inst_func
  863. && !call_ctors_func) {
  864. /* No post instantiation functions to call */
  865. return true;
  866. }
  867. if (is_sub_inst) {
  868. bh_assert(exec_env_main);
  869. #ifdef OS_ENABLE_HW_BOUND_CHECK
  870. bh_assert(exec_env_tls == exec_env_main);
  871. (void)exec_env_tls;
  872. #endif
  873. exec_env = exec_env_main;
  874. /* Temporarily replace parent exec_env's module inst to current
  875. module inst to avoid checking failure when calling the
  876. wasm functions, and ensure that the exec_env's module inst
  877. is the correct one. */
  878. module_inst_main = exec_env_main->module_inst;
  879. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  880. }
  881. else {
  882. /* Try using the existing exec_env */
  883. #ifdef OS_ENABLE_HW_BOUND_CHECK
  884. exec_env = exec_env_tls;
  885. #endif
  886. #if WASM_ENABLE_THREAD_MGR != 0
  887. if (!exec_env)
  888. exec_env = wasm_clusters_search_exec_env(
  889. (WASMModuleInstanceCommon *)module_inst);
  890. #endif
  891. if (!exec_env) {
  892. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  893. (WASMModuleInstanceCommon *)module_inst,
  894. module_inst->default_wasm_stack_size))) {
  895. aot_set_exception(module_inst, "allocate memory failed");
  896. return false;
  897. }
  898. }
  899. else {
  900. /* Temporarily replace exec_env's module inst with current
  901. module inst to ensure that the exec_env's module inst
  902. is the correct one. */
  903. module_inst_main = exec_env->module_inst;
  904. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  905. }
  906. }
  907. /* Execute start function for both main insance and sub instance */
  908. if (module->start_function) {
  909. AOTFunctionInstance start_func = { 0 };
  910. uint32 func_type_idx;
  911. start_func.func_name = "";
  912. start_func.func_index = module->start_func_index;
  913. start_func.is_import_func = false;
  914. func_type_idx = module->func_type_indexes[module->start_func_index
  915. - module->import_func_count];
  916. start_func.u.func.func_type = module->func_types[func_type_idx];
  917. start_func.u.func.func_ptr = module->start_function;
  918. if (!aot_call_function(exec_env, &start_func, 0, NULL)) {
  919. goto fail;
  920. }
  921. }
  922. if (initialize_func
  923. && !aot_call_function(exec_env, initialize_func, 0, NULL)) {
  924. goto fail;
  925. }
  926. if (post_inst_func
  927. && !aot_call_function(exec_env, post_inst_func, 0, NULL)) {
  928. goto fail;
  929. }
  930. if (call_ctors_func
  931. && !aot_call_function(exec_env, call_ctors_func, 0, NULL)) {
  932. goto fail;
  933. }
  934. ret = true;
  935. fail:
  936. if (is_sub_inst) {
  937. /* Restore the parent exec_env's module inst */
  938. exec_env_main->module_inst = module_inst_main;
  939. }
  940. else {
  941. if (module_inst_main)
  942. /* Restore the existing exec_env's module inst */
  943. exec_env->module_inst = module_inst_main;
  944. if (exec_env_created)
  945. wasm_exec_env_destroy(exec_env_created);
  946. }
  947. return ret;
  948. }
  949. static bool
  950. check_linked_symbol(AOTModule *module, char *error_buf, uint32 error_buf_size)
  951. {
  952. uint32 i;
  953. /* init_func_ptrs() will go through import functions */
  954. for (i = 0; i < module->import_global_count; i++) {
  955. AOTImportGlobal *global = module->import_globals + i;
  956. if (!global->is_linked) {
  957. set_error_buf_v(error_buf, error_buf_size,
  958. "failed to link import global (%s, %s)",
  959. global->module_name, global->global_name);
  960. return false;
  961. }
  962. }
  963. return true;
  964. }
  965. AOTModuleInstance *
  966. aot_instantiate(AOTModule *module, bool is_sub_inst, WASMExecEnv *exec_env_main,
  967. uint32 stack_size, uint32 heap_size, char *error_buf,
  968. uint32 error_buf_size)
  969. {
  970. AOTModuleInstance *module_inst;
  971. const uint32 module_inst_struct_size =
  972. offsetof(AOTModuleInstance, global_table_data.bytes);
  973. const uint64 module_inst_mem_inst_size =
  974. (uint64)module->memory_count * sizeof(AOTMemoryInstance);
  975. uint64 total_size, table_size = 0;
  976. uint8 *p;
  977. uint32 i, extra_info_offset;
  978. /* Check heap size */
  979. heap_size = align_uint(heap_size, 8);
  980. if (heap_size > APP_HEAP_SIZE_MAX)
  981. heap_size = APP_HEAP_SIZE_MAX;
  982. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  983. + module->global_data_size;
  984. /*
  985. * calculate size of table data
  986. */
  987. for (i = 0; i != module->import_table_count; ++i) {
  988. table_size += offsetof(AOTTableInstance, elems);
  989. table_size += (uint64)sizeof(uint32)
  990. * (uint64)aot_get_imp_tbl_data_slots(
  991. module->import_tables + i, false);
  992. }
  993. for (i = 0; i != module->table_count; ++i) {
  994. table_size += offsetof(AOTTableInstance, elems);
  995. table_size +=
  996. (uint64)sizeof(uint32)
  997. * (uint64)aot_get_tbl_data_slots(module->tables + i, false);
  998. }
  999. total_size += table_size;
  1000. /* The offset of AOTModuleInstanceExtra, make it 8-byte aligned */
  1001. total_size = (total_size + 7LL) & ~7LL;
  1002. extra_info_offset = (uint32)total_size;
  1003. total_size += sizeof(AOTModuleInstanceExtra);
  1004. /* Allocate module instance, global data, table data and heap data */
  1005. if (!(module_inst =
  1006. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1007. return NULL;
  1008. }
  1009. module_inst->module_type = Wasm_Module_AoT;
  1010. module_inst->module = (void *)module;
  1011. module_inst->e =
  1012. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  1013. /* Initialize global info */
  1014. p = (uint8 *)module_inst + module_inst_struct_size
  1015. + module_inst_mem_inst_size;
  1016. module_inst->global_data = p;
  1017. module_inst->global_data_size = module->global_data_size;
  1018. if (!global_instantiate(module_inst, module, error_buf, error_buf_size))
  1019. goto fail;
  1020. /* Initialize table info */
  1021. p += module->global_data_size;
  1022. module_inst->table_count = module->table_count + module->import_table_count;
  1023. if (!tables_instantiate(module_inst, module, (AOTTableInstance *)p,
  1024. error_buf, error_buf_size))
  1025. goto fail;
  1026. /* Initialize memory space */
  1027. if (!memories_instantiate(module_inst, module, heap_size, error_buf,
  1028. error_buf_size))
  1029. goto fail;
  1030. /* Initialize function pointers */
  1031. if (!init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  1032. goto fail;
  1033. /* Initialize function type indexes */
  1034. if (!init_func_type_indexes(module_inst, module, error_buf, error_buf_size))
  1035. goto fail;
  1036. if (!check_linked_symbol(module, error_buf, error_buf_size))
  1037. goto fail;
  1038. if (!create_exports(module_inst, module, error_buf, error_buf_size))
  1039. goto fail;
  1040. #if WASM_ENABLE_LIBC_WASI != 0
  1041. if (!is_sub_inst) {
  1042. if (!wasm_runtime_init_wasi(
  1043. (WASMModuleInstanceCommon *)module_inst,
  1044. module->wasi_args.dir_list, module->wasi_args.dir_count,
  1045. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  1046. module->wasi_args.env, module->wasi_args.env_count,
  1047. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  1048. module->wasi_args.ns_lookup_pool,
  1049. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  1050. module->wasi_args.argc, module->wasi_args.stdio[0],
  1051. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  1052. error_buf, error_buf_size))
  1053. goto fail;
  1054. }
  1055. #endif
  1056. #if WASM_ENABLE_WASI_NN != 0
  1057. if (!is_sub_inst) {
  1058. if (!(((AOTModuleInstanceExtra *)module_inst->e)->wasi_nn_ctx =
  1059. wasi_nn_initialize())) {
  1060. set_error_buf(error_buf, error_buf_size,
  1061. "wasi nn initialization failed");
  1062. goto fail;
  1063. }
  1064. }
  1065. #endif
  1066. /* Initialize the thread related data */
  1067. if (stack_size == 0)
  1068. stack_size = DEFAULT_WASM_STACK_SIZE;
  1069. #if WASM_ENABLE_SPEC_TEST != 0
  1070. if (stack_size < 48 * 1024)
  1071. stack_size = 48 * 1024;
  1072. #endif
  1073. module_inst->default_wasm_stack_size = stack_size;
  1074. #if WASM_ENABLE_PERF_PROFILING != 0
  1075. total_size = (uint64)sizeof(AOTFuncPerfProfInfo)
  1076. * (module->import_func_count + module->func_count);
  1077. if (!(module_inst->func_perf_profilings =
  1078. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1079. goto fail;
  1080. }
  1081. #endif
  1082. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1083. if (!(module_inst->frames =
  1084. runtime_malloc(sizeof(Vector), error_buf, error_buf_size))) {
  1085. goto fail;
  1086. }
  1087. #endif
  1088. if (!execute_post_instantiate_functions(module_inst, is_sub_inst,
  1089. exec_env_main)) {
  1090. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  1091. goto fail;
  1092. }
  1093. #if WASM_ENABLE_MEMORY_TRACING != 0
  1094. wasm_runtime_dump_module_inst_mem_consumption(
  1095. (WASMModuleInstanceCommon *)module_inst);
  1096. #endif
  1097. return module_inst;
  1098. fail:
  1099. aot_deinstantiate(module_inst, is_sub_inst);
  1100. return NULL;
  1101. }
  1102. void
  1103. aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst)
  1104. {
  1105. if (module_inst->exec_env_singleton) {
  1106. /* wasm_exec_env_destroy will call
  1107. wasm_cluster_wait_for_all_except_self to wait for other
  1108. threads, so as to destroy their exec_envs and module
  1109. instances first, and avoid accessing the shared resources
  1110. of current module instance after it is deinstantiated. */
  1111. wasm_exec_env_destroy((WASMExecEnv *)module_inst->exec_env_singleton);
  1112. }
  1113. #if WASM_ENABLE_LIBC_WASI != 0
  1114. /* Destroy wasi resource before freeing app heap, since some fields of
  1115. wasi contex are allocated from app heap, and if app heap is freed,
  1116. these fields will be set to NULL, we cannot free their internal data
  1117. which may allocated from global heap. */
  1118. /* Only destroy wasi ctx in the main module instance */
  1119. if (!is_sub_inst)
  1120. wasm_runtime_destroy_wasi((WASMModuleInstanceCommon *)module_inst);
  1121. #endif
  1122. #if WASM_ENABLE_PERF_PROFILING != 0
  1123. if (module_inst->func_perf_profilings)
  1124. wasm_runtime_free(module_inst->func_perf_profilings);
  1125. #endif
  1126. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1127. if (module_inst->frames) {
  1128. bh_vector_destroy(module_inst->frames);
  1129. wasm_runtime_free(module_inst->frames);
  1130. module_inst->frames = NULL;
  1131. }
  1132. #endif
  1133. if (module_inst->tables)
  1134. wasm_runtime_free(module_inst->tables);
  1135. if (module_inst->memories)
  1136. memories_deinstantiate(module_inst);
  1137. if (module_inst->export_functions)
  1138. wasm_runtime_free(module_inst->export_functions);
  1139. if (module_inst->func_ptrs)
  1140. wasm_runtime_free(module_inst->func_ptrs);
  1141. if (module_inst->func_type_indexes)
  1142. wasm_runtime_free(module_inst->func_type_indexes);
  1143. if (((AOTModuleInstanceExtra *)module_inst->e)->c_api_func_imports)
  1144. wasm_runtime_free(
  1145. ((AOTModuleInstanceExtra *)module_inst->e)->c_api_func_imports);
  1146. #if WASM_ENABLE_WASI_NN != 0
  1147. if (!is_sub_inst) {
  1148. WASINNContext *wasi_nn_ctx =
  1149. ((AOTModuleInstanceExtra *)module_inst->e)->wasi_nn_ctx;
  1150. if (wasi_nn_ctx)
  1151. wasi_nn_destroy(wasi_nn_ctx);
  1152. }
  1153. #endif
  1154. wasm_runtime_free(module_inst);
  1155. }
  1156. AOTFunctionInstance *
  1157. aot_lookup_function(const AOTModuleInstance *module_inst, const char *name,
  1158. const char *signature)
  1159. {
  1160. uint32 i;
  1161. AOTFunctionInstance *export_funcs =
  1162. (AOTFunctionInstance *)module_inst->export_functions;
  1163. for (i = 0; i < module_inst->export_func_count; i++)
  1164. if (!strcmp(export_funcs[i].func_name, name))
  1165. return &export_funcs[i];
  1166. (void)signature;
  1167. return NULL;
  1168. }
  1169. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1170. static bool
  1171. invoke_native_with_hw_bound_check(WASMExecEnv *exec_env, void *func_ptr,
  1172. const WASMFuncType *func_type,
  1173. const char *signature, void *attachment,
  1174. uint32 *argv, uint32 argc, uint32 *argv_ret)
  1175. {
  1176. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1177. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1178. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  1179. uint32 page_size = os_getpagesize();
  1180. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  1181. uint16 param_count = func_type->param_count;
  1182. uint16 result_count = func_type->result_count;
  1183. const uint8 *types = func_type->types;
  1184. #ifdef BH_PLATFORM_WINDOWS
  1185. int result;
  1186. bool has_exception;
  1187. char exception[EXCEPTION_BUF_LEN];
  1188. #endif
  1189. bool ret;
  1190. /* Check native stack overflow firstly to ensure we have enough
  1191. native stack to run the following codes before actually calling
  1192. the aot function in invokeNative function. */
  1193. RECORD_STACK_USAGE(exec_env, (uint8 *)&module_inst);
  1194. if ((uint8 *)&module_inst < exec_env->native_stack_boundary
  1195. + page_size * (guard_page_count + 1)) {
  1196. aot_set_exception_with_id(module_inst, EXCE_NATIVE_STACK_OVERFLOW);
  1197. return false;
  1198. }
  1199. if (exec_env_tls && (exec_env_tls != exec_env)) {
  1200. aot_set_exception(module_inst, "invalid exec env");
  1201. return false;
  1202. }
  1203. if (!os_thread_signal_inited()) {
  1204. aot_set_exception(module_inst, "thread signal env not inited");
  1205. return false;
  1206. }
  1207. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  1208. wasm_runtime_set_exec_env_tls(exec_env);
  1209. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  1210. /* Quick call with func_ptr if the function signature is simple */
  1211. if (!signature && param_count == 1 && types[0] == VALUE_TYPE_I32) {
  1212. if (result_count == 0) {
  1213. void (*NativeFunc)(WASMExecEnv *, uint32) =
  1214. (void (*)(WASMExecEnv *, uint32))func_ptr;
  1215. NativeFunc(exec_env, argv[0]);
  1216. ret = aot_copy_exception(module_inst, NULL) ? false : true;
  1217. }
  1218. else if (result_count == 1
  1219. && types[param_count] == VALUE_TYPE_I32) {
  1220. uint32 (*NativeFunc)(WASMExecEnv *, uint32) =
  1221. (uint32(*)(WASMExecEnv *, uint32))func_ptr;
  1222. argv_ret[0] = NativeFunc(exec_env, argv[0]);
  1223. ret = aot_copy_exception(module_inst, NULL) ? false : true;
  1224. }
  1225. else {
  1226. ret = wasm_runtime_invoke_native(exec_env, func_ptr, func_type,
  1227. signature, attachment, argv,
  1228. argc, argv_ret);
  1229. }
  1230. }
  1231. else {
  1232. ret = wasm_runtime_invoke_native(exec_env, func_ptr, func_type,
  1233. signature, attachment, argv, argc,
  1234. argv_ret);
  1235. }
  1236. #ifdef BH_PLATFORM_WINDOWS
  1237. has_exception = aot_copy_exception(module_inst, exception);
  1238. if (has_exception && strstr(exception, "native stack overflow")) {
  1239. /* After a stack overflow, the stack was left
  1240. in a damaged state, let the CRT repair it */
  1241. result = _resetstkoflw();
  1242. bh_assert(result != 0);
  1243. }
  1244. #endif
  1245. }
  1246. else {
  1247. /* Exception has been set in signal handler before calling longjmp */
  1248. ret = false;
  1249. }
  1250. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  1251. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  1252. if (!exec_env->jmpbuf_stack_top) {
  1253. wasm_runtime_set_exec_env_tls(NULL);
  1254. }
  1255. if (!ret) {
  1256. os_sigreturn();
  1257. os_signal_unmask();
  1258. }
  1259. (void)jmpbuf_node_pop;
  1260. return ret;
  1261. }
  1262. #define invoke_native_internal invoke_native_with_hw_bound_check
  1263. #else /* else of OS_ENABLE_HW_BOUND_CHECK */
  1264. #define invoke_native_internal wasm_runtime_invoke_native
  1265. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  1266. bool
  1267. aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function,
  1268. unsigned argc, uint32 argv[])
  1269. {
  1270. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1271. AOTFuncType *func_type = function->u.func.func_type;
  1272. uint32 result_count = func_type->result_count;
  1273. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  1274. bool ret;
  1275. if (argc < func_type->param_cell_num) {
  1276. char buf[108];
  1277. snprintf(buf, sizeof(buf),
  1278. "invalid argument count %u, must be no smaller than %u", argc,
  1279. func_type->param_cell_num);
  1280. aot_set_exception(module_inst, buf);
  1281. return false;
  1282. }
  1283. argc = func_type->param_cell_num;
  1284. /* func pointer was looked up previously */
  1285. bh_assert(function->u.func.func_ptr != NULL);
  1286. /* set thread handle and stack boundary */
  1287. wasm_exec_env_set_thread_info(exec_env);
  1288. if (ext_ret_count > 0) {
  1289. uint32 cell_num = 0, i;
  1290. uint8 *ext_ret_types = func_type->types + func_type->param_count + 1;
  1291. uint32 argv1_buf[32], *argv1 = argv1_buf, *ext_rets = NULL;
  1292. uint32 *argv_ret = argv;
  1293. uint32 ext_ret_cell = wasm_get_cell_num(ext_ret_types, ext_ret_count);
  1294. uint64 size;
  1295. /* Allocate memory all arguments */
  1296. size =
  1297. sizeof(uint32) * (uint64)argc /* original arguments */
  1298. + sizeof(void *)
  1299. * (uint64)ext_ret_count /* extra result values' addr */
  1300. + sizeof(uint32) * (uint64)ext_ret_cell; /* extra result values */
  1301. if (size > sizeof(argv1_buf)
  1302. && !(argv1 = runtime_malloc(size, module_inst->cur_exception,
  1303. sizeof(module_inst->cur_exception)))) {
  1304. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_MEMORY);
  1305. return false;
  1306. }
  1307. /* Copy original arguments */
  1308. bh_memcpy_s(argv1, (uint32)size, argv, sizeof(uint32) * argc);
  1309. /* Get the extra result value's address */
  1310. ext_rets =
  1311. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1312. /* Append each extra result value's address to original arguments */
  1313. for (i = 0; i < ext_ret_count; i++) {
  1314. *(uintptr_t *)(argv1 + argc + sizeof(void *) / sizeof(uint32) * i) =
  1315. (uintptr_t)(ext_rets + cell_num);
  1316. cell_num += wasm_value_type_cell_num(ext_ret_types[i]);
  1317. }
  1318. #if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0)
  1319. if (!aot_alloc_frame(exec_env, function->func_index)) {
  1320. if (argv1 != argv1_buf)
  1321. wasm_runtime_free(argv1);
  1322. return false;
  1323. }
  1324. #endif
  1325. ret = invoke_native_internal(exec_env, function->u.func.func_ptr,
  1326. func_type, NULL, NULL, argv1, argc, argv);
  1327. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1328. if (!ret) {
  1329. if (aot_create_call_stack(exec_env)) {
  1330. aot_dump_call_stack(exec_env, true, NULL, 0);
  1331. }
  1332. }
  1333. #endif
  1334. #if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0)
  1335. aot_free_frame(exec_env);
  1336. #endif
  1337. if (!ret) {
  1338. if (argv1 != argv1_buf)
  1339. wasm_runtime_free(argv1);
  1340. return ret;
  1341. }
  1342. /* Get extra result values */
  1343. switch (func_type->types[func_type->param_count]) {
  1344. case VALUE_TYPE_I32:
  1345. case VALUE_TYPE_F32:
  1346. #if WASM_ENABLE_REF_TYPES != 0
  1347. case VALUE_TYPE_FUNCREF:
  1348. case VALUE_TYPE_EXTERNREF:
  1349. #endif
  1350. argv_ret++;
  1351. break;
  1352. case VALUE_TYPE_I64:
  1353. case VALUE_TYPE_F64:
  1354. argv_ret += 2;
  1355. break;
  1356. #if WASM_ENABLE_SIMD != 0
  1357. case VALUE_TYPE_V128:
  1358. argv_ret += 4;
  1359. break;
  1360. #endif
  1361. default:
  1362. bh_assert(0);
  1363. break;
  1364. }
  1365. ext_rets =
  1366. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1367. bh_memcpy_s(argv_ret, sizeof(uint32) * cell_num, ext_rets,
  1368. sizeof(uint32) * cell_num);
  1369. if (argv1 != argv1_buf)
  1370. wasm_runtime_free(argv1);
  1371. return true;
  1372. }
  1373. else {
  1374. #if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0)
  1375. if (!aot_alloc_frame(exec_env, function->func_index)) {
  1376. return false;
  1377. }
  1378. #endif
  1379. ret = invoke_native_internal(exec_env, function->u.func.func_ptr,
  1380. func_type, NULL, NULL, argv, argc, argv);
  1381. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1382. if (aot_copy_exception(module_inst, NULL)) {
  1383. if (aot_create_call_stack(exec_env)) {
  1384. aot_dump_call_stack(exec_env, true, NULL, 0);
  1385. }
  1386. }
  1387. #endif
  1388. #if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0)
  1389. aot_free_frame(exec_env);
  1390. #endif
  1391. return ret && !aot_copy_exception(module_inst, NULL) ? true : false;
  1392. }
  1393. }
  1394. void
  1395. aot_set_exception(AOTModuleInstance *module_inst, const char *exception)
  1396. {
  1397. wasm_set_exception(module_inst, exception);
  1398. }
  1399. void
  1400. aot_set_exception_with_id(AOTModuleInstance *module_inst, uint32 id)
  1401. {
  1402. if (id != EXCE_ALREADY_THROWN)
  1403. wasm_set_exception_with_id(module_inst, id);
  1404. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1405. wasm_runtime_access_exce_check_guard_page();
  1406. #endif
  1407. }
  1408. const char *
  1409. aot_get_exception(AOTModuleInstance *module_inst)
  1410. {
  1411. return wasm_get_exception(module_inst);
  1412. }
  1413. bool
  1414. aot_copy_exception(AOTModuleInstance *module_inst, char *exception_buf)
  1415. {
  1416. /* The field offsets of cur_exception in AOTModuleInstance and
  1417. WASMModuleInstance are the same */
  1418. return wasm_copy_exception(module_inst, exception_buf);
  1419. }
  1420. static bool
  1421. execute_malloc_function(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  1422. AOTFunctionInstance *malloc_func,
  1423. AOTFunctionInstance *retain_func, uint32 size,
  1424. uint32 *p_result)
  1425. {
  1426. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1427. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1428. #endif
  1429. WASMExecEnv *exec_env_created = NULL;
  1430. WASMModuleInstanceCommon *module_inst_old = NULL;
  1431. uint32 argv[2], argc;
  1432. bool ret;
  1433. argv[0] = size;
  1434. argc = 1;
  1435. if (retain_func) {
  1436. argv[1] = 0;
  1437. argc = 2;
  1438. }
  1439. if (exec_env) {
  1440. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1441. if (exec_env_tls) {
  1442. bh_assert(exec_env_tls == exec_env);
  1443. }
  1444. #endif
  1445. bh_assert(exec_env->module_inst
  1446. == (WASMModuleInstanceCommon *)module_inst);
  1447. }
  1448. else {
  1449. /* Try using the existing exec_env */
  1450. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1451. exec_env = exec_env_tls;
  1452. #endif
  1453. #if WASM_ENABLE_THREAD_MGR != 0
  1454. if (!exec_env)
  1455. exec_env = wasm_clusters_search_exec_env(
  1456. (WASMModuleInstanceCommon *)module_inst);
  1457. #endif
  1458. if (!exec_env) {
  1459. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1460. (WASMModuleInstanceCommon *)module_inst,
  1461. module_inst->default_wasm_stack_size))) {
  1462. wasm_set_exception(module_inst, "allocate memory failed");
  1463. return false;
  1464. }
  1465. }
  1466. else {
  1467. /* Temporarily replace exec_env's module inst with current
  1468. module inst to ensure that the exec_env's module inst
  1469. is the correct one. */
  1470. module_inst_old = exec_env->module_inst;
  1471. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  1472. }
  1473. }
  1474. ret = aot_call_function(exec_env, malloc_func, argc, argv);
  1475. if (retain_func && ret)
  1476. ret = aot_call_function(exec_env, retain_func, 1, argv);
  1477. if (module_inst_old)
  1478. /* Restore the existing exec_env's module inst */
  1479. exec_env->module_inst = module_inst_old;
  1480. if (exec_env_created)
  1481. wasm_exec_env_destroy(exec_env_created);
  1482. if (ret)
  1483. *p_result = argv[0];
  1484. return ret;
  1485. }
  1486. static bool
  1487. execute_free_function(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  1488. AOTFunctionInstance *free_func, uint32 offset)
  1489. {
  1490. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1491. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1492. #endif
  1493. WASMExecEnv *exec_env_created = NULL;
  1494. WASMModuleInstanceCommon *module_inst_old = NULL;
  1495. uint32 argv[2];
  1496. bool ret;
  1497. argv[0] = offset;
  1498. if (exec_env) {
  1499. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1500. if (exec_env_tls) {
  1501. bh_assert(exec_env_tls == exec_env);
  1502. }
  1503. #endif
  1504. bh_assert(exec_env->module_inst
  1505. == (WASMModuleInstanceCommon *)module_inst);
  1506. }
  1507. else {
  1508. /* Try using the existing exec_env */
  1509. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1510. exec_env = exec_env_tls;
  1511. #endif
  1512. #if WASM_ENABLE_THREAD_MGR != 0
  1513. if (!exec_env)
  1514. exec_env = wasm_clusters_search_exec_env(
  1515. (WASMModuleInstanceCommon *)module_inst);
  1516. #endif
  1517. if (!exec_env) {
  1518. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1519. (WASMModuleInstanceCommon *)module_inst,
  1520. module_inst->default_wasm_stack_size))) {
  1521. wasm_set_exception(module_inst, "allocate memory failed");
  1522. return false;
  1523. }
  1524. }
  1525. else {
  1526. /* Temporarily replace exec_env's module inst with current
  1527. module inst to ensure that the exec_env's module inst
  1528. is the correct one. */
  1529. module_inst_old = exec_env->module_inst;
  1530. exec_env->module_inst = (WASMModuleInstanceCommon *)module_inst;
  1531. }
  1532. }
  1533. ret = aot_call_function(exec_env, free_func, 1, argv);
  1534. if (module_inst_old)
  1535. /* Restore the existing exec_env's module inst */
  1536. exec_env->module_inst = module_inst_old;
  1537. if (exec_env_created)
  1538. wasm_exec_env_destroy(exec_env_created);
  1539. return ret;
  1540. }
  1541. uint32
  1542. aot_module_malloc_internal(AOTModuleInstance *module_inst,
  1543. WASMExecEnv *exec_env, uint32 size,
  1544. void **p_native_addr)
  1545. {
  1546. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1547. AOTModule *module = (AOTModule *)module_inst->module;
  1548. uint8 *addr = NULL;
  1549. uint32 offset = 0;
  1550. if (!memory_inst) {
  1551. aot_set_exception(module_inst, "uninitialized memory");
  1552. return 0;
  1553. }
  1554. if (memory_inst->heap_handle) {
  1555. addr = mem_allocator_malloc(memory_inst->heap_handle, size);
  1556. }
  1557. else if (module->malloc_func_index != (uint32)-1
  1558. && module->free_func_index != (uint32)-1) {
  1559. AOTFunctionInstance *malloc_func, *retain_func = NULL;
  1560. char *malloc_func_name;
  1561. char *malloc_func_sig;
  1562. if (module->retain_func_index != (uint32)-1) {
  1563. malloc_func_name = "__new";
  1564. malloc_func_sig = "(ii)i";
  1565. retain_func = aot_lookup_function(module_inst, "__retain", "(i)i");
  1566. if (!retain_func)
  1567. retain_func = aot_lookup_function(module_inst, "__pin", "(i)i");
  1568. bh_assert(retain_func);
  1569. }
  1570. else {
  1571. malloc_func_name = "malloc";
  1572. malloc_func_sig = "(i)i";
  1573. }
  1574. malloc_func =
  1575. aot_lookup_function(module_inst, malloc_func_name, malloc_func_sig);
  1576. if (!malloc_func
  1577. || !execute_malloc_function(module_inst, exec_env, malloc_func,
  1578. retain_func, size, &offset)) {
  1579. return 0;
  1580. }
  1581. addr = offset ? (uint8 *)memory_inst->memory_data + offset : NULL;
  1582. }
  1583. if (!addr) {
  1584. if (memory_inst->heap_handle
  1585. && mem_allocator_is_heap_corrupted(memory_inst->heap_handle)) {
  1586. wasm_runtime_show_app_heap_corrupted_prompt();
  1587. aot_set_exception(module_inst, "app heap corrupted");
  1588. }
  1589. else {
  1590. LOG_WARNING("warning: allocate %u bytes memory failed", size);
  1591. }
  1592. return 0;
  1593. }
  1594. if (p_native_addr)
  1595. *p_native_addr = addr;
  1596. return (uint32)(addr - memory_inst->memory_data);
  1597. }
  1598. uint32
  1599. aot_module_realloc_internal(AOTModuleInstance *module_inst,
  1600. WASMExecEnv *exec_env, uint32 ptr, uint32 size,
  1601. void **p_native_addr)
  1602. {
  1603. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1604. uint8 *addr = NULL;
  1605. if (!memory_inst) {
  1606. aot_set_exception(module_inst, "uninitialized memory");
  1607. return 0;
  1608. }
  1609. if (memory_inst->heap_handle) {
  1610. addr = mem_allocator_realloc(
  1611. memory_inst->heap_handle,
  1612. ptr ? memory_inst->memory_data + ptr : NULL, size);
  1613. }
  1614. /* Only support realloc in WAMR's app heap */
  1615. (void)exec_env;
  1616. if (!addr) {
  1617. if (memory_inst->heap_handle
  1618. && mem_allocator_is_heap_corrupted(memory_inst->heap_handle)) {
  1619. aot_set_exception(module_inst, "app heap corrupted");
  1620. }
  1621. else {
  1622. aot_set_exception(module_inst, "out of memory");
  1623. }
  1624. return 0;
  1625. }
  1626. if (p_native_addr)
  1627. *p_native_addr = addr;
  1628. return (uint32)(addr - memory_inst->memory_data);
  1629. }
  1630. void
  1631. aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  1632. uint32 ptr)
  1633. {
  1634. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1635. AOTModule *module = (AOTModule *)module_inst->module;
  1636. if (!memory_inst) {
  1637. return;
  1638. }
  1639. if (ptr) {
  1640. uint8 *addr = memory_inst->memory_data + ptr;
  1641. if (memory_inst->heap_handle && memory_inst->heap_data < addr
  1642. && addr < memory_inst->heap_data_end) {
  1643. mem_allocator_free(memory_inst->heap_handle, addr);
  1644. }
  1645. else if (module->malloc_func_index != (uint32)-1
  1646. && module->free_func_index != (uint32)-1
  1647. && memory_inst->memory_data <= addr
  1648. && addr < memory_inst->memory_data_end) {
  1649. AOTFunctionInstance *free_func;
  1650. char *free_func_name;
  1651. if (module->retain_func_index != (uint32)-1) {
  1652. free_func_name = "__release";
  1653. }
  1654. else {
  1655. free_func_name = "free";
  1656. }
  1657. free_func =
  1658. aot_lookup_function(module_inst, free_func_name, "(i)i");
  1659. if (!free_func && module->retain_func_index != (uint32)-1)
  1660. free_func = aot_lookup_function(module_inst, "__unpin", "(i)i");
  1661. if (free_func)
  1662. execute_free_function(module_inst, exec_env, free_func, ptr);
  1663. }
  1664. }
  1665. }
  1666. uint32
  1667. aot_module_malloc(AOTModuleInstance *module_inst, uint32 size,
  1668. void **p_native_addr)
  1669. {
  1670. return aot_module_malloc_internal(module_inst, NULL, size, p_native_addr);
  1671. }
  1672. uint32
  1673. aot_module_realloc(AOTModuleInstance *module_inst, uint32 ptr, uint32 size,
  1674. void **p_native_addr)
  1675. {
  1676. return aot_module_realloc_internal(module_inst, NULL, ptr, size,
  1677. p_native_addr);
  1678. }
  1679. void
  1680. aot_module_free(AOTModuleInstance *module_inst, uint32 ptr)
  1681. {
  1682. aot_module_free_internal(module_inst, NULL, ptr);
  1683. }
  1684. uint32
  1685. aot_module_dup_data(AOTModuleInstance *module_inst, const char *src,
  1686. uint32 size)
  1687. {
  1688. char *buffer;
  1689. uint32 buffer_offset =
  1690. aot_module_malloc(module_inst, size, (void **)&buffer);
  1691. if (buffer_offset != 0) {
  1692. buffer = wasm_runtime_addr_app_to_native(
  1693. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  1694. bh_memcpy_s(buffer, size, src, size);
  1695. }
  1696. return buffer_offset;
  1697. }
  1698. bool
  1699. aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count)
  1700. {
  1701. return wasm_enlarge_memory(module_inst, inc_page_count);
  1702. }
  1703. bool
  1704. aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  1705. uint32 *argv)
  1706. {
  1707. AOTModuleInstance *module_inst =
  1708. (AOTModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  1709. AOTModule *aot_module = (AOTModule *)module_inst->module;
  1710. AOTModuleInstanceExtra *module_inst_extra =
  1711. (AOTModuleInstanceExtra *)module_inst->e;
  1712. CApiFuncImport *c_api_func_import =
  1713. module_inst_extra->c_api_func_imports
  1714. ? module_inst_extra->c_api_func_imports + func_idx
  1715. : NULL;
  1716. uint32 *func_type_indexes = module_inst->func_type_indexes;
  1717. uint32 func_type_idx = func_type_indexes[func_idx];
  1718. AOTFuncType *func_type = aot_module->func_types[func_type_idx];
  1719. void **func_ptrs = module_inst->func_ptrs;
  1720. void *func_ptr = func_ptrs[func_idx];
  1721. AOTImportFunc *import_func;
  1722. const char *signature;
  1723. void *attachment;
  1724. char buf[96];
  1725. bool ret = false;
  1726. bh_assert(func_idx < aot_module->import_func_count);
  1727. import_func = aot_module->import_funcs + func_idx;
  1728. if (import_func->call_conv_wasm_c_api)
  1729. func_ptr =
  1730. c_api_func_import ? c_api_func_import->func_ptr_linked : NULL;
  1731. if (!func_ptr) {
  1732. snprintf(buf, sizeof(buf),
  1733. "failed to call unlinked import function (%s, %s)",
  1734. import_func->module_name, import_func->func_name);
  1735. aot_set_exception(module_inst, buf);
  1736. goto fail;
  1737. }
  1738. attachment = import_func->attachment;
  1739. if (import_func->call_conv_wasm_c_api) {
  1740. ret = wasm_runtime_invoke_c_api_native(
  1741. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  1742. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  1743. }
  1744. else if (!import_func->call_conv_raw) {
  1745. signature = import_func->signature;
  1746. ret =
  1747. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  1748. attachment, argv, argc, argv);
  1749. }
  1750. else {
  1751. signature = import_func->signature;
  1752. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  1753. signature, attachment, argv, argc,
  1754. argv);
  1755. }
  1756. fail:
  1757. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1758. if (!ret)
  1759. wasm_runtime_access_exce_check_guard_page();
  1760. #endif
  1761. return ret;
  1762. }
  1763. bool
  1764. aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx,
  1765. uint32 argc, uint32 *argv)
  1766. {
  1767. AOTModuleInstance *module_inst =
  1768. (AOTModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  1769. AOTModule *aot_module = (AOTModule *)module_inst->module;
  1770. uint32 *func_type_indexes = module_inst->func_type_indexes;
  1771. AOTTableInstance *tbl_inst;
  1772. AOTFuncType *func_type;
  1773. void **func_ptrs = module_inst->func_ptrs, *func_ptr;
  1774. uint32 func_type_idx, func_idx, ext_ret_count;
  1775. table_elem_type_t tbl_elem_val = NULL_REF;
  1776. AOTImportFunc *import_func;
  1777. const char *signature = NULL;
  1778. void *attachment = NULL;
  1779. char buf[96];
  1780. bool ret;
  1781. /* this function is called from native code, so exec_env->handle and
  1782. exec_env->native_stack_boundary must have been set, we don't set
  1783. it again */
  1784. RECORD_STACK_USAGE(exec_env, (uint8 *)&module_inst);
  1785. if ((uint8 *)&module_inst < exec_env->native_stack_boundary) {
  1786. aot_set_exception_with_id(module_inst, EXCE_NATIVE_STACK_OVERFLOW);
  1787. goto fail;
  1788. }
  1789. tbl_inst = module_inst->tables[tbl_idx];
  1790. bh_assert(tbl_inst);
  1791. if (table_elem_idx >= tbl_inst->cur_size) {
  1792. aot_set_exception_with_id(module_inst, EXCE_UNDEFINED_ELEMENT);
  1793. goto fail;
  1794. }
  1795. tbl_elem_val = ((table_elem_type_t *)tbl_inst->elems)[table_elem_idx];
  1796. if (tbl_elem_val == NULL_REF) {
  1797. aot_set_exception_with_id(module_inst, EXCE_UNINITIALIZED_ELEMENT);
  1798. goto fail;
  1799. }
  1800. #if WASM_ENABLE_GC == 0
  1801. func_idx = tbl_elem_val;
  1802. #else
  1803. func_idx =
  1804. wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val);
  1805. #endif
  1806. func_type_idx = func_type_indexes[func_idx];
  1807. func_type = aot_module->func_types[func_type_idx];
  1808. if (func_idx >= aot_module->import_func_count) {
  1809. /* func pointer was looked up previously */
  1810. bh_assert(func_ptrs[func_idx] != NULL);
  1811. }
  1812. if (!(func_ptr = func_ptrs[func_idx])) {
  1813. bh_assert(func_idx < aot_module->import_func_count);
  1814. import_func = aot_module->import_funcs + func_idx;
  1815. snprintf(buf, sizeof(buf),
  1816. "failed to call unlinked import function (%s, %s)",
  1817. import_func->module_name, import_func->func_name);
  1818. aot_set_exception(module_inst, buf);
  1819. goto fail;
  1820. }
  1821. if (func_idx < aot_module->import_func_count) {
  1822. /* Call native function */
  1823. import_func = aot_module->import_funcs + func_idx;
  1824. signature = import_func->signature;
  1825. if (import_func->call_conv_raw) {
  1826. attachment = import_func->attachment;
  1827. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  1828. signature, attachment, argv,
  1829. argc, argv);
  1830. if (!ret)
  1831. goto fail;
  1832. return true;
  1833. }
  1834. }
  1835. ext_ret_count =
  1836. func_type->result_count > 1 ? func_type->result_count - 1 : 0;
  1837. if (ext_ret_count > 0) {
  1838. uint32 argv1_buf[32], *argv1 = argv1_buf;
  1839. uint32 *ext_rets = NULL, *argv_ret = argv;
  1840. uint32 cell_num = 0, i;
  1841. uint8 *ext_ret_types = func_type->types + func_type->param_count + 1;
  1842. uint32 ext_ret_cell = wasm_get_cell_num(ext_ret_types, ext_ret_count);
  1843. uint64 size;
  1844. /* Allocate memory all arguments */
  1845. size =
  1846. sizeof(uint32) * (uint64)argc /* original arguments */
  1847. + sizeof(void *)
  1848. * (uint64)ext_ret_count /* extra result values' addr */
  1849. + sizeof(uint32) * (uint64)ext_ret_cell; /* extra result values */
  1850. if (size > sizeof(argv1_buf)
  1851. && !(argv1 = runtime_malloc(size, module_inst->cur_exception,
  1852. sizeof(module_inst->cur_exception)))) {
  1853. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_MEMORY);
  1854. goto fail;
  1855. }
  1856. /* Copy original arguments */
  1857. bh_memcpy_s(argv1, (uint32)size, argv, sizeof(uint32) * argc);
  1858. /* Get the extra result value's address */
  1859. ext_rets =
  1860. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1861. /* Append each extra result value's address to original arguments */
  1862. for (i = 0; i < ext_ret_count; i++) {
  1863. *(uintptr_t *)(argv1 + argc + sizeof(void *) / sizeof(uint32) * i) =
  1864. (uintptr_t)(ext_rets + cell_num);
  1865. cell_num += wasm_value_type_cell_num(ext_ret_types[i]);
  1866. }
  1867. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  1868. attachment, argv1, argc, argv);
  1869. if (!ret) {
  1870. if (argv1 != argv1_buf)
  1871. wasm_runtime_free(argv1);
  1872. goto fail;
  1873. }
  1874. /* Get extra result values */
  1875. switch (func_type->types[func_type->param_count]) {
  1876. case VALUE_TYPE_I32:
  1877. case VALUE_TYPE_F32:
  1878. #if WASM_ENABLE_REF_TYPES != 0
  1879. case VALUE_TYPE_FUNCREF:
  1880. case VALUE_TYPE_EXTERNREF:
  1881. #endif
  1882. argv_ret++;
  1883. break;
  1884. case VALUE_TYPE_I64:
  1885. case VALUE_TYPE_F64:
  1886. argv_ret += 2;
  1887. break;
  1888. #if WASM_ENABLE_SIMD != 0
  1889. case VALUE_TYPE_V128:
  1890. argv_ret += 4;
  1891. break;
  1892. #endif
  1893. default:
  1894. bh_assert(0);
  1895. break;
  1896. }
  1897. ext_rets =
  1898. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1899. bh_memcpy_s(argv_ret, sizeof(uint32) * cell_num, ext_rets,
  1900. sizeof(uint32) * cell_num);
  1901. if (argv1 != argv1_buf)
  1902. wasm_runtime_free(argv1);
  1903. return true;
  1904. }
  1905. else {
  1906. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  1907. attachment, argv, argc, argv);
  1908. if (!ret)
  1909. goto fail;
  1910. return true;
  1911. }
  1912. fail:
  1913. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1914. wasm_runtime_access_exce_check_guard_page();
  1915. #endif
  1916. return false;
  1917. }
  1918. bool
  1919. aot_check_app_addr_and_convert(AOTModuleInstance *module_inst, bool is_str,
  1920. uint32 app_buf_addr, uint32 app_buf_size,
  1921. void **p_native_addr)
  1922. {
  1923. bool ret;
  1924. ret = wasm_check_app_addr_and_convert(module_inst, is_str, app_buf_addr,
  1925. app_buf_size, p_native_addr);
  1926. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1927. if (!ret)
  1928. wasm_runtime_access_exce_check_guard_page();
  1929. #endif
  1930. return ret;
  1931. }
  1932. void *
  1933. aot_memmove(void *dest, const void *src, size_t n)
  1934. {
  1935. return memmove(dest, src, n);
  1936. }
  1937. void *
  1938. aot_memset(void *s, int c, size_t n)
  1939. {
  1940. return memset(s, c, n);
  1941. }
  1942. double
  1943. aot_sqrt(double x)
  1944. {
  1945. return sqrt(x);
  1946. }
  1947. float
  1948. aot_sqrtf(float x)
  1949. {
  1950. return sqrtf(x);
  1951. }
  1952. #if WASM_ENABLE_BULK_MEMORY != 0
  1953. bool
  1954. aot_memory_init(AOTModuleInstance *module_inst, uint32 seg_index, uint32 offset,
  1955. uint32 len, uint32 dst)
  1956. {
  1957. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1958. AOTModule *aot_module;
  1959. uint8 *data = NULL;
  1960. uint8 *maddr;
  1961. uint64 seg_len = 0;
  1962. aot_module = (AOTModule *)module_inst->module;
  1963. seg_len = aot_module->mem_init_data_list[seg_index]->byte_count;
  1964. data = aot_module->mem_init_data_list[seg_index]->bytes;
  1965. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  1966. dst, len))
  1967. return false;
  1968. if ((uint64)offset + (uint64)len > seg_len) {
  1969. aot_set_exception(module_inst, "out of bounds memory access");
  1970. return false;
  1971. }
  1972. maddr = wasm_runtime_addr_app_to_native(
  1973. (WASMModuleInstanceCommon *)module_inst, dst);
  1974. bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len);
  1975. return true;
  1976. }
  1977. bool
  1978. aot_data_drop(AOTModuleInstance *module_inst, uint32 seg_index)
  1979. {
  1980. AOTModule *aot_module = (AOTModule *)module_inst->module;
  1981. aot_module->mem_init_data_list[seg_index]->byte_count = 0;
  1982. /* Currently we can't free the dropped data segment
  1983. as the mem_init_data_count is a continuous array */
  1984. return true;
  1985. }
  1986. #endif /* WASM_ENABLE_BULK_MEMORY */
  1987. #if WASM_ENABLE_THREAD_MGR != 0
  1988. bool
  1989. aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size)
  1990. {
  1991. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1992. AOTModule *module = (AOTModule *)module_inst->module;
  1993. uint32 stack_top_idx = module->aux_stack_top_global_index;
  1994. uint32 data_end = module->aux_data_end;
  1995. uint32 stack_bottom = module->aux_stack_bottom;
  1996. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  1997. /* Check the aux stack space, currently we don't allocate space in heap */
  1998. if ((is_stack_before_data && (size > start_offset))
  1999. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  2000. return false;
  2001. if (stack_top_idx != (uint32)-1) {
  2002. /* The aux stack top is a wasm global,
  2003. set the initial value for the global */
  2004. uint32 global_offset = module->globals[stack_top_idx].data_offset;
  2005. uint8 *global_addr = module_inst->global_data + global_offset;
  2006. *(int32 *)global_addr = start_offset;
  2007. /* The aux stack boundary is a constant value,
  2008. set the value to exec_env */
  2009. exec_env->aux_stack_boundary.boundary = start_offset - size;
  2010. exec_env->aux_stack_bottom.bottom = start_offset;
  2011. return true;
  2012. }
  2013. return false;
  2014. }
  2015. bool
  2016. aot_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size)
  2017. {
  2018. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2019. AOTModule *module = (AOTModule *)module_inst->module;
  2020. /* The aux stack information is resolved in loader
  2021. and store in module */
  2022. uint32 stack_bottom = module->aux_stack_bottom;
  2023. uint32 total_aux_stack_size = module->aux_stack_size;
  2024. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  2025. if (start_offset)
  2026. *start_offset = stack_bottom;
  2027. if (size)
  2028. *size = total_aux_stack_size;
  2029. return true;
  2030. }
  2031. return false;
  2032. }
  2033. #endif
  2034. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  2035. static void
  2036. const_string_node_size_cb(void *key, void *value, void *p_const_string_size)
  2037. {
  2038. uint32 const_string_size = 0;
  2039. const_string_size += bh_hash_map_get_elem_struct_size();
  2040. const_string_size += strlen((const char *)value) + 1;
  2041. *(uint32 *)p_const_string_size += const_string_size;
  2042. }
  2043. void
  2044. aot_get_module_mem_consumption(const AOTModule *module,
  2045. WASMModuleMemConsumption *mem_conspn)
  2046. {
  2047. uint32 i, size;
  2048. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2049. mem_conspn->module_struct_size = sizeof(AOTModule);
  2050. mem_conspn->types_size = sizeof(AOTFuncType *) * module->func_type_count;
  2051. for (i = 0; i < module->func_type_count; i++) {
  2052. AOTFuncType *type = module->func_types[i];
  2053. size = offsetof(AOTFuncType, types)
  2054. + sizeof(uint8) * (type->param_count + type->result_count);
  2055. mem_conspn->types_size += size;
  2056. }
  2057. mem_conspn->imports_size =
  2058. sizeof(AOTImportMemory) * module->import_memory_count
  2059. + sizeof(AOTImportTable) * module->import_table_count
  2060. + sizeof(AOTImportGlobal) * module->import_global_count
  2061. + sizeof(AOTImportFunc) * module->import_func_count;
  2062. /* func_ptrs and func_type_indexes */
  2063. mem_conspn->functions_size =
  2064. (sizeof(void *) + sizeof(uint32)) * module->func_count;
  2065. mem_conspn->tables_size = sizeof(AOTTable) * module->table_count;
  2066. mem_conspn->memories_size = sizeof(AOTMemory) * module->memory_count;
  2067. mem_conspn->globals_size = sizeof(AOTGlobal) * module->global_count;
  2068. mem_conspn->exports_size = sizeof(AOTExport) * module->export_count;
  2069. mem_conspn->table_segs_size =
  2070. sizeof(AOTTableInitData *) * module->table_init_data_count;
  2071. for (i = 0; i < module->table_init_data_count; i++) {
  2072. AOTTableInitData *init_data = module->table_init_data_list[i];
  2073. size = offsetof(AOTTableInitData, func_indexes)
  2074. + sizeof(uint32) * init_data->func_index_count;
  2075. mem_conspn->table_segs_size += size;
  2076. }
  2077. mem_conspn->data_segs_size =
  2078. sizeof(AOTMemInitData *) * module->mem_init_data_count;
  2079. for (i = 0; i < module->mem_init_data_count; i++) {
  2080. mem_conspn->data_segs_size += sizeof(AOTMemInitData);
  2081. }
  2082. if (module->const_str_set) {
  2083. uint32 const_string_size = 0;
  2084. mem_conspn->const_strs_size =
  2085. bh_hash_map_get_struct_size(module->const_str_set);
  2086. bh_hash_map_traverse(module->const_str_set, const_string_node_size_cb,
  2087. (void *)&const_string_size);
  2088. mem_conspn->const_strs_size += const_string_size;
  2089. }
  2090. /* code size + literal size + object data section size */
  2091. mem_conspn->aot_code_size =
  2092. module->code_size + module->literal_size
  2093. + sizeof(AOTObjectDataSection) * module->data_section_count;
  2094. for (i = 0; i < module->data_section_count; i++) {
  2095. AOTObjectDataSection *obj_data = module->data_sections + i;
  2096. mem_conspn->aot_code_size += sizeof(uint8) * obj_data->size;
  2097. }
  2098. mem_conspn->total_size += mem_conspn->module_struct_size;
  2099. mem_conspn->total_size += mem_conspn->types_size;
  2100. mem_conspn->total_size += mem_conspn->imports_size;
  2101. mem_conspn->total_size += mem_conspn->functions_size;
  2102. mem_conspn->total_size += mem_conspn->tables_size;
  2103. mem_conspn->total_size += mem_conspn->memories_size;
  2104. mem_conspn->total_size += mem_conspn->globals_size;
  2105. mem_conspn->total_size += mem_conspn->exports_size;
  2106. mem_conspn->total_size += mem_conspn->table_segs_size;
  2107. mem_conspn->total_size += mem_conspn->data_segs_size;
  2108. mem_conspn->total_size += mem_conspn->const_strs_size;
  2109. mem_conspn->total_size += mem_conspn->aot_code_size;
  2110. }
  2111. void
  2112. aot_get_module_inst_mem_consumption(const AOTModuleInstance *module_inst,
  2113. WASMModuleInstMemConsumption *mem_conspn)
  2114. {
  2115. AOTTableInstance *tbl_inst;
  2116. uint32 i;
  2117. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2118. mem_conspn->module_inst_struct_size = sizeof(AOTModuleInstance);
  2119. mem_conspn->memories_size =
  2120. sizeof(void *) * module_inst->memory_count
  2121. + sizeof(AOTMemoryInstance) * module_inst->memory_count;
  2122. for (i = 0; i < module_inst->memory_count; i++) {
  2123. AOTMemoryInstance *mem_inst = module_inst->memories[i];
  2124. mem_conspn->memories_size +=
  2125. mem_inst->num_bytes_per_page * mem_inst->cur_page_count;
  2126. mem_conspn->app_heap_size =
  2127. mem_inst->heap_data_end - mem_inst->heap_data;
  2128. /* size of app heap structure */
  2129. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  2130. }
  2131. mem_conspn->tables_size +=
  2132. sizeof(AOTTableInstance *) * module_inst->table_count;
  2133. for (i = 0; i < module_inst->table_count; i++) {
  2134. tbl_inst = module_inst->tables[i];
  2135. mem_conspn->tables_size += offsetof(AOTTableInstance, elems);
  2136. mem_conspn->tables_size += sizeof(uint32) * tbl_inst->max_size;
  2137. }
  2138. /* func_ptrs and func_type_indexes */
  2139. mem_conspn->functions_size =
  2140. (sizeof(void *) + sizeof(uint32))
  2141. * (((AOTModule *)module_inst->module)->import_func_count
  2142. + ((AOTModule *)module_inst->module)->func_count);
  2143. mem_conspn->globals_size = module_inst->global_data_size;
  2144. mem_conspn->exports_size =
  2145. sizeof(AOTFunctionInstance) * (uint64)module_inst->export_func_count;
  2146. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  2147. mem_conspn->total_size += mem_conspn->memories_size;
  2148. mem_conspn->total_size += mem_conspn->functions_size;
  2149. mem_conspn->total_size += mem_conspn->tables_size;
  2150. mem_conspn->total_size += mem_conspn->globals_size;
  2151. mem_conspn->total_size += mem_conspn->exports_size;
  2152. }
  2153. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  2154. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  2155. #if WASM_ENABLE_REF_TYPES != 0
  2156. void
  2157. aot_drop_table_seg(AOTModuleInstance *module_inst, uint32 tbl_seg_idx)
  2158. {
  2159. AOTModule *module = (AOTModule *)module_inst->module;
  2160. AOTTableInitData *tbl_seg = module->table_init_data_list[tbl_seg_idx];
  2161. tbl_seg->is_dropped = true;
  2162. }
  2163. void
  2164. aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx,
  2165. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  2166. uint32 dst_offset)
  2167. {
  2168. AOTTableInstance *tbl_inst;
  2169. AOTTableInitData *tbl_seg;
  2170. const AOTModule *module = (AOTModule *)module_inst->module;
  2171. tbl_inst = module_inst->tables[tbl_idx];
  2172. bh_assert(tbl_inst);
  2173. tbl_seg = module->table_init_data_list[tbl_seg_idx];
  2174. bh_assert(tbl_seg);
  2175. if (!length) {
  2176. return;
  2177. }
  2178. if (length + src_offset > tbl_seg->func_index_count
  2179. || dst_offset + length > tbl_inst->cur_size) {
  2180. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2181. return;
  2182. }
  2183. if (tbl_seg->is_dropped) {
  2184. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2185. return;
  2186. }
  2187. if (!wasm_elem_is_passive(tbl_seg->mode)) {
  2188. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2189. return;
  2190. }
  2191. bh_memcpy_s((uint8 *)tbl_inst + offsetof(AOTTableInstance, elems)
  2192. + dst_offset * sizeof(uint32),
  2193. (tbl_inst->cur_size - dst_offset) * sizeof(uint32),
  2194. tbl_seg->func_indexes + src_offset, length * sizeof(uint32));
  2195. }
  2196. void
  2197. aot_table_copy(AOTModuleInstance *module_inst, uint32 src_tbl_idx,
  2198. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  2199. uint32 dst_offset)
  2200. {
  2201. AOTTableInstance *src_tbl_inst, *dst_tbl_inst;
  2202. src_tbl_inst = module_inst->tables[src_tbl_idx];
  2203. bh_assert(src_tbl_inst);
  2204. dst_tbl_inst = module_inst->tables[dst_tbl_idx];
  2205. bh_assert(dst_tbl_inst);
  2206. if ((uint64)dst_offset + length > dst_tbl_inst->cur_size
  2207. || (uint64)src_offset + length > src_tbl_inst->cur_size) {
  2208. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2209. return;
  2210. }
  2211. /* if src_offset >= dst_offset, copy from front to back */
  2212. /* if src_offset < dst_offset, copy from back to front */
  2213. /* merge all together */
  2214. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(AOTTableInstance, elems)
  2215. + dst_offset * sizeof(uint32),
  2216. (dst_tbl_inst->cur_size - dst_offset) * sizeof(uint32),
  2217. (uint8 *)src_tbl_inst + offsetof(AOTTableInstance, elems)
  2218. + src_offset * sizeof(uint32),
  2219. length * sizeof(uint32));
  2220. }
  2221. void
  2222. aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length,
  2223. table_elem_type_t val, uint32 data_offset)
  2224. {
  2225. AOTTableInstance *tbl_inst;
  2226. tbl_inst = module_inst->tables[tbl_idx];
  2227. bh_assert(tbl_inst);
  2228. if (data_offset + length > tbl_inst->cur_size) {
  2229. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2230. return;
  2231. }
  2232. for (; length != 0; data_offset++, length--) {
  2233. tbl_inst->elems[data_offset] = val;
  2234. }
  2235. }
  2236. uint32
  2237. aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx,
  2238. uint32 inc_entries, table_elem_type_t init_val)
  2239. {
  2240. uint32 entry_count, i, orig_tbl_sz;
  2241. AOTTableInstance *tbl_inst;
  2242. tbl_inst = module_inst->tables[tbl_idx];
  2243. if (!tbl_inst) {
  2244. return (uint32)-1;
  2245. }
  2246. orig_tbl_sz = tbl_inst->cur_size;
  2247. if (!inc_entries) {
  2248. return orig_tbl_sz;
  2249. }
  2250. if (tbl_inst->cur_size > UINT32_MAX - inc_entries) {
  2251. return (uint32)-1;
  2252. }
  2253. entry_count = tbl_inst->cur_size + inc_entries;
  2254. if (entry_count > tbl_inst->max_size) {
  2255. return (uint32)-1;
  2256. }
  2257. /* fill in */
  2258. for (i = 0; i < inc_entries; ++i) {
  2259. tbl_inst->elems[tbl_inst->cur_size + i] = init_val;
  2260. }
  2261. tbl_inst->cur_size = entry_count;
  2262. return orig_tbl_sz;
  2263. }
  2264. #endif /* WASM_ENABLE_REF_TYPES != 0 */
  2265. #if (WASM_ENABLE_DUMP_CALL_STACK != 0) || (WASM_ENABLE_PERF_PROFILING != 0)
  2266. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2267. static const char *
  2268. lookup_func_name(const char **func_names, uint32 *func_indexes,
  2269. uint32 func_index_count, uint32 func_index)
  2270. {
  2271. int64 low = 0, mid;
  2272. int64 high = func_index_count - 1;
  2273. if (!func_names || !func_indexes || func_index_count == 0)
  2274. return NULL;
  2275. while (low <= high) {
  2276. mid = (low + high) / 2;
  2277. if (func_index == func_indexes[mid]) {
  2278. return func_names[mid];
  2279. }
  2280. else if (func_index < func_indexes[mid])
  2281. high = mid - 1;
  2282. else
  2283. low = mid + 1;
  2284. }
  2285. return NULL;
  2286. }
  2287. #endif /* WASM_ENABLE_CUSTOM_NAME_SECTION != 0 */
  2288. static const char *
  2289. get_func_name_from_index(const AOTModuleInstance *module_inst,
  2290. uint32 func_index)
  2291. {
  2292. const char *func_name = NULL;
  2293. AOTModule *module = (AOTModule *)module_inst->module;
  2294. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2295. if ((func_name =
  2296. lookup_func_name(module->aux_func_names, module->aux_func_indexes,
  2297. module->aux_func_name_count, func_index))) {
  2298. return func_name;
  2299. }
  2300. #endif
  2301. if (func_index < module->import_func_count) {
  2302. func_name = module->import_funcs[func_index].func_name;
  2303. }
  2304. else {
  2305. uint32 i;
  2306. for (i = 0; i < module->export_count; i++) {
  2307. AOTExport export = module->exports[i];
  2308. if (export.index == func_index && export.kind == EXPORT_KIND_FUNC) {
  2309. func_name = export.name;
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. return func_name;
  2315. }
  2316. bool
  2317. aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  2318. {
  2319. AOTFrame *frame =
  2320. wasm_exec_env_alloc_wasm_frame(exec_env, sizeof(AOTFrame));
  2321. #if WASM_ENABLE_PERF_PROFILING != 0
  2322. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2323. AOTFuncPerfProfInfo *func_perf_prof =
  2324. module_inst->func_perf_profilings + func_index;
  2325. #endif
  2326. if (!frame) {
  2327. aot_set_exception((AOTModuleInstance *)exec_env->module_inst,
  2328. "auxiliary call stack overflow");
  2329. return false;
  2330. }
  2331. #if WASM_ENABLE_PERF_PROFILING != 0
  2332. frame->time_started = os_time_get_boot_microsecond();
  2333. frame->func_perf_prof_info = func_perf_prof;
  2334. #endif
  2335. frame->prev_frame = (AOTFrame *)exec_env->cur_frame;
  2336. exec_env->cur_frame = (struct WASMInterpFrame *)frame;
  2337. frame->func_index = func_index;
  2338. return true;
  2339. }
  2340. void
  2341. aot_free_frame(WASMExecEnv *exec_env)
  2342. {
  2343. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  2344. AOTFrame *prev_frame = cur_frame->prev_frame;
  2345. #if WASM_ENABLE_PERF_PROFILING != 0
  2346. cur_frame->func_perf_prof_info->total_exec_time +=
  2347. os_time_get_boot_microsecond() - cur_frame->time_started;
  2348. cur_frame->func_perf_prof_info->total_exec_cnt++;
  2349. #endif
  2350. wasm_exec_env_free_wasm_frame(exec_env, cur_frame);
  2351. exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame;
  2352. }
  2353. #endif /* end of (WASM_ENABLE_DUMP_CALL_STACK != 0) \
  2354. || (WASM_ENABLE_PERF_PROFILING != 0) */
  2355. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2356. bool
  2357. aot_create_call_stack(struct WASMExecEnv *exec_env)
  2358. {
  2359. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame,
  2360. *first_frame = cur_frame;
  2361. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2362. uint32 n = 0;
  2363. while (cur_frame) {
  2364. cur_frame = cur_frame->prev_frame;
  2365. n++;
  2366. }
  2367. /* release previous stack frames and create new ones */
  2368. if (!bh_vector_destroy(module_inst->frames)
  2369. || !bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame),
  2370. false)) {
  2371. return false;
  2372. }
  2373. cur_frame = first_frame;
  2374. while (cur_frame) {
  2375. WASMCApiFrame frame = { 0 };
  2376. frame.instance = module_inst;
  2377. frame.module_offset = 0;
  2378. frame.func_index = cur_frame->func_index;
  2379. frame.func_offset = 0;
  2380. frame.func_name_wp =
  2381. get_func_name_from_index(module_inst, cur_frame->func_index);
  2382. if (!bh_vector_append(module_inst->frames, &frame)) {
  2383. bh_vector_destroy(module_inst->frames);
  2384. return false;
  2385. }
  2386. cur_frame = cur_frame->prev_frame;
  2387. }
  2388. return true;
  2389. }
  2390. #define PRINT_OR_DUMP() \
  2391. do { \
  2392. total_len += \
  2393. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  2394. if ((!print) && buf && (len == 0)) { \
  2395. return total_len; \
  2396. } \
  2397. } while (0)
  2398. uint32
  2399. aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len)
  2400. {
  2401. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2402. uint32 n = 0, total_len = 0, total_frames;
  2403. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  2404. * will be truncated */
  2405. char line_buf[256];
  2406. if (!module_inst->frames) {
  2407. return 0;
  2408. }
  2409. total_frames = (uint32)bh_vector_size(module_inst->frames);
  2410. if (total_frames == 0) {
  2411. return 0;
  2412. }
  2413. snprintf(line_buf, sizeof(line_buf), "\n");
  2414. PRINT_OR_DUMP();
  2415. while (n < total_frames) {
  2416. WASMCApiFrame frame = { 0 };
  2417. uint32 line_length, i;
  2418. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  2419. return 0;
  2420. }
  2421. /* function name not exported, print number instead */
  2422. if (frame.func_name_wp == NULL) {
  2423. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d $f%d\n",
  2424. n, frame.func_index);
  2425. }
  2426. else {
  2427. line_length = snprintf(line_buf, sizeof(line_buf), "#%02d %s\n", n,
  2428. frame.func_name_wp);
  2429. }
  2430. if (line_length >= sizeof(line_buf)) {
  2431. uint32 line_buffer_len = sizeof(line_buf);
  2432. /* If line too long, ensure the last character is '\n' */
  2433. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  2434. line_buf[i] = '.';
  2435. }
  2436. line_buf[line_buffer_len - 2] = '\n';
  2437. }
  2438. PRINT_OR_DUMP();
  2439. n++;
  2440. }
  2441. snprintf(line_buf, sizeof(line_buf), "\n");
  2442. PRINT_OR_DUMP();
  2443. return total_len + 1;
  2444. }
  2445. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  2446. #if WASM_ENABLE_PERF_PROFILING != 0
  2447. void
  2448. aot_dump_perf_profiling(const AOTModuleInstance *module_inst)
  2449. {
  2450. AOTFuncPerfProfInfo *perf_prof =
  2451. (AOTFuncPerfProfInfo *)module_inst->func_perf_profilings;
  2452. AOTModule *module = (AOTModule *)module_inst->module;
  2453. uint32 total_func_count = module->import_func_count + module->func_count, i;
  2454. const char *func_name;
  2455. os_printf("Performance profiler data:\n");
  2456. for (i = 0; i < total_func_count; i++, perf_prof++) {
  2457. func_name = get_func_name_from_index(module_inst, i);
  2458. if (func_name)
  2459. os_printf(" func %s, execution time: %.3f ms, execution count: %d "
  2460. "times\n",
  2461. func_name, perf_prof->total_exec_time / 1000.0f,
  2462. perf_prof->total_exec_cnt);
  2463. else
  2464. os_printf(" func %d, execution time: %.3f ms, execution count: %d "
  2465. "times\n",
  2466. i, perf_prof->total_exec_time / 1000.0f,
  2467. perf_prof->total_exec_cnt);
  2468. }
  2469. }
  2470. #endif /* end of WASM_ENABLE_PERF_PROFILING */