aot_runtime.c 120 KB

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