aot_runtime.c 121 KB

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