aot_runtime.c 113 KB

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