aot_runtime.c 119 KB

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