aot_runtime.c 158 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631
  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, cur_frame) == 1 * sizeof(uintptr_t));
  22. bh_static_assert(offsetof(WASMExecEnv, module_inst) == 2 * sizeof(uintptr_t));
  23. bh_static_assert(offsetof(WASMExecEnv, argv_buf) == 3 * sizeof(uintptr_t));
  24. bh_static_assert(offsetof(WASMExecEnv, native_stack_boundary)
  25. == 4 * sizeof(uintptr_t));
  26. bh_static_assert(offsetof(WASMExecEnv, suspend_flags) == 5 * sizeof(uintptr_t));
  27. bh_static_assert(offsetof(WASMExecEnv, aux_stack_boundary)
  28. == 6 * sizeof(uintptr_t));
  29. bh_static_assert(offsetof(WASMExecEnv, aux_stack_bottom)
  30. == 7 * sizeof(uintptr_t));
  31. bh_static_assert(offsetof(WASMExecEnv, native_symbol) == 8 * sizeof(uintptr_t));
  32. bh_static_assert(offsetof(WASMExecEnv, native_stack_top_min)
  33. == 9 * sizeof(uintptr_t));
  34. bh_static_assert(offsetof(WASMExecEnv, wasm_stack.top_boundary)
  35. == 10 * sizeof(uintptr_t));
  36. bh_static_assert(offsetof(WASMExecEnv, wasm_stack.top)
  37. == 11 * sizeof(uintptr_t));
  38. bh_static_assert(offsetof(WASMExecEnv, wasm_stack.bottom)
  39. == 12 * sizeof(uintptr_t));
  40. bh_static_assert(offsetof(AOTModuleInstance, memories) == 1 * sizeof(uint64));
  41. bh_static_assert(offsetof(AOTModuleInstance, func_ptrs) == 5 * sizeof(uint64));
  42. bh_static_assert(offsetof(AOTModuleInstance, func_type_indexes)
  43. == 6 * sizeof(uint64));
  44. bh_static_assert(offsetof(AOTModuleInstance, cur_exception)
  45. == 13 * sizeof(uint64));
  46. bh_static_assert(offsetof(AOTModuleInstance, global_table_data)
  47. == 13 * sizeof(uint64) + 128 + 11 * sizeof(uint64));
  48. bh_static_assert(sizeof(AOTMemoryInstance) == 104);
  49. bh_static_assert(offsetof(AOTTableInstance, elems) == 24);
  50. bh_static_assert(offsetof(AOTModuleInstanceExtra, stack_sizes) == 0);
  51. bh_static_assert(offsetof(AOTModuleInstanceExtra, common.c_api_func_imports)
  52. == sizeof(uint64));
  53. bh_static_assert(sizeof(CApiFuncImport) == sizeof(uintptr_t) * 3);
  54. bh_static_assert(sizeof(wasm_val_t) == 16);
  55. bh_static_assert(offsetof(wasm_val_t, of) == 8);
  56. bh_static_assert(offsetof(AOTFrame, prev_frame) == sizeof(uintptr_t) * 0);
  57. bh_static_assert(offsetof(AOTFrame, func_index) == sizeof(uintptr_t) * 1);
  58. bh_static_assert(offsetof(AOTFrame, time_started) == sizeof(uintptr_t) * 2);
  59. bh_static_assert(offsetof(AOTFrame, func_perf_prof_info)
  60. == sizeof(uintptr_t) * 3);
  61. bh_static_assert(offsetof(AOTFrame, ip_offset) == sizeof(uintptr_t) * 4);
  62. bh_static_assert(offsetof(AOTFrame, sp) == sizeof(uintptr_t) * 5);
  63. bh_static_assert(offsetof(AOTFrame, frame_ref) == sizeof(uintptr_t) * 6);
  64. bh_static_assert(offsetof(AOTFrame, lp) == sizeof(uintptr_t) * 7);
  65. static void
  66. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  67. {
  68. if (error_buf != NULL) {
  69. snprintf(error_buf, error_buf_size, "AOT module instantiate failed: %s",
  70. string);
  71. }
  72. }
  73. static void
  74. set_error_buf_v(char *error_buf, uint32 error_buf_size, const char *format, ...)
  75. {
  76. va_list args;
  77. char buf[128];
  78. if (error_buf != NULL) {
  79. va_start(args, format);
  80. vsnprintf(buf, sizeof(buf), format, args);
  81. va_end(args);
  82. snprintf(error_buf, error_buf_size, "AOT module instantiate failed: %s",
  83. buf);
  84. }
  85. }
  86. static void *
  87. runtime_malloc(uint64 size, char *error_buf, uint32 error_buf_size)
  88. {
  89. void *mem;
  90. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  91. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  92. return NULL;
  93. }
  94. memset(mem, 0, (uint32)size);
  95. return mem;
  96. }
  97. static bool
  98. check_global_init_expr(const AOTModule *module, uint32 global_index,
  99. char *error_buf, uint32 error_buf_size)
  100. {
  101. if (global_index >= module->import_global_count + module->global_count) {
  102. set_error_buf_v(error_buf, error_buf_size, "unknown global %d",
  103. global_index);
  104. return false;
  105. }
  106. #if WASM_ENABLE_GC == 0
  107. /**
  108. * Currently, constant expressions occurring as initializers of
  109. * globals are further constrained in that contained global.get
  110. * instructions are only allowed to refer to imported globals.
  111. *
  112. * And initializer expression cannot reference a mutable global.
  113. */
  114. if (global_index >= module->import_global_count
  115. || module->import_globals->is_mutable) {
  116. set_error_buf(error_buf, error_buf_size,
  117. "constant expression required");
  118. return false;
  119. }
  120. #else
  121. if (global_index >= module->import_global_count + module->global_count) {
  122. set_error_buf_v(error_buf, error_buf_size, "unknown global %u",
  123. global_index);
  124. return false;
  125. }
  126. if (global_index < module->import_global_count
  127. && module->import_globals[global_index].is_mutable) {
  128. set_error_buf(error_buf, error_buf_size,
  129. "constant expression required");
  130. return false;
  131. }
  132. #endif
  133. return true;
  134. }
  135. static void
  136. init_global_data(uint8 *global_data, uint8 type, WASMValue *initial_value)
  137. {
  138. switch (type) {
  139. case VALUE_TYPE_I32:
  140. case VALUE_TYPE_F32:
  141. #if WASM_ENABLE_REF_TYPES != 0
  142. case VALUE_TYPE_FUNCREF:
  143. case VALUE_TYPE_EXTERNREF:
  144. #endif
  145. *(int32 *)global_data = initial_value->i32;
  146. break;
  147. case VALUE_TYPE_I64:
  148. case VALUE_TYPE_F64:
  149. bh_memcpy_s(global_data, sizeof(int64), &initial_value->i64,
  150. sizeof(int64));
  151. break;
  152. #if WASM_ENABLE_SIMD != 0
  153. case VALUE_TYPE_V128:
  154. bh_memcpy_s(global_data, sizeof(V128), &initial_value->v128,
  155. sizeof(V128));
  156. break;
  157. #endif
  158. default:
  159. #if WASM_ENABLE_GC != 0
  160. if ((type >= (uint8)REF_TYPE_ARRAYREF
  161. && type <= (uint8)REF_TYPE_NULLFUNCREF)
  162. || (type >= (uint8)REF_TYPE_HT_NULLABLE
  163. && type <= (uint8)REF_TYPE_HT_NON_NULLABLE)
  164. #if WASM_ENABLE_STRINGREF != 0
  165. || (type >= (uint8)REF_TYPE_STRINGVIEWWTF8
  166. && type <= (uint8)REF_TYPE_STRINGREF)
  167. || (type >= (uint8)REF_TYPE_STRINGVIEWITER
  168. && type <= (uint8)REF_TYPE_STRINGVIEWWTF16)
  169. #endif
  170. ) {
  171. bh_memcpy_s(global_data, sizeof(wasm_obj_t),
  172. &initial_value->gc_obj, sizeof(wasm_obj_t));
  173. break;
  174. }
  175. #endif /* end of WASM_ENABLE_GC */
  176. bh_assert(0);
  177. }
  178. }
  179. #if WASM_ENABLE_GC != 0
  180. static bool
  181. assign_table_init_value(AOTModuleInstance *module_inst, AOTModule *module,
  182. InitializerExpression *init_expr, void *addr,
  183. char *error_buf, uint32 error_buf_size)
  184. {
  185. uint8 flag = init_expr->init_expr_type;
  186. bh_assert(flag >= INIT_EXPR_TYPE_GET_GLOBAL
  187. && flag <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY);
  188. switch (flag) {
  189. case INIT_EXPR_TYPE_GET_GLOBAL:
  190. {
  191. if (!check_global_init_expr(module, init_expr->u.global_index,
  192. error_buf, error_buf_size)) {
  193. return false;
  194. }
  195. if (init_expr->u.global_index < module->import_global_count) {
  196. PUT_REF_TO_ADDR(
  197. addr, module->import_globals[init_expr->u.global_index]
  198. .global_data_linked.gc_obj);
  199. }
  200. else {
  201. uint32 global_idx =
  202. init_expr->u.global_index - module->import_global_count;
  203. return assign_table_init_value(
  204. module_inst, module, &module->globals[global_idx].init_expr,
  205. addr, error_buf, error_buf_size);
  206. }
  207. break;
  208. }
  209. case INIT_EXPR_TYPE_REFNULL_CONST:
  210. {
  211. WASMObjectRef gc_obj = NULL_REF;
  212. PUT_REF_TO_ADDR(addr, gc_obj);
  213. break;
  214. }
  215. case INIT_EXPR_TYPE_FUNCREF_CONST:
  216. {
  217. WASMFuncObjectRef func_obj = NULL;
  218. uint32 func_idx = init_expr->u.u32;
  219. if (func_idx != UINT32_MAX) {
  220. if (!(func_obj =
  221. aot_create_func_obj(module_inst, func_idx, false,
  222. error_buf, error_buf_size))) {
  223. return false;
  224. }
  225. }
  226. PUT_REF_TO_ADDR(addr, func_obj);
  227. break;
  228. }
  229. case INIT_EXPR_TYPE_I31_NEW:
  230. {
  231. WASMI31ObjectRef i31_obj = wasm_i31_obj_new(init_expr->u.i32);
  232. PUT_REF_TO_ADDR(addr, i31_obj);
  233. break;
  234. }
  235. case INIT_EXPR_TYPE_STRUCT_NEW:
  236. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  237. {
  238. WASMRttType *rtt_type;
  239. WASMStructObjectRef struct_obj;
  240. WASMStructType *struct_type;
  241. WASMStructNewInitValues *init_values = NULL;
  242. uint32 type_idx;
  243. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  244. init_values = (WASMStructNewInitValues *)init_expr->u.data;
  245. type_idx = init_values->type_idx;
  246. }
  247. else {
  248. type_idx = init_expr->u.type_index;
  249. }
  250. struct_type = (WASMStructType *)module->types[type_idx];
  251. if (!(rtt_type = wasm_rtt_type_new(
  252. (WASMType *)struct_type, type_idx, module->rtt_types,
  253. module->type_count, &module->rtt_type_lock))) {
  254. set_error_buf(error_buf, error_buf_size,
  255. "create rtt object failed");
  256. return false;
  257. }
  258. if (!(struct_obj = wasm_struct_obj_new_internal(
  259. ((AOTModuleInstanceExtra *)module_inst->e)
  260. ->common.gc_heap_handle,
  261. rtt_type))) {
  262. set_error_buf(error_buf, error_buf_size,
  263. "create struct object failed");
  264. return false;
  265. }
  266. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  267. uint32 field_idx;
  268. bh_assert(init_values->count == struct_type->field_count);
  269. for (field_idx = 0; field_idx < init_values->count;
  270. field_idx++) {
  271. wasm_struct_obj_set_field(struct_obj, field_idx,
  272. &init_values->fields[field_idx]);
  273. }
  274. }
  275. PUT_REF_TO_ADDR(addr, struct_obj);
  276. break;
  277. }
  278. case INIT_EXPR_TYPE_ARRAY_NEW:
  279. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  280. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  281. {
  282. WASMRttType *rtt_type;
  283. WASMArrayObjectRef array_obj;
  284. WASMArrayType *array_type;
  285. WASMArrayNewInitValues *init_values = NULL;
  286. WASMValue *arr_init_val = NULL, empty_val = { 0 };
  287. uint32 type_idx, len;
  288. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  289. type_idx = init_expr->u.array_new_default.type_index;
  290. len = init_expr->u.array_new_default.length;
  291. arr_init_val = &empty_val;
  292. }
  293. else {
  294. init_values = (WASMArrayNewInitValues *)init_expr->u.data;
  295. type_idx = init_values->type_idx;
  296. len = init_values->length;
  297. if (flag == INIT_EXPR_TYPE_ARRAY_NEW) {
  298. arr_init_val = init_values->elem_data;
  299. }
  300. }
  301. array_type = (WASMArrayType *)module->types[type_idx];
  302. if (!(rtt_type = wasm_rtt_type_new(
  303. (WASMType *)array_type, type_idx, module->rtt_types,
  304. module->type_count, &module->rtt_type_lock))) {
  305. set_error_buf(error_buf, error_buf_size,
  306. "create rtt object failed");
  307. return false;
  308. }
  309. if (!(array_obj = wasm_array_obj_new_internal(
  310. ((AOTModuleInstanceExtra *)module_inst->e)
  311. ->common.gc_heap_handle,
  312. rtt_type, len, arr_init_val))) {
  313. set_error_buf(error_buf, error_buf_size,
  314. "create array object failed");
  315. return false;
  316. }
  317. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  318. uint32 elem_idx;
  319. bh_assert(init_values);
  320. for (elem_idx = 0; elem_idx < len; elem_idx++) {
  321. wasm_array_obj_set_elem(array_obj, elem_idx,
  322. &init_values->elem_data[elem_idx]);
  323. }
  324. }
  325. PUT_REF_TO_ADDR(addr, array_obj);
  326. break;
  327. }
  328. default:
  329. set_error_buf(error_buf, error_buf_size, "invalid init expr type.");
  330. return false;
  331. }
  332. return true;
  333. }
  334. #endif /* end of WASM_ENABLE_GC != 0 */
  335. static bool
  336. global_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  337. char *error_buf, uint32 error_buf_size)
  338. {
  339. uint32 i;
  340. InitializerExpression *init_expr;
  341. uint8 *p = module_inst->global_data;
  342. AOTImportGlobal *import_global = module->import_globals;
  343. AOTGlobal *global = module->globals;
  344. /* Initialize import global data */
  345. for (i = 0; i < module->import_global_count; i++, import_global++) {
  346. bh_assert(import_global->data_offset
  347. == (uint32)(p - module_inst->global_data));
  348. init_global_data(p, import_global->type,
  349. &import_global->global_data_linked);
  350. p += import_global->size;
  351. }
  352. /* Initialize defined global data */
  353. for (i = 0; i < module->global_count; i++, global++) {
  354. uint8 flag;
  355. bh_assert(global->data_offset
  356. == (uint32)(p - module_inst->global_data));
  357. init_expr = &global->init_expr;
  358. flag = init_expr->init_expr_type;
  359. switch (flag) {
  360. case INIT_EXPR_TYPE_GET_GLOBAL:
  361. {
  362. if (!check_global_init_expr(module, init_expr->u.global_index,
  363. error_buf, error_buf_size)) {
  364. return false;
  365. }
  366. #if WASM_ENABLE_GC == 0
  367. init_global_data(
  368. p, global->type,
  369. &module->import_globals[init_expr->u.global_index]
  370. .global_data_linked);
  371. #else
  372. if (init_expr->u.global_index < module->import_global_count) {
  373. init_global_data(
  374. p, global->type,
  375. &module->import_globals[init_expr->u.global_index]
  376. .global_data_linked);
  377. }
  378. else {
  379. uint32 global_idx =
  380. init_expr->u.global_index - module->import_global_count;
  381. init_global_data(p, global->type,
  382. &module->globals[global_idx].init_expr.u);
  383. }
  384. #endif
  385. break;
  386. }
  387. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  388. case INIT_EXPR_TYPE_REFNULL_CONST:
  389. {
  390. *(uint32 *)p = NULL_REF;
  391. break;
  392. }
  393. #elif WASM_ENABLE_GC != 0
  394. case INIT_EXPR_TYPE_REFNULL_CONST:
  395. {
  396. WASMObjectRef gc_obj = NULL_REF;
  397. PUT_REF_TO_ADDR(p, gc_obj);
  398. break;
  399. }
  400. #endif
  401. #if WASM_ENABLE_GC != 0
  402. case INIT_EXPR_TYPE_FUNCREF_CONST:
  403. {
  404. WASMFuncObjectRef func_obj = NULL;
  405. uint32 func_idx = init_expr->u.u32;
  406. if (func_idx != UINT32_MAX) {
  407. if (!(func_obj =
  408. aot_create_func_obj(module_inst, func_idx, false,
  409. error_buf, error_buf_size))) {
  410. return false;
  411. }
  412. }
  413. PUT_REF_TO_ADDR(p, func_obj);
  414. break;
  415. }
  416. case INIT_EXPR_TYPE_I31_NEW:
  417. {
  418. WASMI31ObjectRef i31_obj = wasm_i31_obj_new(init_expr->u.i32);
  419. PUT_REF_TO_ADDR(p, i31_obj);
  420. break;
  421. }
  422. case INIT_EXPR_TYPE_STRUCT_NEW:
  423. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  424. {
  425. WASMRttType *rtt_type;
  426. WASMStructObjectRef struct_obj;
  427. WASMStructType *struct_type;
  428. WASMStructNewInitValues *init_values = NULL;
  429. uint32 type_idx;
  430. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  431. init_values = (WASMStructNewInitValues *)init_expr->u.data;
  432. type_idx = init_values->type_idx;
  433. }
  434. else {
  435. type_idx = init_expr->u.type_index;
  436. }
  437. struct_type = (WASMStructType *)module->types[type_idx];
  438. if (!(rtt_type = wasm_rtt_type_new(
  439. (WASMType *)struct_type, type_idx, module->rtt_types,
  440. module->type_count, &module->rtt_type_lock))) {
  441. set_error_buf(error_buf, error_buf_size,
  442. "create rtt object failed");
  443. return false;
  444. }
  445. if (!(struct_obj = wasm_struct_obj_new_internal(
  446. ((AOTModuleInstanceExtra *)module_inst->e)
  447. ->common.gc_heap_handle,
  448. rtt_type))) {
  449. set_error_buf(error_buf, error_buf_size,
  450. "create struct object failed");
  451. return false;
  452. }
  453. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  454. uint32 field_idx;
  455. bh_assert(init_values->count == struct_type->field_count);
  456. for (field_idx = 0; field_idx < init_values->count;
  457. field_idx++) {
  458. wasm_struct_obj_set_field(
  459. struct_obj, field_idx,
  460. &init_values->fields[field_idx]);
  461. }
  462. }
  463. PUT_REF_TO_ADDR(p, struct_obj);
  464. break;
  465. }
  466. case INIT_EXPR_TYPE_ARRAY_NEW:
  467. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  468. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  469. {
  470. WASMRttType *rtt_type;
  471. WASMArrayObjectRef array_obj;
  472. WASMArrayType *array_type;
  473. WASMArrayNewInitValues *init_values = NULL;
  474. WASMValue *arr_init_val = NULL, empty_val = { 0 };
  475. uint32 type_idx, len;
  476. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  477. type_idx = init_expr->u.array_new_default.type_index;
  478. len = init_expr->u.array_new_default.length;
  479. arr_init_val = &empty_val;
  480. }
  481. else {
  482. init_values = (WASMArrayNewInitValues *)init_expr->u.data;
  483. type_idx = init_values->type_idx;
  484. len = init_values->length;
  485. if (flag == INIT_EXPR_TYPE_ARRAY_NEW) {
  486. arr_init_val = init_values->elem_data;
  487. }
  488. }
  489. array_type = (WASMArrayType *)module->types[type_idx];
  490. if (!(rtt_type = wasm_rtt_type_new(
  491. (WASMType *)array_type, type_idx, module->rtt_types,
  492. module->type_count, &module->rtt_type_lock))) {
  493. set_error_buf(error_buf, error_buf_size,
  494. "create rtt object failed");
  495. return false;
  496. }
  497. if (!(array_obj = wasm_array_obj_new_internal(
  498. ((AOTModuleInstanceExtra *)module_inst->e)
  499. ->common.gc_heap_handle,
  500. rtt_type, len, arr_init_val))) {
  501. set_error_buf(error_buf, error_buf_size,
  502. "create array object failed");
  503. return false;
  504. }
  505. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  506. uint32 elem_idx;
  507. bh_assert(init_values);
  508. for (elem_idx = 0; elem_idx < len; elem_idx++) {
  509. wasm_array_obj_set_elem(
  510. array_obj, elem_idx,
  511. &init_values->elem_data[elem_idx]);
  512. }
  513. }
  514. PUT_REF_TO_ADDR(p, array_obj);
  515. break;
  516. }
  517. #endif /* end of WASM_ENABLE_GC != 0 */
  518. default:
  519. {
  520. init_global_data(p, global->type, &init_expr->u);
  521. break;
  522. }
  523. }
  524. p += global->size;
  525. }
  526. bh_assert(module_inst->global_data_size
  527. == (uint32)(p - module_inst->global_data));
  528. return true;
  529. }
  530. static bool
  531. tables_instantiate(AOTModuleInstance *module_inst, AOTModule *module,
  532. AOTTableInstance *first_tbl_inst, char *error_buf,
  533. uint32 error_buf_size)
  534. {
  535. uint32 i, global_index, global_data_offset, base_offset, length;
  536. uint64 total_size;
  537. AOTTableInitData *table_seg;
  538. AOTTableInstance *tbl_inst = first_tbl_inst;
  539. total_size = (uint64)sizeof(AOTTableInstance *) * module_inst->table_count;
  540. if (total_size > 0
  541. && !(module_inst->tables =
  542. runtime_malloc(total_size, error_buf, error_buf_size))) {
  543. return false;
  544. }
  545. /*
  546. * treat import table like a local one until we enable module linking
  547. * in AOT mode
  548. */
  549. for (i = 0; i != module_inst->table_count; ++i) {
  550. if (i < module->import_table_count) {
  551. AOTImportTable *import_table = module->import_tables + i;
  552. tbl_inst->cur_size = import_table->table_init_size;
  553. tbl_inst->max_size =
  554. aot_get_imp_tbl_data_slots(import_table, false);
  555. #if WASM_ENABLE_GC != 0
  556. tbl_inst->elem_type = module->tables[i].elem_type;
  557. tbl_inst->elem_ref_type.elem_ref_type =
  558. module->tables[i].elem_ref_type;
  559. #endif
  560. }
  561. else {
  562. AOTTable *table = module->tables + (i - module->import_table_count);
  563. tbl_inst->cur_size = table->table_init_size;
  564. tbl_inst->max_size = aot_get_tbl_data_slots(table, false);
  565. #if WASM_ENABLE_GC != 0
  566. tbl_inst->elem_type = module->tables[i].elem_type;
  567. tbl_inst->elem_ref_type.elem_ref_type =
  568. module->tables[i].elem_ref_type;
  569. #endif
  570. }
  571. /* Set all elements to -1 or NULL_REF to mark them as uninitialized
  572. * elements */
  573. #if WASM_ENABLE_GC == 0
  574. memset(tbl_inst->elems, 0xff,
  575. sizeof(table_elem_type_t) * tbl_inst->max_size);
  576. #else
  577. memset(tbl_inst->elems, 0x00,
  578. sizeof(table_elem_type_t) * tbl_inst->max_size);
  579. #endif
  580. module_inst->tables[i] = tbl_inst;
  581. tbl_inst = (AOTTableInstance *)((uint8 *)tbl_inst
  582. + offsetof(AOTTableInstance, elems)
  583. + sizeof(table_elem_type_t)
  584. * tbl_inst->max_size);
  585. }
  586. /* fill table with element segment content */
  587. for (i = 0; i < module->table_init_data_count; i++) {
  588. #if WASM_ENABLE_GC == 0
  589. uint32 j;
  590. #endif
  591. table_seg = module->table_init_data_list[i];
  592. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  593. if (!wasm_elem_is_active(table_seg->mode))
  594. continue;
  595. #endif
  596. bh_assert(table_seg->table_index < module_inst->table_count);
  597. tbl_inst = module_inst->tables[table_seg->table_index];
  598. bh_assert(tbl_inst);
  599. #if WASM_ENABLE_REF_TYPES != 0
  600. bh_assert(
  601. table_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  602. || table_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL
  603. || table_seg->offset.init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST
  604. || table_seg->offset.init_expr_type
  605. == INIT_EXPR_TYPE_REFNULL_CONST);
  606. #else
  607. bh_assert(table_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  608. || table_seg->offset.init_expr_type
  609. == INIT_EXPR_TYPE_GET_GLOBAL);
  610. #endif
  611. /* Resolve table data base offset */
  612. if (table_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  613. global_index = table_seg->offset.u.global_index;
  614. if (!check_global_init_expr(module, global_index, error_buf,
  615. error_buf_size)) {
  616. return false;
  617. }
  618. if (global_index < module->import_global_count)
  619. global_data_offset =
  620. module->import_globals[global_index].data_offset;
  621. else
  622. global_data_offset =
  623. module->globals[global_index - module->import_global_count]
  624. .data_offset;
  625. base_offset =
  626. *(uint32 *)(module_inst->global_data + global_data_offset);
  627. }
  628. else
  629. base_offset = (uint32)table_seg->offset.u.i32;
  630. /* Copy table data */
  631. /* base_offset only since length might negative */
  632. if (base_offset > tbl_inst->cur_size) {
  633. #if WASM_ENABLE_REF_TYPES != 0
  634. set_error_buf(error_buf, error_buf_size,
  635. "out of bounds table access");
  636. #else
  637. set_error_buf(error_buf, error_buf_size,
  638. "type mismatch: elements segment does not fit");
  639. #endif
  640. return false;
  641. }
  642. /* base_offset + length(could be zero) */
  643. length = table_seg->value_count;
  644. if (base_offset + length > tbl_inst->cur_size) {
  645. #if WASM_ENABLE_REF_TYPES != 0
  646. set_error_buf(error_buf, error_buf_size,
  647. "out of bounds table access");
  648. #else
  649. set_error_buf(error_buf, error_buf_size,
  650. "type mismatch: elements segment does not fit");
  651. #endif
  652. return false;
  653. }
  654. /**
  655. * Check function index in the current module inst for now.
  656. * will check the linked table inst owner in future
  657. */
  658. #if WASM_ENABLE_GC == 0
  659. for (j = 0; j < length; j++) {
  660. tbl_inst->elems[base_offset + j] =
  661. table_seg->init_values[j].u.ref_index;
  662. }
  663. #endif
  664. }
  665. return true;
  666. }
  667. static void
  668. memories_deinstantiate(AOTModuleInstance *module_inst)
  669. {
  670. uint32 i;
  671. AOTMemoryInstance *memory_inst;
  672. for (i = 0; i < module_inst->memory_count; i++) {
  673. memory_inst = module_inst->memories[i];
  674. if (memory_inst) {
  675. #if WASM_ENABLE_SHARED_MEMORY != 0
  676. if (shared_memory_is_shared(memory_inst)) {
  677. uint32 ref_count = shared_memory_dec_reference(memory_inst);
  678. /* if the reference count is not zero,
  679. don't free the memory */
  680. if (ref_count > 0)
  681. continue;
  682. }
  683. #endif
  684. if (memory_inst->heap_handle) {
  685. mem_allocator_destroy(memory_inst->heap_handle);
  686. wasm_runtime_free(memory_inst->heap_handle);
  687. }
  688. if (memory_inst->memory_data) {
  689. wasm_deallocate_linear_memory(memory_inst);
  690. }
  691. }
  692. }
  693. wasm_runtime_free(module_inst->memories);
  694. }
  695. static AOTMemoryInstance *
  696. memory_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent,
  697. AOTModule *module, AOTMemoryInstance *memory_inst,
  698. AOTMemory *memory, uint32 memory_idx, uint32 heap_size,
  699. char *error_buf, uint32 error_buf_size)
  700. {
  701. void *heap_handle;
  702. uint32 num_bytes_per_page = memory->num_bytes_per_page;
  703. uint32 init_page_count = memory->mem_init_page_count;
  704. uint32 max_page_count = memory->mem_max_page_count;
  705. uint32 inc_page_count, aux_heap_base, global_idx;
  706. uint32 bytes_of_last_page, bytes_to_page_end;
  707. uint32 heap_offset = num_bytes_per_page * init_page_count;
  708. uint64 memory_data_size, max_memory_data_size;
  709. uint8 *p = NULL, *global_addr;
  710. bool is_shared_memory = false;
  711. #if WASM_ENABLE_SHARED_MEMORY != 0
  712. is_shared_memory = memory->memory_flags & 0x02 ? true : false;
  713. /* Shared memory */
  714. if (is_shared_memory && parent != NULL) {
  715. AOTMemoryInstance *shared_memory_instance;
  716. bh_assert(memory_idx == 0);
  717. bh_assert(parent->memory_count > memory_idx);
  718. shared_memory_instance = parent->memories[memory_idx];
  719. shared_memory_inc_reference(shared_memory_instance);
  720. return shared_memory_instance;
  721. }
  722. #endif
  723. if (heap_size > 0 && module->malloc_func_index != (uint32)-1
  724. && module->free_func_index != (uint32)-1) {
  725. /* Disable app heap, use malloc/free function exported
  726. by wasm app to allocate/free memory instead */
  727. heap_size = 0;
  728. }
  729. if (init_page_count == max_page_count && init_page_count == 1) {
  730. /* If only one page and at most one page, we just append
  731. the app heap to the end of linear memory, enlarge the
  732. num_bytes_per_page, and don't change the page count */
  733. heap_offset = num_bytes_per_page;
  734. num_bytes_per_page += heap_size;
  735. if (num_bytes_per_page < heap_size) {
  736. set_error_buf(error_buf, error_buf_size,
  737. "failed to insert app heap into linear memory, "
  738. "try using `--heap-size=0` option");
  739. return NULL;
  740. }
  741. }
  742. else if (heap_size > 0) {
  743. if (init_page_count == max_page_count && init_page_count == 0) {
  744. /* If the memory data size is always 0, we resize it to
  745. one page for app heap */
  746. num_bytes_per_page = heap_size;
  747. heap_offset = 0;
  748. inc_page_count = 1;
  749. }
  750. else if (module->aux_heap_base_global_index != (uint32)-1
  751. && module->aux_heap_base
  752. < num_bytes_per_page * init_page_count) {
  753. /* Insert app heap before __heap_base */
  754. aux_heap_base = module->aux_heap_base;
  755. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  756. if (bytes_of_last_page == 0)
  757. bytes_of_last_page = num_bytes_per_page;
  758. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  759. inc_page_count =
  760. (heap_size - bytes_to_page_end + num_bytes_per_page - 1)
  761. / num_bytes_per_page;
  762. heap_offset = aux_heap_base;
  763. aux_heap_base += heap_size;
  764. bytes_of_last_page = aux_heap_base % num_bytes_per_page;
  765. if (bytes_of_last_page == 0)
  766. bytes_of_last_page = num_bytes_per_page;
  767. bytes_to_page_end = num_bytes_per_page - bytes_of_last_page;
  768. if (bytes_to_page_end < 1 * BH_KB) {
  769. aux_heap_base += 1 * BH_KB;
  770. inc_page_count++;
  771. }
  772. /* Adjust __heap_base global value */
  773. global_idx = module->aux_heap_base_global_index
  774. - module->import_global_count;
  775. global_addr = module_inst->global_data
  776. + module->globals[global_idx].data_offset;
  777. *(uint32 *)global_addr = aux_heap_base;
  778. LOG_VERBOSE("Reset __heap_base global to %u", aux_heap_base);
  779. }
  780. else {
  781. /* Insert app heap before new page */
  782. inc_page_count =
  783. (heap_size + num_bytes_per_page - 1) / num_bytes_per_page;
  784. heap_offset = num_bytes_per_page * init_page_count;
  785. heap_size = num_bytes_per_page * inc_page_count;
  786. if (heap_size > 0)
  787. heap_size -= 1 * BH_KB;
  788. }
  789. init_page_count += inc_page_count;
  790. max_page_count += inc_page_count;
  791. if (init_page_count > DEFAULT_MAX_PAGES) {
  792. set_error_buf(error_buf, error_buf_size,
  793. "failed to insert app heap into linear memory, "
  794. "try using `--heap-size=0` option");
  795. return NULL;
  796. }
  797. else if (init_page_count == DEFAULT_MAX_PAGES) {
  798. num_bytes_per_page = UINT32_MAX;
  799. init_page_count = max_page_count = 1;
  800. }
  801. if (max_page_count > DEFAULT_MAX_PAGES)
  802. max_page_count = DEFAULT_MAX_PAGES;
  803. }
  804. else { /* heap_size == 0 */
  805. if (init_page_count == DEFAULT_MAX_PAGES) {
  806. num_bytes_per_page = UINT32_MAX;
  807. init_page_count = max_page_count = 1;
  808. }
  809. }
  810. LOG_VERBOSE("Memory instantiate:");
  811. LOG_VERBOSE(" page bytes: %u, init pages: %u, max pages: %u",
  812. num_bytes_per_page, init_page_count, max_page_count);
  813. LOG_VERBOSE(" data offset: %u, stack size: %d", module->aux_data_end,
  814. module->aux_stack_size);
  815. LOG_VERBOSE(" heap offset: %u, heap size: %d\n", heap_offset, heap_size);
  816. max_memory_data_size = (uint64)num_bytes_per_page * max_page_count;
  817. bh_assert(max_memory_data_size <= 4 * (uint64)BH_GB);
  818. (void)max_memory_data_size;
  819. if (wasm_allocate_linear_memory(&p, is_shared_memory, num_bytes_per_page,
  820. init_page_count, max_page_count,
  821. &memory_data_size)
  822. != BHT_OK) {
  823. set_error_buf(error_buf, error_buf_size,
  824. "allocate linear memory failed");
  825. return NULL;
  826. }
  827. memory_inst->module_type = Wasm_Module_AoT;
  828. memory_inst->num_bytes_per_page = num_bytes_per_page;
  829. memory_inst->cur_page_count = init_page_count;
  830. memory_inst->max_page_count = max_page_count;
  831. memory_inst->memory_data_size = (uint32)memory_data_size;
  832. /* Init memory info */
  833. memory_inst->memory_data = p;
  834. memory_inst->memory_data_end = p + (uint32)memory_data_size;
  835. /* Initialize heap info */
  836. memory_inst->heap_data = p + heap_offset;
  837. memory_inst->heap_data_end = p + heap_offset + heap_size;
  838. if (heap_size > 0) {
  839. uint32 heap_struct_size = mem_allocator_get_heap_struct_size();
  840. if (!(heap_handle = runtime_malloc((uint64)heap_struct_size, error_buf,
  841. error_buf_size))) {
  842. goto fail1;
  843. }
  844. memory_inst->heap_handle = heap_handle;
  845. if (!mem_allocator_create_with_struct_and_pool(
  846. heap_handle, heap_struct_size, memory_inst->heap_data,
  847. heap_size)) {
  848. set_error_buf(error_buf, error_buf_size, "init app heap failed");
  849. goto fail2;
  850. }
  851. }
  852. if (memory_data_size > 0) {
  853. wasm_runtime_set_mem_bound_check_bytes(memory_inst, memory_data_size);
  854. }
  855. #if WASM_ENABLE_SHARED_MEMORY != 0
  856. if (is_shared_memory) {
  857. memory_inst->is_shared_memory = 1;
  858. memory_inst->ref_count = 1;
  859. }
  860. #endif
  861. return memory_inst;
  862. fail2:
  863. if (heap_size > 0)
  864. wasm_runtime_free(memory_inst->heap_handle);
  865. fail1:
  866. wasm_deallocate_linear_memory(memory_inst);
  867. return NULL;
  868. }
  869. static AOTMemoryInstance *
  870. aot_get_default_memory(AOTModuleInstance *module_inst)
  871. {
  872. if (module_inst->memories)
  873. return module_inst->memories[0];
  874. else
  875. return NULL;
  876. }
  877. static bool
  878. memories_instantiate(AOTModuleInstance *module_inst, AOTModuleInstance *parent,
  879. AOTModule *module, uint32 heap_size, char *error_buf,
  880. uint32 error_buf_size)
  881. {
  882. uint32 global_index, global_data_offset, base_offset, length;
  883. uint32 i, memory_count = module->memory_count;
  884. AOTMemoryInstance *memories, *memory_inst;
  885. AOTMemInitData *data_seg;
  886. uint64 total_size;
  887. module_inst->memory_count = memory_count;
  888. total_size = sizeof(AOTMemoryInstance *) * (uint64)memory_count;
  889. if (!(module_inst->memories =
  890. runtime_malloc(total_size, error_buf, error_buf_size))) {
  891. return false;
  892. }
  893. memories = module_inst->global_table_data.memory_instances;
  894. for (i = 0; i < memory_count; i++, memories++) {
  895. memory_inst = memory_instantiate(module_inst, parent, module, memories,
  896. &module->memories[i], i, heap_size,
  897. error_buf, error_buf_size);
  898. if (!memory_inst) {
  899. return false;
  900. }
  901. module_inst->memories[i] = memory_inst;
  902. }
  903. /* Get default memory instance */
  904. memory_inst = aot_get_default_memory(module_inst);
  905. if (!memory_inst) {
  906. /* Ignore setting memory init data if no memory inst is created */
  907. return true;
  908. }
  909. for (i = 0; i < module->mem_init_data_count; i++) {
  910. data_seg = module->mem_init_data_list[i];
  911. #if WASM_ENABLE_BULK_MEMORY != 0
  912. if (data_seg->is_passive)
  913. continue;
  914. #endif
  915. if (parent != NULL)
  916. /* Ignore setting memory init data if the memory has been
  917. initialized */
  918. continue;
  919. bh_assert(data_seg->offset.init_expr_type == INIT_EXPR_TYPE_I32_CONST
  920. || data_seg->offset.init_expr_type
  921. == INIT_EXPR_TYPE_GET_GLOBAL);
  922. /* Resolve memory data base offset */
  923. if (data_seg->offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  924. global_index = data_seg->offset.u.global_index;
  925. if (!check_global_init_expr(module, global_index, error_buf,
  926. error_buf_size)) {
  927. return false;
  928. }
  929. if (global_index < module->import_global_count)
  930. global_data_offset =
  931. module->import_globals[global_index].data_offset;
  932. else
  933. global_data_offset =
  934. module->globals[global_index - module->import_global_count]
  935. .data_offset;
  936. base_offset =
  937. *(uint32 *)(module_inst->global_data + global_data_offset);
  938. }
  939. else {
  940. base_offset = (uint32)data_seg->offset.u.i32;
  941. }
  942. /* Copy memory data */
  943. bh_assert(memory_inst->memory_data
  944. || memory_inst->memory_data_size == 0);
  945. /* Check memory data */
  946. /* check offset since length might negative */
  947. if (base_offset > memory_inst->memory_data_size) {
  948. LOG_DEBUG("base_offset(%d) > memory_data_size(%d)", base_offset,
  949. memory_inst->memory_data_size);
  950. #if WASM_ENABLE_REF_TYPES != 0
  951. set_error_buf(error_buf, error_buf_size,
  952. "out of bounds memory access");
  953. #else
  954. set_error_buf(error_buf, error_buf_size,
  955. "data segment does not fit");
  956. #endif
  957. return false;
  958. }
  959. /* check offset + length(could be zero) */
  960. length = data_seg->byte_count;
  961. if (base_offset + length > memory_inst->memory_data_size) {
  962. LOG_DEBUG("base_offset(%d) + length(%d) > memory_data_size(%d)",
  963. base_offset, length, memory_inst->memory_data_size);
  964. #if WASM_ENABLE_REF_TYPES != 0
  965. set_error_buf(error_buf, error_buf_size,
  966. "out of bounds memory access");
  967. #else
  968. set_error_buf(error_buf, error_buf_size,
  969. "data segment does not fit");
  970. #endif
  971. return false;
  972. }
  973. if (memory_inst->memory_data) {
  974. bh_memcpy_s((uint8 *)memory_inst->memory_data + base_offset,
  975. memory_inst->memory_data_size - base_offset,
  976. data_seg->bytes, length);
  977. }
  978. }
  979. return true;
  980. }
  981. static bool
  982. init_func_ptrs(AOTModuleInstance *module_inst, AOTModule *module,
  983. char *error_buf, uint32 error_buf_size)
  984. {
  985. uint32 i;
  986. void **func_ptrs;
  987. uint64 total_size = ((uint64)module->import_func_count + module->func_count)
  988. * sizeof(void *);
  989. if (module->import_func_count + module->func_count == 0)
  990. return true;
  991. /* Allocate memory */
  992. if (!(module_inst->func_ptrs =
  993. runtime_malloc(total_size, error_buf, error_buf_size))) {
  994. return false;
  995. }
  996. /* Set import function pointers */
  997. func_ptrs = (void **)module_inst->func_ptrs;
  998. for (i = 0; i < module->import_func_count; i++, func_ptrs++) {
  999. *func_ptrs = (void *)module->import_funcs[i].func_ptr_linked;
  1000. if (!*func_ptrs) {
  1001. const char *module_name = module->import_funcs[i].module_name;
  1002. const char *field_name = module->import_funcs[i].func_name;
  1003. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1004. module_name, field_name);
  1005. }
  1006. }
  1007. /* Set defined function pointers */
  1008. bh_memcpy_s(func_ptrs, sizeof(void *) * module->func_count,
  1009. module->func_ptrs, sizeof(void *) * module->func_count);
  1010. return true;
  1011. }
  1012. static bool
  1013. init_func_type_indexes(AOTModuleInstance *module_inst, AOTModule *module,
  1014. char *error_buf, uint32 error_buf_size)
  1015. {
  1016. uint32 i;
  1017. uint32 *func_type_index;
  1018. uint64 total_size = ((uint64)module->import_func_count + module->func_count)
  1019. * sizeof(uint32);
  1020. if (module->import_func_count + module->func_count == 0)
  1021. return true;
  1022. /* Allocate memory */
  1023. if (!(module_inst->func_type_indexes =
  1024. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1025. return false;
  1026. }
  1027. /* Set import function type indexes */
  1028. func_type_index = module_inst->func_type_indexes;
  1029. for (i = 0; i < module->import_func_count; i++, func_type_index++)
  1030. *func_type_index = module->import_funcs[i].func_type_index;
  1031. bh_memcpy_s(func_type_index, sizeof(uint32) * module->func_count,
  1032. module->func_type_indexes, sizeof(uint32) * module->func_count);
  1033. return true;
  1034. }
  1035. static bool
  1036. create_export_funcs(AOTModuleInstance *module_inst, AOTModule *module,
  1037. char *error_buf, uint32 error_buf_size)
  1038. {
  1039. AOTExport *exports = module->exports;
  1040. AOTFunctionInstance *export_func;
  1041. uint64 size;
  1042. uint32 i, func_index, ftype_index;
  1043. if (module_inst->export_func_count > 0) {
  1044. /* Allocate memory */
  1045. size = sizeof(AOTFunctionInstance)
  1046. * (uint64)module_inst->export_func_count;
  1047. if (!(export_func = runtime_malloc(size, error_buf, error_buf_size))) {
  1048. return false;
  1049. }
  1050. module_inst->export_functions = (void *)export_func;
  1051. for (i = 0; i < module->export_count; i++) {
  1052. if (exports[i].kind == EXPORT_KIND_FUNC) {
  1053. export_func->func_name = exports[i].name;
  1054. export_func->func_index = exports[i].index;
  1055. if (export_func->func_index < module->import_func_count) {
  1056. export_func->is_import_func = true;
  1057. export_func->u.func_import =
  1058. &module->import_funcs[export_func->func_index];
  1059. }
  1060. else {
  1061. export_func->is_import_func = false;
  1062. func_index =
  1063. export_func->func_index - module->import_func_count;
  1064. ftype_index = module->func_type_indexes[func_index];
  1065. export_func->u.func.func_type =
  1066. (AOTFuncType *)module->types[ftype_index];
  1067. export_func->u.func.func_ptr =
  1068. module->func_ptrs[func_index];
  1069. }
  1070. export_func++;
  1071. }
  1072. }
  1073. }
  1074. return true;
  1075. }
  1076. static bool
  1077. create_exports(AOTModuleInstance *module_inst, AOTModule *module,
  1078. char *error_buf, uint32 error_buf_size)
  1079. {
  1080. AOTExport *exports = module->exports;
  1081. uint32 i;
  1082. for (i = 0; i < module->export_count; i++) {
  1083. switch (exports[i].kind) {
  1084. case EXPORT_KIND_FUNC:
  1085. module_inst->export_func_count++;
  1086. break;
  1087. case EXPORT_KIND_GLOBAL:
  1088. module_inst->export_global_count++;
  1089. break;
  1090. case EXPORT_KIND_TABLE:
  1091. module_inst->export_table_count++;
  1092. break;
  1093. case EXPORT_KIND_MEMORY:
  1094. module_inst->export_memory_count++;
  1095. break;
  1096. default:
  1097. return false;
  1098. }
  1099. }
  1100. return create_export_funcs(module_inst, module, error_buf, error_buf_size);
  1101. }
  1102. static AOTFunctionInstance *
  1103. lookup_post_instantiate_func(AOTModuleInstance *module_inst,
  1104. const char *func_name)
  1105. {
  1106. AOTFunctionInstance *func;
  1107. AOTFuncType *func_type;
  1108. if (!(func = aot_lookup_function(module_inst, func_name, NULL)))
  1109. /* Not found */
  1110. return NULL;
  1111. func_type = func->u.func.func_type;
  1112. if (!(func_type->param_count == 0 && func_type->result_count == 0))
  1113. /* Not a valid function type, ignore it */
  1114. return NULL;
  1115. return func;
  1116. }
  1117. static bool
  1118. execute_post_instantiate_functions(AOTModuleInstance *module_inst,
  1119. bool is_sub_inst, WASMExecEnv *exec_env_main)
  1120. {
  1121. AOTModule *module = (AOTModule *)module_inst->module;
  1122. AOTFunctionInstance *initialize_func = NULL;
  1123. AOTFunctionInstance *post_inst_func = NULL;
  1124. AOTFunctionInstance *call_ctors_func = NULL;
  1125. WASMModuleInstanceCommon *module_inst_main = NULL;
  1126. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1127. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1128. #endif
  1129. WASMExecEnv *exec_env = NULL, *exec_env_created = NULL;
  1130. bool ret = false;
  1131. #if WASM_ENABLE_LIBC_WASI != 0
  1132. /*
  1133. * WASI reactor instances may assume that _initialize will be called by
  1134. * the environment at most once, and that none of their other exports
  1135. * are accessed before that call.
  1136. */
  1137. if (!is_sub_inst && module->import_wasi_api) {
  1138. initialize_func =
  1139. lookup_post_instantiate_func(module_inst, "_initialize");
  1140. }
  1141. #endif
  1142. /* Execute possible "__post_instantiate" function if wasm app is
  1143. compiled by emsdk's early version */
  1144. if (!is_sub_inst) {
  1145. post_inst_func =
  1146. lookup_post_instantiate_func(module_inst, "__post_instantiate");
  1147. }
  1148. #if WASM_ENABLE_BULK_MEMORY != 0
  1149. /* Only execute the memory init function for main instance since
  1150. the data segments will be dropped once initialized */
  1151. if (!is_sub_inst
  1152. #if WASM_ENABLE_LIBC_WASI != 0
  1153. && !module->import_wasi_api
  1154. #endif
  1155. ) {
  1156. call_ctors_func =
  1157. lookup_post_instantiate_func(module_inst, "__wasm_call_ctors");
  1158. }
  1159. #endif
  1160. if (!module->start_function && !initialize_func && !post_inst_func
  1161. && !call_ctors_func) {
  1162. /* No post instantiation functions to call */
  1163. return true;
  1164. }
  1165. if (is_sub_inst) {
  1166. bh_assert(exec_env_main);
  1167. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1168. bh_assert(exec_env_tls == exec_env_main);
  1169. (void)exec_env_tls;
  1170. #endif
  1171. exec_env = exec_env_main;
  1172. /* Temporarily replace parent exec_env's module inst to current
  1173. module inst to avoid checking failure when calling the
  1174. wasm functions, and ensure that the exec_env's module inst
  1175. is the correct one. */
  1176. module_inst_main = exec_env_main->module_inst;
  1177. wasm_exec_env_set_module_inst(exec_env,
  1178. (WASMModuleInstanceCommon *)module_inst);
  1179. }
  1180. else {
  1181. /* Try using the existing exec_env */
  1182. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1183. exec_env = exec_env_tls;
  1184. #endif
  1185. #if WASM_ENABLE_THREAD_MGR != 0
  1186. if (!exec_env)
  1187. exec_env = wasm_clusters_search_exec_env(
  1188. (WASMModuleInstanceCommon *)module_inst);
  1189. #endif
  1190. if (!exec_env) {
  1191. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1192. (WASMModuleInstanceCommon *)module_inst,
  1193. module_inst->default_wasm_stack_size))) {
  1194. aot_set_exception(module_inst, "allocate memory failed");
  1195. return false;
  1196. }
  1197. }
  1198. else {
  1199. /* Temporarily replace exec_env's module inst with current
  1200. module inst to ensure that the exec_env's module inst
  1201. is the correct one. */
  1202. module_inst_main = exec_env->module_inst;
  1203. wasm_exec_env_set_module_inst(
  1204. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1205. }
  1206. }
  1207. #if defined(os_writegsbase)
  1208. {
  1209. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1210. if (memory_inst)
  1211. /* write base addr of linear memory to GS segment register */
  1212. os_writegsbase(memory_inst->memory_data);
  1213. }
  1214. #endif
  1215. /* Execute start function for both main insance and sub instance */
  1216. if (module->start_function) {
  1217. AOTFunctionInstance start_func = { 0 };
  1218. uint32 func_type_idx;
  1219. start_func.func_name = "";
  1220. start_func.func_index = module->start_func_index;
  1221. start_func.is_import_func = false;
  1222. func_type_idx = module->func_type_indexes[module->start_func_index
  1223. - module->import_func_count];
  1224. start_func.u.func.func_type =
  1225. (AOTFuncType *)module->types[func_type_idx];
  1226. start_func.u.func.func_ptr = module->start_function;
  1227. if (!aot_call_function(exec_env, &start_func, 0, NULL)) {
  1228. goto fail;
  1229. }
  1230. }
  1231. if (initialize_func
  1232. && !aot_call_function(exec_env, initialize_func, 0, NULL)) {
  1233. goto fail;
  1234. }
  1235. if (post_inst_func
  1236. && !aot_call_function(exec_env, post_inst_func, 0, NULL)) {
  1237. goto fail;
  1238. }
  1239. if (call_ctors_func
  1240. && !aot_call_function(exec_env, call_ctors_func, 0, NULL)) {
  1241. goto fail;
  1242. }
  1243. ret = true;
  1244. fail:
  1245. if (is_sub_inst) {
  1246. /* Restore the parent exec_env's module inst */
  1247. wasm_exec_env_restore_module_inst(exec_env_main, module_inst_main);
  1248. }
  1249. else {
  1250. if (module_inst_main)
  1251. /* Restore the existing exec_env's module inst */
  1252. wasm_exec_env_restore_module_inst(exec_env, module_inst_main);
  1253. if (exec_env_created)
  1254. wasm_exec_env_destroy(exec_env_created);
  1255. }
  1256. return ret;
  1257. }
  1258. static bool
  1259. check_linked_symbol(AOTModule *module, char *error_buf, uint32 error_buf_size)
  1260. {
  1261. uint32 i;
  1262. /* init_func_ptrs() will go through import functions */
  1263. for (i = 0; i < module->import_global_count; i++) {
  1264. AOTImportGlobal *global = module->import_globals + i;
  1265. if (!global->is_linked) {
  1266. set_error_buf_v(error_buf, error_buf_size,
  1267. "failed to link import global (%s, %s)",
  1268. global->module_name, global->global_name);
  1269. return false;
  1270. }
  1271. }
  1272. return true;
  1273. }
  1274. AOTModuleInstance *
  1275. aot_instantiate(AOTModule *module, AOTModuleInstance *parent,
  1276. WASMExecEnv *exec_env_main, uint32 stack_size, uint32 heap_size,
  1277. char *error_buf, uint32 error_buf_size)
  1278. {
  1279. AOTModuleInstance *module_inst;
  1280. #if WASM_ENABLE_BULK_MEMORY != 0 || WASM_ENABLE_REF_TYPES != 0
  1281. WASMModuleInstanceExtraCommon *common;
  1282. #endif
  1283. const uint32 module_inst_struct_size =
  1284. offsetof(AOTModuleInstance, global_table_data.bytes);
  1285. const uint64 module_inst_mem_inst_size =
  1286. (uint64)module->memory_count * sizeof(AOTMemoryInstance);
  1287. uint64 total_size, table_size = 0;
  1288. uint8 *p;
  1289. uint32 i, extra_info_offset;
  1290. const bool is_sub_inst = parent != NULL;
  1291. #if WASM_ENABLE_MULTI_MODULE != 0
  1292. bool ret = false;
  1293. #endif
  1294. /* Check heap size */
  1295. heap_size = align_uint(heap_size, 8);
  1296. if (heap_size > APP_HEAP_SIZE_MAX)
  1297. heap_size = APP_HEAP_SIZE_MAX;
  1298. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  1299. + module->global_data_size;
  1300. /*
  1301. * calculate size of table data
  1302. */
  1303. for (i = 0; i != module->import_table_count; ++i) {
  1304. table_size += offsetof(AOTTableInstance, elems);
  1305. table_size += (uint64)sizeof(table_elem_type_t)
  1306. * (uint64)aot_get_imp_tbl_data_slots(
  1307. module->import_tables + i, false);
  1308. }
  1309. for (i = 0; i != module->table_count; ++i) {
  1310. table_size += offsetof(AOTTableInstance, elems);
  1311. table_size +=
  1312. (uint64)sizeof(table_elem_type_t)
  1313. * (uint64)aot_get_tbl_data_slots(module->tables + i, false);
  1314. }
  1315. total_size += table_size;
  1316. /* The offset of AOTModuleInstanceExtra, make it 8-byte aligned */
  1317. total_size = (total_size + 7LL) & ~7LL;
  1318. extra_info_offset = (uint32)total_size;
  1319. total_size += sizeof(AOTModuleInstanceExtra);
  1320. /* Allocate module instance, global data, table data and heap data */
  1321. if (!(module_inst =
  1322. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1323. return NULL;
  1324. }
  1325. module_inst->module_type = Wasm_Module_AoT;
  1326. module_inst->module = (void *)module;
  1327. module_inst->e =
  1328. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  1329. #if WASM_ENABLE_GC != 0
  1330. /* Initialize gc heap first since it may be used when initializing
  1331. globals and others */
  1332. if (!is_sub_inst) {
  1333. uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default();
  1334. AOTModuleInstanceExtra *extra =
  1335. (AOTModuleInstanceExtra *)module_inst->e;
  1336. if (gc_heap_size < GC_HEAP_SIZE_MIN)
  1337. gc_heap_size = GC_HEAP_SIZE_MIN;
  1338. if (gc_heap_size > GC_HEAP_SIZE_MAX)
  1339. gc_heap_size = GC_HEAP_SIZE_MAX;
  1340. extra->common.gc_heap_pool =
  1341. runtime_malloc(gc_heap_size, error_buf, error_buf_size);
  1342. if (!extra->common.gc_heap_pool)
  1343. goto fail;
  1344. extra->common.gc_heap_handle =
  1345. mem_allocator_create(extra->common.gc_heap_pool, gc_heap_size);
  1346. if (!extra->common.gc_heap_handle)
  1347. goto fail;
  1348. }
  1349. #endif
  1350. #if WASM_ENABLE_MULTI_MODULE != 0
  1351. ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list =
  1352. &((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list_head;
  1353. ret = wasm_runtime_sub_module_instantiate(
  1354. (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst,
  1355. stack_size, heap_size, error_buf, error_buf_size);
  1356. if (!ret) {
  1357. LOG_DEBUG("build a sub module list failed");
  1358. goto fail;
  1359. }
  1360. #endif
  1361. /* Initialize function type indexes before initializing global info,
  1362. module_inst->func_type_indexes may be used in the latter */
  1363. if (!init_func_type_indexes(module_inst, module, error_buf, error_buf_size))
  1364. goto fail;
  1365. #if WASM_ENABLE_BULK_MEMORY != 0 || WASM_ENABLE_REF_TYPES != 0
  1366. common = &((AOTModuleInstanceExtra *)module_inst->e)->common;
  1367. #endif
  1368. #if WASM_ENABLE_BULK_MEMORY != 0
  1369. if (module->mem_init_data_count > 0) {
  1370. common->data_dropped = bh_bitmap_new(0, module->mem_init_data_count);
  1371. if (common->data_dropped == NULL) {
  1372. LOG_DEBUG("failed to allocate bitmaps");
  1373. set_error_buf(error_buf, error_buf_size,
  1374. "failed to allocate bitmaps");
  1375. goto fail;
  1376. }
  1377. for (i = 0; i < module->mem_init_data_count; i++) {
  1378. if (!module->mem_init_data_list[i]->is_passive)
  1379. bh_bitmap_set_bit(common->data_dropped, i);
  1380. }
  1381. }
  1382. #endif
  1383. #if WASM_ENABLE_REF_TYPES != 0
  1384. if (module->table_init_data_count > 0) {
  1385. common->elem_dropped = bh_bitmap_new(0, module->table_init_data_count);
  1386. if (common->elem_dropped == NULL) {
  1387. LOG_DEBUG("failed to allocate bitmaps");
  1388. set_error_buf(error_buf, error_buf_size,
  1389. "failed to allocate bitmaps");
  1390. goto fail;
  1391. }
  1392. for (i = 0; i < module->table_init_data_count; i++) {
  1393. if (wasm_elem_is_active(module->table_init_data_list[i]->mode))
  1394. bh_bitmap_set_bit(common->elem_dropped, i);
  1395. }
  1396. }
  1397. #endif
  1398. /* Initialize global info */
  1399. p = (uint8 *)module_inst + module_inst_struct_size
  1400. + module_inst_mem_inst_size;
  1401. module_inst->global_data = p;
  1402. module_inst->global_data_size = module->global_data_size;
  1403. if (!global_instantiate(module_inst, module, error_buf, error_buf_size))
  1404. goto fail;
  1405. /* Initialize table info */
  1406. p += module->global_data_size;
  1407. module_inst->table_count = module->table_count + module->import_table_count;
  1408. if (!tables_instantiate(module_inst, module, (AOTTableInstance *)p,
  1409. error_buf, error_buf_size))
  1410. goto fail;
  1411. /* Initialize memory space */
  1412. if (!memories_instantiate(module_inst, parent, module, heap_size, error_buf,
  1413. error_buf_size))
  1414. goto fail;
  1415. /* Initialize function pointers */
  1416. if (!init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  1417. goto fail;
  1418. if (!check_linked_symbol(module, error_buf, error_buf_size))
  1419. goto fail;
  1420. if (!create_exports(module_inst, module, error_buf, error_buf_size))
  1421. goto fail;
  1422. #if WASM_ENABLE_LIBC_WASI != 0
  1423. if (!is_sub_inst) {
  1424. if (!wasm_runtime_init_wasi(
  1425. (WASMModuleInstanceCommon *)module_inst,
  1426. module->wasi_args.dir_list, module->wasi_args.dir_count,
  1427. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  1428. module->wasi_args.env, module->wasi_args.env_count,
  1429. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  1430. module->wasi_args.ns_lookup_pool,
  1431. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  1432. module->wasi_args.argc, module->wasi_args.stdio[0],
  1433. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  1434. error_buf, error_buf_size))
  1435. goto fail;
  1436. }
  1437. #endif
  1438. /* Initialize the thread related data */
  1439. if (stack_size == 0)
  1440. stack_size = DEFAULT_WASM_STACK_SIZE;
  1441. #if WASM_ENABLE_SPEC_TEST != 0
  1442. #if WASM_ENABLE_TAIL_CALL == 0
  1443. if (stack_size < 128 * 1024)
  1444. stack_size = 128 * 1024;
  1445. #else
  1446. /* Some tail-call cases require large operand stack */
  1447. if (stack_size < 10 * 1024 * 1024)
  1448. stack_size = 10 * 1024 * 1024;
  1449. #endif
  1450. #endif
  1451. module_inst->default_wasm_stack_size = stack_size;
  1452. ((AOTModuleInstanceExtra *)module_inst->e)->stack_sizes =
  1453. aot_get_data_section_addr(module, AOT_STACK_SIZES_SECTION_NAME, NULL);
  1454. #if WASM_ENABLE_PERF_PROFILING != 0
  1455. total_size = (uint64)sizeof(AOTFuncPerfProfInfo)
  1456. * (module->import_func_count + module->func_count);
  1457. if (!(module_inst->func_perf_profilings =
  1458. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1459. goto fail;
  1460. }
  1461. #endif
  1462. #if WASM_ENABLE_GC != 0
  1463. for (i = 0; i < module_inst->table_count; i++) {
  1464. uint32 j;
  1465. AOTTable *table;
  1466. AOTTableInstance *table_inst;
  1467. table_elem_type_t *table_data;
  1468. table = &module->tables[i];
  1469. bh_assert(table);
  1470. if (table->init_expr.init_expr_type == INIT_EXPR_NONE) {
  1471. continue;
  1472. }
  1473. table_inst = module_inst->tables[i];
  1474. bh_assert(table_inst);
  1475. table_data = table_inst->elems;
  1476. bh_assert(table_data);
  1477. for (j = 0; j < table_inst->cur_size; j++) {
  1478. if (!assign_table_init_value(module_inst, module, &table->init_expr,
  1479. table_data + j, error_buf,
  1480. error_buf_size)) {
  1481. goto fail;
  1482. }
  1483. }
  1484. }
  1485. /* Initialize the table data with table init data */
  1486. for (i = 0;
  1487. module_inst->table_count > 0 && i < module->table_init_data_count;
  1488. i++) {
  1489. AOTTableInitData *table_init_data = module->table_init_data_list[i];
  1490. AOTTableInstance *table;
  1491. table_elem_type_t *table_data;
  1492. uint8 tbl_elem_type;
  1493. uint32 tbl_init_size, tbl_max_size, j;
  1494. WASMRefType *tbl_elem_ref_type;
  1495. bh_assert(table_init_data);
  1496. table = module_inst->tables[table_init_data->table_index];
  1497. bh_assert(table);
  1498. table_data = table->elems;
  1499. bh_assert(table_data);
  1500. wasm_runtime_get_table_inst_elem_type(
  1501. (WASMModuleInstanceCommon *)module_inst, i, &tbl_elem_type,
  1502. &tbl_elem_ref_type, &tbl_init_size, &tbl_max_size);
  1503. if (!wasm_elem_is_declarative(table_init_data->mode)
  1504. && !wasm_reftype_is_subtype_of(
  1505. table_init_data->elem_type, table_init_data->elem_ref_type,
  1506. table->elem_type, table->elem_ref_type.elem_ref_type,
  1507. module->types, module->type_count)) {
  1508. set_error_buf(error_buf, error_buf_size,
  1509. "type mismatch: elements segment does not fit");
  1510. goto fail;
  1511. }
  1512. (void)tbl_init_size;
  1513. (void)tbl_max_size;
  1514. if (!wasm_elem_is_active(table_init_data->mode)) {
  1515. continue;
  1516. }
  1517. bh_assert(table_init_data->offset.init_expr_type
  1518. == INIT_EXPR_TYPE_I32_CONST
  1519. || table_init_data->offset.init_expr_type
  1520. == INIT_EXPR_TYPE_GET_GLOBAL
  1521. || table_init_data->offset.init_expr_type
  1522. == INIT_EXPR_TYPE_FUNCREF_CONST
  1523. || table_init_data->offset.init_expr_type
  1524. == INIT_EXPR_TYPE_REFNULL_CONST);
  1525. /* init vec(funcidx) or vec(expr) */
  1526. if (table_init_data->offset.init_expr_type
  1527. == INIT_EXPR_TYPE_GET_GLOBAL) {
  1528. uint32 data_offset;
  1529. if (!check_global_init_expr(module,
  1530. table_init_data->offset.u.global_index,
  1531. error_buf, error_buf_size)) {
  1532. goto fail;
  1533. }
  1534. if (table_init_data->offset.u.global_index
  1535. < module->import_global_count) {
  1536. data_offset =
  1537. module
  1538. ->import_globals[table_init_data->offset.u.global_index]
  1539. .data_offset;
  1540. }
  1541. else {
  1542. data_offset =
  1543. module
  1544. ->globals[table_init_data->offset.u.global_index
  1545. - module->import_global_count]
  1546. .data_offset;
  1547. }
  1548. table_init_data->offset.u.i32 =
  1549. *(uint32 *)(module_inst->global_data + data_offset);
  1550. }
  1551. /* check offset since length might negative */
  1552. if ((uint32)table_init_data->offset.u.i32 > table->cur_size) {
  1553. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)",
  1554. table_init_data->offset.u.i32, table->cur_size);
  1555. set_error_buf(error_buf, error_buf_size,
  1556. "out of bounds table access");
  1557. goto fail;
  1558. }
  1559. if ((uint32)table_init_data->offset.u.i32 + table_init_data->value_count
  1560. > table->cur_size) {
  1561. LOG_DEBUG("base_offset(%d) + length(%d) > table->cur_size(%d)",
  1562. table_init_data->offset.u.i32,
  1563. table_init_data->value_count, table->cur_size);
  1564. set_error_buf(error_buf, error_buf_size,
  1565. "out of bounds table access");
  1566. goto fail;
  1567. }
  1568. for (j = 0; j < module->table_init_data_list[i]->value_count; j++) {
  1569. if (!assign_table_init_value(
  1570. module_inst, module, &table_init_data->init_values[j],
  1571. table_data + table_init_data->offset.u.i32 + j, error_buf,
  1572. error_buf_size)) {
  1573. goto fail;
  1574. }
  1575. }
  1576. }
  1577. #endif
  1578. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1579. if (!(module_inst->frames =
  1580. runtime_malloc(sizeof(Vector), error_buf, error_buf_size))) {
  1581. goto fail;
  1582. }
  1583. #endif
  1584. if (!execute_post_instantiate_functions(module_inst, is_sub_inst,
  1585. exec_env_main)) {
  1586. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  1587. goto fail;
  1588. }
  1589. #if WASM_ENABLE_MEMORY_TRACING != 0
  1590. wasm_runtime_dump_module_inst_mem_consumption(
  1591. (WASMModuleInstanceCommon *)module_inst);
  1592. #endif
  1593. return module_inst;
  1594. fail:
  1595. aot_deinstantiate(module_inst, is_sub_inst);
  1596. return NULL;
  1597. }
  1598. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1599. static void
  1600. destroy_c_api_frames(Vector *frames)
  1601. {
  1602. WASMCApiFrame frame = { 0 };
  1603. uint32 i, total_frames, ret;
  1604. total_frames = (uint32)bh_vector_size(frames);
  1605. for (i = 0; i < total_frames; i++) {
  1606. ret = bh_vector_get(frames, i, &frame);
  1607. bh_assert(ret);
  1608. if (frame.lp)
  1609. wasm_runtime_free(frame.lp);
  1610. }
  1611. ret = bh_vector_destroy(frames);
  1612. bh_assert(ret);
  1613. (void)ret;
  1614. }
  1615. #endif
  1616. void
  1617. aot_deinstantiate(AOTModuleInstance *module_inst, bool is_sub_inst)
  1618. {
  1619. WASMModuleInstanceExtraCommon *common =
  1620. &((AOTModuleInstanceExtra *)module_inst->e)->common;
  1621. if (module_inst->exec_env_singleton) {
  1622. /* wasm_exec_env_destroy will call
  1623. wasm_cluster_wait_for_all_except_self to wait for other
  1624. threads, so as to destroy their exec_envs and module
  1625. instances first, and avoid accessing the shared resources
  1626. of current module instance after it is deinstantiated. */
  1627. wasm_exec_env_destroy((WASMExecEnv *)module_inst->exec_env_singleton);
  1628. }
  1629. #if WASM_ENABLE_PERF_PROFILING != 0
  1630. if (module_inst->func_perf_profilings)
  1631. wasm_runtime_free(module_inst->func_perf_profilings);
  1632. #endif
  1633. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1634. if (module_inst->frames) {
  1635. destroy_c_api_frames(module_inst->frames);
  1636. wasm_runtime_free(module_inst->frames);
  1637. module_inst->frames = NULL;
  1638. }
  1639. #endif
  1640. #if WASM_ENABLE_MULTI_MODULE != 0
  1641. wasm_runtime_sub_module_deinstantiate(
  1642. (WASMModuleInstanceCommon *)module_inst);
  1643. #endif
  1644. if (module_inst->tables)
  1645. wasm_runtime_free(module_inst->tables);
  1646. if (module_inst->memories)
  1647. memories_deinstantiate(module_inst);
  1648. if (module_inst->export_functions)
  1649. wasm_runtime_free(module_inst->export_functions);
  1650. if (module_inst->func_ptrs)
  1651. wasm_runtime_free(module_inst->func_ptrs);
  1652. if (module_inst->func_type_indexes)
  1653. wasm_runtime_free(module_inst->func_type_indexes);
  1654. if (common->c_api_func_imports)
  1655. wasm_runtime_free(((AOTModuleInstanceExtra *)module_inst->e)
  1656. ->common.c_api_func_imports);
  1657. #if WASM_ENABLE_GC != 0
  1658. if (!is_sub_inst) {
  1659. AOTModuleInstanceExtra *extra =
  1660. (AOTModuleInstanceExtra *)module_inst->e;
  1661. if (extra->common.gc_heap_handle)
  1662. mem_allocator_destroy(extra->common.gc_heap_handle);
  1663. if (extra->common.gc_heap_pool)
  1664. wasm_runtime_free(extra->common.gc_heap_pool);
  1665. }
  1666. #endif
  1667. if (!is_sub_inst) {
  1668. #if WASM_ENABLE_WASI_NN != 0
  1669. wasi_nn_destroy(module_inst);
  1670. #endif
  1671. wasm_native_call_context_dtors((WASMModuleInstanceCommon *)module_inst);
  1672. }
  1673. #if WASM_ENABLE_BULK_MEMORY != 0
  1674. bh_bitmap_delete(common->data_dropped);
  1675. #endif
  1676. #if WASM_ENABLE_REF_TYPES != 0
  1677. bh_bitmap_delete(common->elem_dropped);
  1678. #endif
  1679. wasm_runtime_free(module_inst);
  1680. }
  1681. AOTFunctionInstance *
  1682. aot_lookup_function(const AOTModuleInstance *module_inst, const char *name,
  1683. const char *signature)
  1684. {
  1685. uint32 i;
  1686. AOTFunctionInstance *export_funcs =
  1687. (AOTFunctionInstance *)module_inst->export_functions;
  1688. for (i = 0; i < module_inst->export_func_count; i++)
  1689. if (!strcmp(export_funcs[i].func_name, name))
  1690. return &export_funcs[i];
  1691. (void)signature;
  1692. return NULL;
  1693. }
  1694. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1695. static bool
  1696. invoke_native_with_hw_bound_check(WASMExecEnv *exec_env, void *func_ptr,
  1697. const WASMFuncType *func_type,
  1698. const char *signature, void *attachment,
  1699. uint32 *argv, uint32 argc, uint32 *argv_ret)
  1700. {
  1701. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1702. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1703. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  1704. uint32 page_size = os_getpagesize();
  1705. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  1706. #ifdef BH_PLATFORM_WINDOWS
  1707. int result;
  1708. bool has_exception;
  1709. char exception[EXCEPTION_BUF_LEN];
  1710. #endif
  1711. bool ret;
  1712. /* Check native stack overflow firstly to ensure we have enough
  1713. native stack to run the following codes before actually calling
  1714. the aot function in invokeNative function. */
  1715. RECORD_STACK_USAGE(exec_env, (uint8 *)&module_inst);
  1716. if ((uint8 *)&module_inst < exec_env->native_stack_boundary
  1717. + page_size * (guard_page_count + 1)) {
  1718. aot_set_exception_with_id(module_inst, EXCE_NATIVE_STACK_OVERFLOW);
  1719. return false;
  1720. }
  1721. if (!exec_env_tls) {
  1722. if (!os_thread_signal_inited()) {
  1723. aot_set_exception(module_inst, "thread signal env not inited");
  1724. return false;
  1725. }
  1726. /* Set thread handle and stack boundary if they haven't been set */
  1727. wasm_exec_env_set_thread_info(exec_env);
  1728. wasm_runtime_set_exec_env_tls(exec_env);
  1729. }
  1730. else {
  1731. if (exec_env_tls != exec_env) {
  1732. aot_set_exception(module_inst, "invalid exec env");
  1733. return false;
  1734. }
  1735. }
  1736. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  1737. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  1738. #if WASM_ENABLE_QUICK_AOT_ENTRY != 0
  1739. /* Quick call if the quick aot entry is registered */
  1740. if (!signature && func_type->quick_aot_entry) {
  1741. void (*invoke_native)(void *func_ptr, void *exec_env, uint32 *argv,
  1742. uint32 *argv_ret) =
  1743. func_type->quick_aot_entry;
  1744. invoke_native(func_ptr, exec_env, argv, argv_ret);
  1745. ret = !aot_copy_exception(module_inst, NULL);
  1746. }
  1747. else
  1748. #endif
  1749. {
  1750. ret = wasm_runtime_invoke_native(exec_env, func_ptr, func_type,
  1751. signature, attachment, argv, argc,
  1752. argv_ret);
  1753. }
  1754. #ifdef BH_PLATFORM_WINDOWS
  1755. has_exception = aot_copy_exception(module_inst, exception);
  1756. if (has_exception && strstr(exception, "native stack overflow")) {
  1757. /* After a stack overflow, the stack was left
  1758. in a damaged state, let the CRT repair it */
  1759. result = _resetstkoflw();
  1760. bh_assert(result != 0);
  1761. }
  1762. #endif
  1763. }
  1764. else {
  1765. /* Exception has been set in signal handler before calling longjmp */
  1766. ret = false;
  1767. }
  1768. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  1769. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  1770. if (!exec_env->jmpbuf_stack_top) {
  1771. wasm_runtime_set_exec_env_tls(NULL);
  1772. }
  1773. if (!ret) {
  1774. os_sigreturn();
  1775. os_signal_unmask();
  1776. }
  1777. (void)jmpbuf_node_pop;
  1778. return ret;
  1779. }
  1780. #define invoke_native_internal invoke_native_with_hw_bound_check /* NOLINT */
  1781. #else /* else of OS_ENABLE_HW_BOUND_CHECK */
  1782. static inline bool
  1783. invoke_native_internal(WASMExecEnv *exec_env, void *func_ptr,
  1784. const WASMFuncType *func_type, const char *signature,
  1785. void *attachment, uint32 *argv, uint32 argc,
  1786. uint32 *argv_ret)
  1787. {
  1788. #if WASM_ENABLE_QUICK_AOT_ENTRY != 0
  1789. /* Quick call if the quick aot entry is registered */
  1790. if (!signature && func_type->quick_aot_entry) {
  1791. AOTModuleInstance *module_inst =
  1792. (AOTModuleInstance *)exec_env->module_inst;
  1793. void (*invoke_native)(void *func_ptr, void *exec_env, uint32 *argv,
  1794. uint32 *argv_ret) = func_type->quick_aot_entry;
  1795. invoke_native(func_ptr, exec_env, argv, argv_ret);
  1796. return !aot_copy_exception(module_inst, NULL);
  1797. }
  1798. #endif
  1799. return wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  1800. attachment, argv, argc, argv_ret);
  1801. }
  1802. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  1803. #ifdef AOT_STACK_FRAME_DEBUG
  1804. typedef void (*stack_frame_callback_t)(struct WASMExecEnv *exec_env);
  1805. static stack_frame_callback_t aot_stack_frame_callback;
  1806. /* set the callback, only for debug purpose */
  1807. void
  1808. aot_set_stack_frame_callback(stack_frame_callback_t callback)
  1809. {
  1810. aot_stack_frame_callback = callback;
  1811. }
  1812. #endif
  1813. bool
  1814. aot_call_function(WASMExecEnv *exec_env, AOTFunctionInstance *function,
  1815. unsigned argc, uint32 argv[])
  1816. {
  1817. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1818. AOTFuncType *func_type = function->is_import_func
  1819. ? function->u.func_import->func_type
  1820. : function->u.func.func_type;
  1821. uint32 result_count = func_type->result_count;
  1822. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  1823. bool ret;
  1824. void *func_ptr = function->is_import_func
  1825. ? function->u.func_import->func_ptr_linked
  1826. : function->u.func.func_ptr;
  1827. #if WASM_ENABLE_MULTI_MODULE != 0
  1828. bh_list *sub_module_list_node = NULL;
  1829. const char *sub_inst_name = NULL;
  1830. const char *func_name = function->u.func_import->module_name;
  1831. if (function->is_import_func) {
  1832. sub_module_list_node =
  1833. ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list;
  1834. sub_module_list_node = bh_list_first_elem(sub_module_list_node);
  1835. while (sub_module_list_node) {
  1836. sub_inst_name =
  1837. ((AOTSubModInstNode *)sub_module_list_node)->module_name;
  1838. if (strcmp(sub_inst_name, func_name) == 0) {
  1839. exec_env = wasm_runtime_get_exec_env_singleton(
  1840. (WASMModuleInstanceCommon *)((AOTSubModInstNode *)
  1841. sub_module_list_node)
  1842. ->module_inst);
  1843. module_inst = (AOTModuleInstance *)exec_env->module_inst;
  1844. break;
  1845. }
  1846. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  1847. }
  1848. if (exec_env == NULL) {
  1849. wasm_runtime_set_exception((WASMModuleInstanceCommon *)module_inst,
  1850. "create singleton exec_env failed");
  1851. return false;
  1852. }
  1853. }
  1854. #endif
  1855. if (argc < func_type->param_cell_num) {
  1856. char buf[108];
  1857. snprintf(buf, sizeof(buf),
  1858. "invalid argument count %u, must be no smaller than %u", argc,
  1859. func_type->param_cell_num);
  1860. aot_set_exception(module_inst, buf);
  1861. return false;
  1862. }
  1863. argc = func_type->param_cell_num;
  1864. #if defined(os_writegsbase)
  1865. {
  1866. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  1867. if (memory_inst)
  1868. /* write base addr of linear memory to GS segment register */
  1869. os_writegsbase(memory_inst->memory_data);
  1870. }
  1871. #endif
  1872. /* func pointer was looked up previously */
  1873. bh_assert(func_ptr != NULL);
  1874. #ifndef OS_ENABLE_HW_BOUND_CHECK
  1875. /* Set thread handle and stack boundary */
  1876. wasm_exec_env_set_thread_info(exec_env);
  1877. #else
  1878. /* Set thread info in invoke_native_with_hw_bound_check when
  1879. hw bound check is enabled */
  1880. #endif
  1881. /* Set exec env so it can be later retrieved from instance */
  1882. ((AOTModuleInstanceExtra *)module_inst->e)->common.cur_exec_env = exec_env;
  1883. if (ext_ret_count > 0) {
  1884. uint32 cell_num = 0, i;
  1885. uint8 *ext_ret_types = func_type->types + func_type->param_count + 1;
  1886. uint32 argv1_buf[32], *argv1 = argv1_buf, *ext_rets = NULL;
  1887. uint32 *argv_ret = argv;
  1888. uint32 ext_ret_cell = wasm_get_cell_num(ext_ret_types, ext_ret_count);
  1889. uint64 size;
  1890. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  1891. struct WASMInterpFrame *prev_frame = exec_env->cur_frame;
  1892. #endif
  1893. /* Allocate memory all arguments */
  1894. size =
  1895. sizeof(uint32) * (uint64)argc /* original arguments */
  1896. + sizeof(void *)
  1897. * (uint64)ext_ret_count /* extra result values' addr */
  1898. + sizeof(uint32) * (uint64)ext_ret_cell; /* extra result values */
  1899. if (size > sizeof(argv1_buf)
  1900. && !(argv1 = runtime_malloc(size, module_inst->cur_exception,
  1901. sizeof(module_inst->cur_exception)))) {
  1902. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_MEMORY);
  1903. return false;
  1904. }
  1905. /* Copy original arguments */
  1906. bh_memcpy_s(argv1, (uint32)size, argv, sizeof(uint32) * argc);
  1907. /* Get the extra result value's address */
  1908. ext_rets =
  1909. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1910. /* Append each extra result value's address to original arguments */
  1911. for (i = 0; i < ext_ret_count; i++) {
  1912. *(uintptr_t *)(argv1 + argc + sizeof(void *) / sizeof(uint32) * i) =
  1913. (uintptr_t)(ext_rets + cell_num);
  1914. cell_num += wasm_value_type_cell_num(ext_ret_types[i]);
  1915. }
  1916. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  1917. if (!aot_alloc_frame(exec_env, function->func_index)) {
  1918. if (argv1 != argv1_buf)
  1919. wasm_runtime_free(argv1);
  1920. return false;
  1921. }
  1922. #endif
  1923. ret = invoke_native_internal(exec_env, function->u.func.func_ptr,
  1924. func_type, NULL, NULL, argv1, argc, argv);
  1925. if (!ret) {
  1926. #ifdef AOT_STACK_FRAME_DEBUG
  1927. if (aot_stack_frame_callback) {
  1928. aot_stack_frame_callback(exec_env);
  1929. }
  1930. #endif
  1931. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1932. if (aot_create_call_stack(exec_env)) {
  1933. aot_dump_call_stack(exec_env, true, NULL, 0);
  1934. }
  1935. #endif
  1936. }
  1937. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  1938. /* Free all frames allocated, note that some frames
  1939. may be allocated in AOT code and havent' been
  1940. freed if exception occured */
  1941. while (exec_env->cur_frame != prev_frame)
  1942. aot_free_frame(exec_env);
  1943. #endif
  1944. if (!ret) {
  1945. if (argv1 != argv1_buf)
  1946. wasm_runtime_free(argv1);
  1947. return ret;
  1948. }
  1949. /* Get extra result values */
  1950. switch (func_type->types[func_type->param_count]) {
  1951. case VALUE_TYPE_I32:
  1952. case VALUE_TYPE_F32:
  1953. #if WASM_ENABLE_REF_TYPES != 0
  1954. case VALUE_TYPE_FUNCREF:
  1955. case VALUE_TYPE_EXTERNREF:
  1956. #endif
  1957. argv_ret++;
  1958. break;
  1959. case VALUE_TYPE_I64:
  1960. case VALUE_TYPE_F64:
  1961. argv_ret += 2;
  1962. break;
  1963. #if WASM_ENABLE_SIMD != 0
  1964. case VALUE_TYPE_V128:
  1965. argv_ret += 4;
  1966. break;
  1967. #endif
  1968. default:
  1969. bh_assert(0);
  1970. break;
  1971. }
  1972. ext_rets =
  1973. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  1974. bh_memcpy_s(argv_ret, sizeof(uint32) * cell_num, ext_rets,
  1975. sizeof(uint32) * cell_num);
  1976. if (argv1 != argv1_buf)
  1977. wasm_runtime_free(argv1);
  1978. return true;
  1979. }
  1980. else {
  1981. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  1982. struct WASMInterpFrame *prev_frame = exec_env->cur_frame;
  1983. if (!aot_alloc_frame(exec_env, function->func_index)) {
  1984. return false;
  1985. }
  1986. #endif
  1987. ret = invoke_native_internal(exec_env, func_ptr, func_type, NULL, NULL,
  1988. argv, argc, argv);
  1989. if (aot_copy_exception(module_inst, NULL)) {
  1990. #ifdef AOT_STACK_FRAME_DEBUG
  1991. if (aot_stack_frame_callback) {
  1992. aot_stack_frame_callback(exec_env);
  1993. }
  1994. #endif
  1995. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  1996. if (aot_create_call_stack(exec_env)) {
  1997. aot_dump_call_stack(exec_env, true, NULL, 0);
  1998. }
  1999. #endif
  2000. }
  2001. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2002. /* Free all frames allocated, note that some frames
  2003. may be allocated in AOT code and havent' been
  2004. freed if exception occured */
  2005. while (exec_env->cur_frame != prev_frame)
  2006. aot_free_frame(exec_env);
  2007. #endif
  2008. return ret && !aot_copy_exception(module_inst, NULL) ? true : false;
  2009. }
  2010. }
  2011. void
  2012. aot_set_exception(AOTModuleInstance *module_inst, const char *exception)
  2013. {
  2014. wasm_set_exception(module_inst, exception);
  2015. }
  2016. void
  2017. aot_set_exception_with_id(AOTModuleInstance *module_inst, uint32 id)
  2018. {
  2019. if (id != EXCE_ALREADY_THROWN)
  2020. wasm_set_exception_with_id(module_inst, id);
  2021. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2022. wasm_runtime_access_exce_check_guard_page();
  2023. #endif
  2024. }
  2025. const char *
  2026. aot_get_exception(AOTModuleInstance *module_inst)
  2027. {
  2028. return wasm_get_exception(module_inst);
  2029. }
  2030. bool
  2031. aot_copy_exception(AOTModuleInstance *module_inst, char *exception_buf)
  2032. {
  2033. /* The field offsets of cur_exception in AOTModuleInstance and
  2034. WASMModuleInstance are the same */
  2035. return wasm_copy_exception(module_inst, exception_buf);
  2036. }
  2037. static bool
  2038. execute_malloc_function(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  2039. AOTFunctionInstance *malloc_func,
  2040. AOTFunctionInstance *retain_func, uint32 size,
  2041. uint32 *p_result)
  2042. {
  2043. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2044. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  2045. #endif
  2046. WASMExecEnv *exec_env_created = NULL;
  2047. WASMModuleInstanceCommon *module_inst_old = NULL;
  2048. uint32 argv[2], argc;
  2049. bool ret;
  2050. argv[0] = size;
  2051. argc = 1;
  2052. if (retain_func) {
  2053. argv[1] = 0;
  2054. argc = 2;
  2055. }
  2056. if (exec_env) {
  2057. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2058. if (exec_env_tls) {
  2059. bh_assert(exec_env_tls == exec_env);
  2060. }
  2061. #endif
  2062. bh_assert(exec_env->module_inst
  2063. == (WASMModuleInstanceCommon *)module_inst);
  2064. }
  2065. else {
  2066. /* Try using the existing exec_env */
  2067. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2068. exec_env = exec_env_tls;
  2069. #endif
  2070. #if WASM_ENABLE_THREAD_MGR != 0
  2071. if (!exec_env)
  2072. exec_env = wasm_clusters_search_exec_env(
  2073. (WASMModuleInstanceCommon *)module_inst);
  2074. #endif
  2075. if (!exec_env) {
  2076. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  2077. (WASMModuleInstanceCommon *)module_inst,
  2078. module_inst->default_wasm_stack_size))) {
  2079. wasm_set_exception(module_inst, "allocate memory failed");
  2080. return false;
  2081. }
  2082. }
  2083. else {
  2084. /* Temporarily replace exec_env's module inst with current
  2085. module inst to ensure that the exec_env's module inst
  2086. is the correct one. */
  2087. module_inst_old = exec_env->module_inst;
  2088. wasm_exec_env_set_module_inst(
  2089. exec_env, (WASMModuleInstanceCommon *)module_inst);
  2090. }
  2091. }
  2092. ret = aot_call_function(exec_env, malloc_func, argc, argv);
  2093. if (retain_func && ret)
  2094. ret = aot_call_function(exec_env, retain_func, 1, argv);
  2095. if (module_inst_old)
  2096. /* Restore the existing exec_env's module inst */
  2097. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  2098. if (exec_env_created)
  2099. wasm_exec_env_destroy(exec_env_created);
  2100. if (ret)
  2101. *p_result = argv[0];
  2102. return ret;
  2103. }
  2104. static bool
  2105. execute_free_function(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  2106. AOTFunctionInstance *free_func, uint32 offset)
  2107. {
  2108. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2109. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  2110. #endif
  2111. WASMExecEnv *exec_env_created = NULL;
  2112. WASMModuleInstanceCommon *module_inst_old = NULL;
  2113. uint32 argv[2];
  2114. bool ret;
  2115. argv[0] = offset;
  2116. if (exec_env) {
  2117. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2118. if (exec_env_tls) {
  2119. bh_assert(exec_env_tls == exec_env);
  2120. }
  2121. #endif
  2122. bh_assert(exec_env->module_inst
  2123. == (WASMModuleInstanceCommon *)module_inst);
  2124. }
  2125. else {
  2126. /* Try using the existing exec_env */
  2127. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2128. exec_env = exec_env_tls;
  2129. #endif
  2130. #if WASM_ENABLE_THREAD_MGR != 0
  2131. if (!exec_env)
  2132. exec_env = wasm_clusters_search_exec_env(
  2133. (WASMModuleInstanceCommon *)module_inst);
  2134. #endif
  2135. if (!exec_env) {
  2136. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  2137. (WASMModuleInstanceCommon *)module_inst,
  2138. module_inst->default_wasm_stack_size))) {
  2139. wasm_set_exception(module_inst, "allocate memory failed");
  2140. return false;
  2141. }
  2142. }
  2143. else {
  2144. /* Temporarily replace exec_env's module inst with current
  2145. module inst to ensure that the exec_env's module inst
  2146. is the correct one. */
  2147. module_inst_old = exec_env->module_inst;
  2148. wasm_exec_env_set_module_inst(
  2149. exec_env, (WASMModuleInstanceCommon *)module_inst);
  2150. }
  2151. }
  2152. ret = aot_call_function(exec_env, free_func, 1, argv);
  2153. if (module_inst_old)
  2154. /* Restore the existing exec_env's module inst */
  2155. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  2156. if (exec_env_created)
  2157. wasm_exec_env_destroy(exec_env_created);
  2158. return ret;
  2159. }
  2160. uint32
  2161. aot_module_malloc_internal(AOTModuleInstance *module_inst,
  2162. WASMExecEnv *exec_env, uint32 size,
  2163. void **p_native_addr)
  2164. {
  2165. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  2166. AOTModule *module = (AOTModule *)module_inst->module;
  2167. uint8 *addr = NULL;
  2168. uint32 offset = 0;
  2169. if (!memory_inst) {
  2170. aot_set_exception(module_inst, "uninitialized memory");
  2171. return 0;
  2172. }
  2173. if (memory_inst->heap_handle) {
  2174. addr = mem_allocator_malloc(memory_inst->heap_handle, size);
  2175. }
  2176. else if (module->malloc_func_index != (uint32)-1
  2177. && module->free_func_index != (uint32)-1) {
  2178. AOTFunctionInstance *malloc_func, *retain_func = NULL;
  2179. char *malloc_func_name;
  2180. char *malloc_func_sig;
  2181. if (module->retain_func_index != (uint32)-1) {
  2182. malloc_func_name = "__new";
  2183. malloc_func_sig = "(ii)i";
  2184. retain_func = aot_lookup_function(module_inst, "__retain", "(i)i");
  2185. if (!retain_func)
  2186. retain_func = aot_lookup_function(module_inst, "__pin", "(i)i");
  2187. bh_assert(retain_func);
  2188. }
  2189. else {
  2190. malloc_func_name = "malloc";
  2191. malloc_func_sig = "(i)i";
  2192. }
  2193. malloc_func =
  2194. aot_lookup_function(module_inst, malloc_func_name, malloc_func_sig);
  2195. if (!malloc_func
  2196. || !execute_malloc_function(module_inst, exec_env, malloc_func,
  2197. retain_func, size, &offset)) {
  2198. return 0;
  2199. }
  2200. addr = offset ? (uint8 *)memory_inst->memory_data + offset : NULL;
  2201. }
  2202. if (!addr) {
  2203. if (memory_inst->heap_handle
  2204. && mem_allocator_is_heap_corrupted(memory_inst->heap_handle)) {
  2205. wasm_runtime_show_app_heap_corrupted_prompt();
  2206. aot_set_exception(module_inst, "app heap corrupted");
  2207. }
  2208. else {
  2209. LOG_WARNING("warning: allocate %u bytes memory failed", size);
  2210. }
  2211. return 0;
  2212. }
  2213. if (p_native_addr)
  2214. *p_native_addr = addr;
  2215. return (uint32)(addr - memory_inst->memory_data);
  2216. }
  2217. uint32
  2218. aot_module_realloc_internal(AOTModuleInstance *module_inst,
  2219. WASMExecEnv *exec_env, uint32 ptr, uint32 size,
  2220. void **p_native_addr)
  2221. {
  2222. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  2223. uint8 *addr = NULL;
  2224. if (!memory_inst) {
  2225. aot_set_exception(module_inst, "uninitialized memory");
  2226. return 0;
  2227. }
  2228. if (memory_inst->heap_handle) {
  2229. addr = mem_allocator_realloc(
  2230. memory_inst->heap_handle,
  2231. ptr ? memory_inst->memory_data + ptr : NULL, size);
  2232. }
  2233. /* Only support realloc in WAMR's app heap */
  2234. (void)exec_env;
  2235. if (!addr) {
  2236. if (memory_inst->heap_handle
  2237. && mem_allocator_is_heap_corrupted(memory_inst->heap_handle)) {
  2238. aot_set_exception(module_inst, "app heap corrupted");
  2239. }
  2240. else {
  2241. aot_set_exception(module_inst, "out of memory");
  2242. }
  2243. return 0;
  2244. }
  2245. if (p_native_addr)
  2246. *p_native_addr = addr;
  2247. return (uint32)(addr - memory_inst->memory_data);
  2248. }
  2249. void
  2250. aot_module_free_internal(AOTModuleInstance *module_inst, WASMExecEnv *exec_env,
  2251. uint32 ptr)
  2252. {
  2253. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  2254. AOTModule *module = (AOTModule *)module_inst->module;
  2255. if (!memory_inst) {
  2256. return;
  2257. }
  2258. if (ptr) {
  2259. uint8 *addr = memory_inst->memory_data + ptr;
  2260. uint8 *memory_data_end;
  2261. /* memory->memory_data_end may be changed in memory grow */
  2262. SHARED_MEMORY_LOCK(memory_inst);
  2263. memory_data_end = memory_inst->memory_data_end;
  2264. SHARED_MEMORY_UNLOCK(memory_inst);
  2265. if (memory_inst->heap_handle && memory_inst->heap_data < addr
  2266. && addr < memory_inst->heap_data_end) {
  2267. mem_allocator_free(memory_inst->heap_handle, addr);
  2268. }
  2269. else if (module->malloc_func_index != (uint32)-1
  2270. && module->free_func_index != (uint32)-1
  2271. && memory_inst->memory_data <= addr
  2272. && addr < memory_data_end) {
  2273. AOTFunctionInstance *free_func;
  2274. char *free_func_name;
  2275. if (module->retain_func_index != (uint32)-1) {
  2276. free_func_name = "__release";
  2277. }
  2278. else {
  2279. free_func_name = "free";
  2280. }
  2281. free_func =
  2282. aot_lookup_function(module_inst, free_func_name, "(i)i");
  2283. if (!free_func && module->retain_func_index != (uint32)-1)
  2284. free_func = aot_lookup_function(module_inst, "__unpin", "(i)i");
  2285. if (free_func)
  2286. execute_free_function(module_inst, exec_env, free_func, ptr);
  2287. }
  2288. }
  2289. }
  2290. uint32
  2291. aot_module_malloc(AOTModuleInstance *module_inst, uint32 size,
  2292. void **p_native_addr)
  2293. {
  2294. return aot_module_malloc_internal(module_inst, NULL, size, p_native_addr);
  2295. }
  2296. uint32
  2297. aot_module_realloc(AOTModuleInstance *module_inst, uint32 ptr, uint32 size,
  2298. void **p_native_addr)
  2299. {
  2300. return aot_module_realloc_internal(module_inst, NULL, ptr, size,
  2301. p_native_addr);
  2302. }
  2303. void
  2304. aot_module_free(AOTModuleInstance *module_inst, uint32 ptr)
  2305. {
  2306. aot_module_free_internal(module_inst, NULL, ptr);
  2307. }
  2308. uint32
  2309. aot_module_dup_data(AOTModuleInstance *module_inst, const char *src,
  2310. uint32 size)
  2311. {
  2312. char *buffer;
  2313. uint32 buffer_offset =
  2314. aot_module_malloc(module_inst, size, (void **)&buffer);
  2315. if (buffer_offset != 0) {
  2316. buffer = wasm_runtime_addr_app_to_native(
  2317. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  2318. bh_memcpy_s(buffer, size, src, size);
  2319. }
  2320. return buffer_offset;
  2321. }
  2322. bool
  2323. aot_enlarge_memory(AOTModuleInstance *module_inst, uint32 inc_page_count)
  2324. {
  2325. return wasm_enlarge_memory(module_inst, inc_page_count);
  2326. }
  2327. bool
  2328. aot_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  2329. uint32 *argv)
  2330. {
  2331. AOTModuleInstance *module_inst =
  2332. (AOTModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  2333. AOTModule *aot_module = (AOTModule *)module_inst->module;
  2334. AOTModuleInstanceExtra *module_inst_extra =
  2335. (AOTModuleInstanceExtra *)module_inst->e;
  2336. CApiFuncImport *c_api_func_import =
  2337. module_inst_extra->common.c_api_func_imports
  2338. ? module_inst_extra->common.c_api_func_imports + func_idx
  2339. : NULL;
  2340. uint32 *func_type_indexes = module_inst->func_type_indexes;
  2341. uint32 func_type_idx = func_type_indexes[func_idx];
  2342. AOTFuncType *func_type = (AOTFuncType *)aot_module->types[func_type_idx];
  2343. void **func_ptrs = module_inst->func_ptrs;
  2344. void *func_ptr = func_ptrs[func_idx];
  2345. AOTImportFunc *import_func;
  2346. const char *signature;
  2347. void *attachment;
  2348. char buf[96];
  2349. bool ret = false;
  2350. #if WASM_ENABLE_MULTI_MODULE != 0
  2351. bh_list *sub_module_list_node = NULL;
  2352. const char *sub_inst_name = NULL;
  2353. #endif
  2354. bh_assert(func_idx < aot_module->import_func_count);
  2355. import_func = aot_module->import_funcs + func_idx;
  2356. if (import_func->call_conv_wasm_c_api)
  2357. func_ptr =
  2358. c_api_func_import ? c_api_func_import->func_ptr_linked : NULL;
  2359. if (!func_ptr) {
  2360. snprintf(buf, sizeof(buf),
  2361. "failed to call unlinked import function (%s, %s)",
  2362. import_func->module_name, import_func->func_name);
  2363. aot_set_exception(module_inst, buf);
  2364. goto fail;
  2365. }
  2366. attachment = import_func->attachment;
  2367. if (import_func->call_conv_wasm_c_api) {
  2368. ret = wasm_runtime_invoke_c_api_native(
  2369. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  2370. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  2371. }
  2372. else if (!import_func->call_conv_raw) {
  2373. signature = import_func->signature;
  2374. #if WASM_ENABLE_MULTI_MODULE != 0
  2375. sub_module_list_node =
  2376. ((AOTModuleInstanceExtra *)module_inst->e)->sub_module_inst_list;
  2377. sub_module_list_node = bh_list_first_elem(sub_module_list_node);
  2378. while (sub_module_list_node) {
  2379. sub_inst_name =
  2380. ((AOTSubModInstNode *)sub_module_list_node)->module_name;
  2381. if (strcmp(sub_inst_name, import_func->module_name) == 0) {
  2382. exec_env = wasm_runtime_get_exec_env_singleton(
  2383. (WASMModuleInstanceCommon *)((AOTSubModInstNode *)
  2384. sub_module_list_node)
  2385. ->module_inst);
  2386. break;
  2387. }
  2388. sub_module_list_node = bh_list_elem_next(sub_module_list_node);
  2389. }
  2390. if (exec_env == NULL) {
  2391. wasm_runtime_set_exception((WASMModuleInstanceCommon *)module_inst,
  2392. "create singleton exec_env failed");
  2393. goto fail;
  2394. }
  2395. #endif
  2396. ret =
  2397. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  2398. attachment, argv, argc, argv);
  2399. }
  2400. else {
  2401. signature = import_func->signature;
  2402. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  2403. signature, attachment, argv, argc,
  2404. argv);
  2405. }
  2406. fail:
  2407. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2408. if (!ret)
  2409. wasm_runtime_access_exce_check_guard_page();
  2410. #endif
  2411. return ret;
  2412. }
  2413. bool
  2414. aot_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 table_elem_idx,
  2415. uint32 argc, uint32 *argv)
  2416. {
  2417. AOTModuleInstance *module_inst =
  2418. (AOTModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  2419. AOTModule *aot_module = (AOTModule *)module_inst->module;
  2420. uint32 *func_type_indexes = module_inst->func_type_indexes;
  2421. AOTTableInstance *tbl_inst;
  2422. AOTFuncType *func_type;
  2423. void **func_ptrs = module_inst->func_ptrs, *func_ptr;
  2424. uint32 func_type_idx, func_idx, ext_ret_count;
  2425. table_elem_type_t tbl_elem_val = NULL_REF;
  2426. AOTImportFunc *import_func;
  2427. const char *signature = NULL;
  2428. void *attachment = NULL;
  2429. char buf[96];
  2430. bool ret;
  2431. /* this function is called from native code, so exec_env->handle and
  2432. exec_env->native_stack_boundary must have been set, we don't set
  2433. it again */
  2434. RECORD_STACK_USAGE(exec_env, (uint8 *)&module_inst);
  2435. if ((uint8 *)&module_inst < exec_env->native_stack_boundary) {
  2436. aot_set_exception_with_id(module_inst, EXCE_NATIVE_STACK_OVERFLOW);
  2437. goto fail;
  2438. }
  2439. tbl_inst = module_inst->tables[tbl_idx];
  2440. bh_assert(tbl_inst);
  2441. if (table_elem_idx >= tbl_inst->cur_size) {
  2442. aot_set_exception_with_id(module_inst, EXCE_UNDEFINED_ELEMENT);
  2443. goto fail;
  2444. }
  2445. tbl_elem_val = ((table_elem_type_t *)tbl_inst->elems)[table_elem_idx];
  2446. if (tbl_elem_val == NULL_REF) {
  2447. aot_set_exception_with_id(module_inst, EXCE_UNINITIALIZED_ELEMENT);
  2448. goto fail;
  2449. }
  2450. #if WASM_ENABLE_GC == 0
  2451. func_idx = tbl_elem_val;
  2452. #else
  2453. func_idx =
  2454. wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val);
  2455. #endif
  2456. func_type_idx = func_type_indexes[func_idx];
  2457. func_type = (AOTFuncType *)aot_module->types[func_type_idx];
  2458. if (func_idx >= aot_module->import_func_count) {
  2459. /* func pointer was looked up previously */
  2460. bh_assert(func_ptrs[func_idx] != NULL);
  2461. }
  2462. if (!(func_ptr = func_ptrs[func_idx])) {
  2463. bh_assert(func_idx < aot_module->import_func_count);
  2464. import_func = aot_module->import_funcs + func_idx;
  2465. snprintf(buf, sizeof(buf),
  2466. "failed to call unlinked import function (%s, %s)",
  2467. import_func->module_name, import_func->func_name);
  2468. aot_set_exception(module_inst, buf);
  2469. goto fail;
  2470. }
  2471. if (func_idx < aot_module->import_func_count) {
  2472. /* Call native function */
  2473. import_func = aot_module->import_funcs + func_idx;
  2474. signature = import_func->signature;
  2475. if (import_func->call_conv_raw) {
  2476. attachment = import_func->attachment;
  2477. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  2478. signature, attachment, argv,
  2479. argc, argv);
  2480. if (!ret)
  2481. goto fail;
  2482. return true;
  2483. }
  2484. }
  2485. ext_ret_count =
  2486. func_type->result_count > 1 ? func_type->result_count - 1 : 0;
  2487. if (ext_ret_count > 0) {
  2488. uint32 argv1_buf[32], *argv1 = argv1_buf;
  2489. uint32 *ext_rets = NULL, *argv_ret = argv;
  2490. uint32 cell_num = 0, i;
  2491. uint8 *ext_ret_types = func_type->types + func_type->param_count + 1;
  2492. uint32 ext_ret_cell = wasm_get_cell_num(ext_ret_types, ext_ret_count);
  2493. uint64 size;
  2494. /* Allocate memory all arguments */
  2495. size =
  2496. sizeof(uint32) * (uint64)argc /* original arguments */
  2497. + sizeof(void *)
  2498. * (uint64)ext_ret_count /* extra result values' addr */
  2499. + sizeof(uint32) * (uint64)ext_ret_cell; /* extra result values */
  2500. if (size > sizeof(argv1_buf)
  2501. && !(argv1 = runtime_malloc(size, module_inst->cur_exception,
  2502. sizeof(module_inst->cur_exception)))) {
  2503. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_MEMORY);
  2504. goto fail;
  2505. }
  2506. /* Copy original arguments */
  2507. bh_memcpy_s(argv1, (uint32)size, argv, sizeof(uint32) * argc);
  2508. /* Get the extra result value's address */
  2509. ext_rets =
  2510. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  2511. /* Append each extra result value's address to original arguments */
  2512. for (i = 0; i < ext_ret_count; i++) {
  2513. *(uintptr_t *)(argv1 + argc + sizeof(void *) / sizeof(uint32) * i) =
  2514. (uintptr_t)(ext_rets + cell_num);
  2515. cell_num += wasm_value_type_cell_num(ext_ret_types[i]);
  2516. }
  2517. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  2518. attachment, argv1, argc, argv);
  2519. if (!ret) {
  2520. if (argv1 != argv1_buf)
  2521. wasm_runtime_free(argv1);
  2522. goto fail;
  2523. }
  2524. /* Get extra result values */
  2525. switch (func_type->types[func_type->param_count]) {
  2526. case VALUE_TYPE_I32:
  2527. case VALUE_TYPE_F32:
  2528. #if WASM_ENABLE_REF_TYPES != 0
  2529. case VALUE_TYPE_FUNCREF:
  2530. case VALUE_TYPE_EXTERNREF:
  2531. #endif
  2532. argv_ret++;
  2533. break;
  2534. case VALUE_TYPE_I64:
  2535. case VALUE_TYPE_F64:
  2536. argv_ret += 2;
  2537. break;
  2538. #if WASM_ENABLE_SIMD != 0
  2539. case VALUE_TYPE_V128:
  2540. argv_ret += 4;
  2541. break;
  2542. #endif
  2543. default:
  2544. bh_assert(0);
  2545. break;
  2546. }
  2547. ext_rets =
  2548. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  2549. bh_memcpy_s(argv_ret, sizeof(uint32) * cell_num, ext_rets,
  2550. sizeof(uint32) * cell_num);
  2551. if (argv1 != argv1_buf)
  2552. wasm_runtime_free(argv1);
  2553. return true;
  2554. }
  2555. else {
  2556. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  2557. attachment, argv, argc, argv);
  2558. if (!ret)
  2559. goto fail;
  2560. return true;
  2561. }
  2562. fail:
  2563. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2564. wasm_runtime_access_exce_check_guard_page();
  2565. #endif
  2566. return false;
  2567. }
  2568. bool
  2569. aot_check_app_addr_and_convert(AOTModuleInstance *module_inst, bool is_str,
  2570. uint32 app_buf_addr, uint32 app_buf_size,
  2571. void **p_native_addr)
  2572. {
  2573. bool ret;
  2574. ret = wasm_check_app_addr_and_convert(module_inst, is_str, app_buf_addr,
  2575. app_buf_size, p_native_addr);
  2576. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2577. if (!ret)
  2578. wasm_runtime_access_exce_check_guard_page();
  2579. #endif
  2580. return ret;
  2581. }
  2582. void *
  2583. aot_memmove(void *dest, const void *src, size_t n)
  2584. {
  2585. return memmove(dest, src, n);
  2586. }
  2587. void *
  2588. aot_memset(void *s, int c, size_t n)
  2589. {
  2590. return memset(s, c, n);
  2591. }
  2592. double
  2593. aot_sqrt(double x)
  2594. {
  2595. return sqrt(x);
  2596. }
  2597. float
  2598. aot_sqrtf(float x)
  2599. {
  2600. return sqrtf(x);
  2601. }
  2602. #if WASM_ENABLE_BULK_MEMORY != 0
  2603. bool
  2604. aot_memory_init(AOTModuleInstance *module_inst, uint32 seg_index, uint32 offset,
  2605. uint32 len, uint32 dst)
  2606. {
  2607. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  2608. AOTModule *aot_module;
  2609. uint8 *data;
  2610. uint8 *maddr;
  2611. uint64 seg_len;
  2612. if (bh_bitmap_get_bit(
  2613. ((AOTModuleInstanceExtra *)module_inst->e)->common.data_dropped,
  2614. seg_index)) {
  2615. seg_len = 0;
  2616. data = NULL;
  2617. }
  2618. else {
  2619. aot_module = (AOTModule *)module_inst->module;
  2620. seg_len = aot_module->mem_init_data_list[seg_index]->byte_count;
  2621. data = aot_module->mem_init_data_list[seg_index]->bytes;
  2622. }
  2623. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  2624. dst, len))
  2625. return false;
  2626. if ((uint64)offset + (uint64)len > seg_len) {
  2627. aot_set_exception(module_inst, "out of bounds memory access");
  2628. return false;
  2629. }
  2630. maddr = wasm_runtime_addr_app_to_native(
  2631. (WASMModuleInstanceCommon *)module_inst, dst);
  2632. SHARED_MEMORY_LOCK(memory_inst);
  2633. bh_memcpy_s(maddr, memory_inst->memory_data_size - dst, data + offset, len);
  2634. SHARED_MEMORY_UNLOCK(memory_inst);
  2635. return true;
  2636. }
  2637. bool
  2638. aot_data_drop(AOTModuleInstance *module_inst, uint32 seg_index)
  2639. {
  2640. bh_bitmap_set_bit(
  2641. ((AOTModuleInstanceExtra *)module_inst->e)->common.data_dropped,
  2642. seg_index);
  2643. /* Currently we can't free the dropped data segment
  2644. as the mem_init_data_count is a continuous array */
  2645. return true;
  2646. }
  2647. #endif /* WASM_ENABLE_BULK_MEMORY */
  2648. #if WASM_ENABLE_THREAD_MGR != 0
  2649. bool
  2650. aot_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset, uint32 size)
  2651. {
  2652. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2653. AOTModule *module = (AOTModule *)module_inst->module;
  2654. uint32 stack_top_idx = module->aux_stack_top_global_index;
  2655. uint32 data_end = module->aux_data_end;
  2656. uint32 stack_bottom = module->aux_stack_bottom;
  2657. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  2658. /* Check the aux stack space, currently we don't allocate space in heap */
  2659. if ((is_stack_before_data && (size > start_offset))
  2660. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  2661. return false;
  2662. if (stack_top_idx != (uint32)-1) {
  2663. /* The aux stack top is a wasm global,
  2664. set the initial value for the global */
  2665. uint32 global_offset = module->globals[stack_top_idx].data_offset;
  2666. uint8 *global_addr = module_inst->global_data + global_offset;
  2667. *(int32 *)global_addr = start_offset;
  2668. /* The aux stack boundary is a constant value,
  2669. set the value to exec_env */
  2670. exec_env->aux_stack_boundary.boundary = start_offset - size;
  2671. exec_env->aux_stack_bottom.bottom = start_offset;
  2672. return true;
  2673. }
  2674. return false;
  2675. }
  2676. bool
  2677. aot_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset, uint32 *size)
  2678. {
  2679. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  2680. AOTModule *module = (AOTModule *)module_inst->module;
  2681. /* The aux stack information is resolved in loader
  2682. and store in module */
  2683. uint32 stack_bottom = module->aux_stack_bottom;
  2684. uint32 total_aux_stack_size = module->aux_stack_size;
  2685. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  2686. if (start_offset)
  2687. *start_offset = stack_bottom;
  2688. if (size)
  2689. *size = total_aux_stack_size;
  2690. return true;
  2691. }
  2692. return false;
  2693. }
  2694. #endif
  2695. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  2696. static void
  2697. const_string_node_size_cb(void *key, void *value, void *p_const_string_size)
  2698. {
  2699. uint32 const_string_size = 0;
  2700. const_string_size += bh_hash_map_get_elem_struct_size();
  2701. const_string_size += strlen((const char *)value) + 1;
  2702. *(uint32 *)p_const_string_size += const_string_size;
  2703. }
  2704. void
  2705. aot_get_module_mem_consumption(const AOTModule *module,
  2706. WASMModuleMemConsumption *mem_conspn)
  2707. {
  2708. uint32 i, size;
  2709. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2710. mem_conspn->module_struct_size = sizeof(AOTModule);
  2711. mem_conspn->types_size = sizeof(AOTFuncType *) * module->type_count;
  2712. for (i = 0; i < module->type_count; i++) {
  2713. AOTFuncType *type = (AOTFuncType *)module->types[i];
  2714. size = offsetof(AOTFuncType, types)
  2715. + sizeof(uint8) * (type->param_count + type->result_count);
  2716. mem_conspn->types_size += size;
  2717. }
  2718. mem_conspn->imports_size =
  2719. sizeof(AOTImportMemory) * module->import_memory_count
  2720. + sizeof(AOTImportTable) * module->import_table_count
  2721. + sizeof(AOTImportGlobal) * module->import_global_count
  2722. + sizeof(AOTImportFunc) * module->import_func_count;
  2723. /* func_ptrs and func_type_indexes */
  2724. mem_conspn->functions_size =
  2725. (sizeof(void *) + sizeof(uint32)) * module->func_count;
  2726. mem_conspn->tables_size = sizeof(AOTTable) * module->table_count;
  2727. mem_conspn->memories_size = sizeof(AOTMemory) * module->memory_count;
  2728. mem_conspn->globals_size = sizeof(AOTGlobal) * module->global_count;
  2729. mem_conspn->exports_size = sizeof(AOTExport) * module->export_count;
  2730. mem_conspn->table_segs_size =
  2731. sizeof(AOTTableInitData *) * module->table_init_data_count;
  2732. for (i = 0; i < module->table_init_data_count; i++) {
  2733. AOTTableInitData *init_data = module->table_init_data_list[i];
  2734. size = offsetof(AOTTableInitData, init_values)
  2735. + sizeof(InitializerExpression) * init_data->value_count;
  2736. mem_conspn->table_segs_size += size;
  2737. }
  2738. mem_conspn->data_segs_size =
  2739. sizeof(AOTMemInitData *) * module->mem_init_data_count;
  2740. for (i = 0; i < module->mem_init_data_count; i++) {
  2741. mem_conspn->data_segs_size += sizeof(AOTMemInitData);
  2742. }
  2743. if (module->const_str_set) {
  2744. uint32 const_string_size = 0;
  2745. mem_conspn->const_strs_size =
  2746. bh_hash_map_get_struct_size(module->const_str_set);
  2747. bh_hash_map_traverse(module->const_str_set, const_string_node_size_cb,
  2748. (void *)&const_string_size);
  2749. mem_conspn->const_strs_size += const_string_size;
  2750. }
  2751. /* code size + literal size + object data section size */
  2752. mem_conspn->aot_code_size =
  2753. module->code_size + module->literal_size
  2754. + sizeof(AOTObjectDataSection) * module->data_section_count;
  2755. for (i = 0; i < module->data_section_count; i++) {
  2756. AOTObjectDataSection *obj_data = module->data_sections + i;
  2757. mem_conspn->aot_code_size += sizeof(uint8) * obj_data->size;
  2758. }
  2759. mem_conspn->total_size += mem_conspn->module_struct_size;
  2760. mem_conspn->total_size += mem_conspn->types_size;
  2761. mem_conspn->total_size += mem_conspn->imports_size;
  2762. mem_conspn->total_size += mem_conspn->functions_size;
  2763. mem_conspn->total_size += mem_conspn->tables_size;
  2764. mem_conspn->total_size += mem_conspn->memories_size;
  2765. mem_conspn->total_size += mem_conspn->globals_size;
  2766. mem_conspn->total_size += mem_conspn->exports_size;
  2767. mem_conspn->total_size += mem_conspn->table_segs_size;
  2768. mem_conspn->total_size += mem_conspn->data_segs_size;
  2769. mem_conspn->total_size += mem_conspn->const_strs_size;
  2770. mem_conspn->total_size += mem_conspn->aot_code_size;
  2771. }
  2772. void
  2773. aot_get_module_inst_mem_consumption(const AOTModuleInstance *module_inst,
  2774. WASMModuleInstMemConsumption *mem_conspn)
  2775. {
  2776. AOTTableInstance *tbl_inst;
  2777. uint32 i;
  2778. memset(mem_conspn, 0, sizeof(*mem_conspn));
  2779. mem_conspn->module_inst_struct_size = sizeof(AOTModuleInstance);
  2780. mem_conspn->memories_size =
  2781. sizeof(void *) * module_inst->memory_count
  2782. + sizeof(AOTMemoryInstance) * module_inst->memory_count;
  2783. for (i = 0; i < module_inst->memory_count; i++) {
  2784. AOTMemoryInstance *mem_inst = module_inst->memories[i];
  2785. mem_conspn->memories_size +=
  2786. mem_inst->num_bytes_per_page * mem_inst->cur_page_count;
  2787. mem_conspn->app_heap_size =
  2788. mem_inst->heap_data_end - mem_inst->heap_data;
  2789. /* size of app heap structure */
  2790. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  2791. }
  2792. mem_conspn->tables_size +=
  2793. sizeof(AOTTableInstance *) * module_inst->table_count;
  2794. for (i = 0; i < module_inst->table_count; i++) {
  2795. tbl_inst = module_inst->tables[i];
  2796. mem_conspn->tables_size += offsetof(AOTTableInstance, elems);
  2797. mem_conspn->tables_size += sizeof(uint32) * tbl_inst->max_size;
  2798. }
  2799. /* func_ptrs and func_type_indexes */
  2800. mem_conspn->functions_size =
  2801. (sizeof(void *) + sizeof(uint32))
  2802. * (((AOTModule *)module_inst->module)->import_func_count
  2803. + ((AOTModule *)module_inst->module)->func_count);
  2804. mem_conspn->globals_size = module_inst->global_data_size;
  2805. mem_conspn->exports_size =
  2806. sizeof(AOTFunctionInstance) * (uint64)module_inst->export_func_count;
  2807. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  2808. mem_conspn->total_size += mem_conspn->memories_size;
  2809. mem_conspn->total_size += mem_conspn->functions_size;
  2810. mem_conspn->total_size += mem_conspn->tables_size;
  2811. mem_conspn->total_size += mem_conspn->globals_size;
  2812. mem_conspn->total_size += mem_conspn->exports_size;
  2813. }
  2814. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  2815. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  2816. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2817. void
  2818. aot_drop_table_seg(AOTModuleInstance *module_inst, uint32 tbl_seg_idx)
  2819. {
  2820. bh_bitmap_set_bit(
  2821. ((AOTModuleInstanceExtra *)module_inst->e)->common.elem_dropped,
  2822. tbl_seg_idx);
  2823. }
  2824. void
  2825. aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx,
  2826. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  2827. uint32 dst_offset)
  2828. {
  2829. AOTTableInstance *tbl_inst;
  2830. AOTTableInitData *tbl_seg;
  2831. const AOTModule *module = (AOTModule *)module_inst->module;
  2832. table_elem_type_t *table_elems;
  2833. InitializerExpression *tbl_seg_init_values = NULL, *init_values;
  2834. uint32 i, tbl_seg_len = 0;
  2835. #if WASM_ENABLE_GC != 0
  2836. void *func_obj;
  2837. #endif
  2838. tbl_inst = module_inst->tables[tbl_idx];
  2839. bh_assert(tbl_inst);
  2840. tbl_seg = module->table_init_data_list[tbl_seg_idx];
  2841. bh_assert(tbl_seg);
  2842. if (!bh_bitmap_get_bit(
  2843. ((AOTModuleInstanceExtra *)module_inst->e)->common.elem_dropped,
  2844. tbl_seg_idx)) {
  2845. /* table segment isn't dropped */
  2846. tbl_seg_init_values = tbl_seg->init_values;
  2847. tbl_seg_len = tbl_seg->value_count;
  2848. }
  2849. if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len)
  2850. || offset_len_out_of_bounds(dst_offset, length, tbl_inst->cur_size)) {
  2851. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2852. return;
  2853. }
  2854. if (!length) {
  2855. return;
  2856. }
  2857. table_elems = tbl_inst->elems + dst_offset;
  2858. init_values = tbl_seg_init_values + src_offset;
  2859. for (i = 0; i < length; i++) {
  2860. #if WASM_ENABLE_GC != 0
  2861. /* UINT32_MAX indicates that it is a null ref */
  2862. if (init_values[i].u.ref_index != UINT32_MAX) {
  2863. if (!(func_obj = aot_create_func_obj(module_inst,
  2864. init_values[i].u.ref_index,
  2865. true, NULL, 0))) {
  2866. aot_set_exception_with_id(module_inst, EXCE_NULL_FUNC_OBJ);
  2867. return;
  2868. }
  2869. table_elems[i] = func_obj;
  2870. }
  2871. else {
  2872. table_elems[i] = NULL_REF;
  2873. }
  2874. #else
  2875. table_elems[i] = init_values[i].u.ref_index;
  2876. #endif
  2877. }
  2878. }
  2879. void
  2880. aot_table_copy(AOTModuleInstance *module_inst, uint32 src_tbl_idx,
  2881. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  2882. uint32 dst_offset)
  2883. {
  2884. AOTTableInstance *src_tbl_inst, *dst_tbl_inst;
  2885. src_tbl_inst = module_inst->tables[src_tbl_idx];
  2886. bh_assert(src_tbl_inst);
  2887. dst_tbl_inst = module_inst->tables[dst_tbl_idx];
  2888. bh_assert(dst_tbl_inst);
  2889. if (offset_len_out_of_bounds(dst_offset, length, dst_tbl_inst->cur_size)
  2890. || offset_len_out_of_bounds(src_offset, length,
  2891. src_tbl_inst->cur_size)) {
  2892. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2893. return;
  2894. }
  2895. /* if src_offset >= dst_offset, copy from front to back */
  2896. /* if src_offset < dst_offset, copy from back to front */
  2897. /* merge all together */
  2898. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(AOTTableInstance, elems)
  2899. + dst_offset * sizeof(table_elem_type_t),
  2900. (dst_tbl_inst->cur_size - dst_offset)
  2901. * sizeof(table_elem_type_t),
  2902. (uint8 *)src_tbl_inst + offsetof(AOTTableInstance, elems)
  2903. + src_offset * sizeof(table_elem_type_t),
  2904. length * sizeof(table_elem_type_t));
  2905. }
  2906. void
  2907. aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length,
  2908. table_elem_type_t val, uint32 data_offset)
  2909. {
  2910. AOTTableInstance *tbl_inst;
  2911. tbl_inst = module_inst->tables[tbl_idx];
  2912. bh_assert(tbl_inst);
  2913. if (offset_len_out_of_bounds(data_offset, length, tbl_inst->cur_size)) {
  2914. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  2915. return;
  2916. }
  2917. for (; length != 0; data_offset++, length--) {
  2918. tbl_inst->elems[data_offset] = val;
  2919. }
  2920. }
  2921. uint32
  2922. aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx,
  2923. uint32 inc_entries, table_elem_type_t init_val)
  2924. {
  2925. uint32 entry_count, i, orig_tbl_sz;
  2926. AOTTableInstance *tbl_inst;
  2927. tbl_inst = module_inst->tables[tbl_idx];
  2928. if (!tbl_inst) {
  2929. return (uint32)-1;
  2930. }
  2931. orig_tbl_sz = tbl_inst->cur_size;
  2932. if (!inc_entries) {
  2933. return orig_tbl_sz;
  2934. }
  2935. if (tbl_inst->cur_size > UINT32_MAX - inc_entries) {
  2936. return (uint32)-1;
  2937. }
  2938. entry_count = tbl_inst->cur_size + inc_entries;
  2939. if (entry_count > tbl_inst->max_size) {
  2940. return (uint32)-1;
  2941. }
  2942. /* fill in */
  2943. for (i = 0; i < inc_entries; ++i) {
  2944. tbl_inst->elems[tbl_inst->cur_size + i] = init_val;
  2945. }
  2946. tbl_inst->cur_size = entry_count;
  2947. return orig_tbl_sz;
  2948. }
  2949. #endif /* WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  2950. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2951. #if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0
  2952. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2953. static const char *
  2954. lookup_func_name(const char **func_names, uint32 *func_indexes,
  2955. uint32 func_index_count, uint32 func_index)
  2956. {
  2957. int64 low = 0, mid;
  2958. int64 high = func_index_count - 1;
  2959. if (!func_names || !func_indexes || func_index_count == 0)
  2960. return NULL;
  2961. while (low <= high) {
  2962. mid = (low + high) / 2;
  2963. if (func_index == func_indexes[mid]) {
  2964. return func_names[mid];
  2965. }
  2966. else if (func_index < func_indexes[mid])
  2967. high = mid - 1;
  2968. else
  2969. low = mid + 1;
  2970. }
  2971. return NULL;
  2972. }
  2973. #endif /* WASM_ENABLE_CUSTOM_NAME_SECTION != 0 */
  2974. static const char *
  2975. get_func_name_from_index(const AOTModuleInstance *module_inst,
  2976. uint32 func_index)
  2977. {
  2978. const char *func_name = NULL;
  2979. AOTModule *module = (AOTModule *)module_inst->module;
  2980. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  2981. if ((func_name =
  2982. lookup_func_name(module->aux_func_names, module->aux_func_indexes,
  2983. module->aux_func_name_count, func_index))) {
  2984. return func_name;
  2985. }
  2986. #endif
  2987. if (func_index < module->import_func_count) {
  2988. func_name = module->import_funcs[func_index].func_name;
  2989. }
  2990. else {
  2991. uint32 i;
  2992. for (i = 0; i < module->export_count; i++) {
  2993. AOTExport export = module->exports[i];
  2994. if (export.index == func_index && export.kind == EXPORT_KIND_FUNC) {
  2995. func_name = export.name;
  2996. break;
  2997. }
  2998. }
  2999. }
  3000. return func_name;
  3001. }
  3002. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 || \
  3003. WASM_ENABLE_PERF_PROFILING != 0 */
  3004. #if WASM_ENABLE_GC == 0
  3005. bool
  3006. aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  3007. {
  3008. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3009. #if WASM_ENABLE_PERF_PROFILING != 0
  3010. AOTFuncPerfProfInfo *func_perf_prof =
  3011. module_inst->func_perf_profilings + func_index;
  3012. #endif
  3013. AOTFrame *cur_frame, *frame;
  3014. uint32 size = (uint32)offsetof(AOTFrame, lp);
  3015. cur_frame = (AOTFrame *)exec_env->cur_frame;
  3016. if (!cur_frame)
  3017. frame = (AOTFrame *)exec_env->wasm_stack.bottom;
  3018. else
  3019. frame = (AOTFrame *)((uint8 *)cur_frame + size);
  3020. if ((uint8 *)frame + size > exec_env->wasm_stack.top_boundary) {
  3021. aot_set_exception(module_inst, "wasm operand stack overflow");
  3022. return false;
  3023. }
  3024. frame->func_index = func_index;
  3025. /* No need to initialize ip, it will be committed in jitted code
  3026. when needed */
  3027. /* frame->ip = NULL; */
  3028. frame->prev_frame = (AOTFrame *)exec_env->cur_frame;
  3029. #if WASM_ENABLE_PERF_PROFILING != 0
  3030. frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3031. frame->func_perf_prof_info = func_perf_prof;
  3032. #endif
  3033. #if WASM_ENABLE_MEMORY_PROFILING != 0
  3034. {
  3035. uint32 wasm_stack_used =
  3036. (uint8 *)frame + size - exec_env->wasm_stack.bottom;
  3037. if (wasm_stack_used > exec_env->max_wasm_stack_used)
  3038. exec_env->max_wasm_stack_used = wasm_stack_used;
  3039. }
  3040. #endif
  3041. exec_env->cur_frame = (struct WASMInterpFrame *)frame;
  3042. return true;
  3043. }
  3044. static inline void
  3045. aot_free_frame_internal(WASMExecEnv *exec_env)
  3046. {
  3047. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  3048. AOTFrame *prev_frame = cur_frame->prev_frame;
  3049. #if WASM_ENABLE_PERF_PROFILING != 0
  3050. uint64 time_elapsed =
  3051. (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started;
  3052. cur_frame->func_perf_prof_info->total_exec_time += time_elapsed;
  3053. cur_frame->func_perf_prof_info->total_exec_cnt++;
  3054. /* parent function */
  3055. if (prev_frame)
  3056. prev_frame->func_perf_prof_info->children_exec_time += time_elapsed;
  3057. #endif
  3058. exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame;
  3059. }
  3060. void
  3061. aot_free_frame(WASMExecEnv *exec_env)
  3062. {
  3063. aot_free_frame_internal(exec_env);
  3064. }
  3065. #else /* else of WASM_ENABLE_GC == 0 */
  3066. bool
  3067. aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  3068. {
  3069. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3070. AOTModule *module = (AOTModule *)module_inst->module;
  3071. #if WASM_ENABLE_PERF_PROFILING != 0
  3072. AOTFuncPerfProfInfo *func_perf_prof =
  3073. module_inst->func_perf_profilings + func_index;
  3074. #endif
  3075. AOTFrame *frame;
  3076. uint32 max_local_cell_num, max_stack_cell_num, all_cell_num;
  3077. uint32 aot_func_idx, frame_size;
  3078. if (func_index >= module->import_func_count) {
  3079. aot_func_idx = func_index - module->import_func_count;
  3080. max_local_cell_num = module->max_local_cell_nums[aot_func_idx];
  3081. max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx];
  3082. }
  3083. else {
  3084. AOTFuncType *func_type = module->import_funcs[func_index].func_type;
  3085. max_local_cell_num =
  3086. func_type->param_cell_num > 2 ? func_type->param_cell_num : 2;
  3087. max_stack_cell_num = 0;
  3088. }
  3089. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3090. #if WASM_ENABLE_GC == 0
  3091. frame_size = (uint32)offsetof(AOTFrame, lp) + all_cell_num * 4;
  3092. #else
  3093. frame_size =
  3094. (uint32)offsetof(AOTFrame, lp) + align_uint(all_cell_num * 5, 4);
  3095. #endif
  3096. frame = wasm_exec_env_alloc_wasm_frame(exec_env, frame_size);
  3097. if (!frame) {
  3098. aot_set_exception(module_inst, "wasm operand stack overflow");
  3099. return false;
  3100. }
  3101. #if WASM_ENABLE_PERF_PROFILING != 0
  3102. frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3103. frame->func_perf_prof_info = func_perf_prof;
  3104. #endif
  3105. #if WASM_ENABLE_GC != 0
  3106. frame->sp = frame->lp + max_local_cell_num;
  3107. frame->frame_ref = (uint8 *)(frame->sp + max_stack_cell_num);
  3108. #endif
  3109. frame->prev_frame = (AOTFrame *)exec_env->cur_frame;
  3110. exec_env->cur_frame = (struct WASMInterpFrame *)frame;
  3111. frame->func_index = func_index;
  3112. return true;
  3113. }
  3114. static inline void
  3115. aot_free_frame_internal(WASMExecEnv *exec_env)
  3116. {
  3117. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  3118. AOTFrame *prev_frame = cur_frame->prev_frame;
  3119. #if WASM_ENABLE_PERF_PROFILING != 0
  3120. uint64 time_elapsed =
  3121. (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started;
  3122. cur_frame->func_perf_prof_info->total_exec_time += time_elapsed;
  3123. cur_frame->func_perf_prof_info->total_exec_cnt++;
  3124. /* parent function */
  3125. if (prev_frame)
  3126. prev_frame->func_perf_prof_info->children_exec_time += time_elapsed;
  3127. #endif
  3128. wasm_exec_env_free_wasm_frame(exec_env, cur_frame);
  3129. exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame;
  3130. }
  3131. void
  3132. aot_free_frame(WASMExecEnv *exec_env)
  3133. {
  3134. aot_free_frame_internal(exec_env);
  3135. }
  3136. #endif /* end of WASM_ENABLE_GC == 0 */
  3137. void
  3138. aot_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame)
  3139. {
  3140. #if WASM_ENABLE_PERF_PROFILING != 0
  3141. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  3142. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3143. AOTFuncPerfProfInfo *func_perf_prof =
  3144. module_inst->func_perf_profilings + cur_frame->func_index;
  3145. if (alloc_frame) {
  3146. cur_frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3147. cur_frame->func_perf_prof_info = func_perf_prof;
  3148. }
  3149. else {
  3150. AOTFrame *prev_frame = cur_frame->prev_frame;
  3151. uint64 time_elapsed =
  3152. (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started;
  3153. cur_frame->func_perf_prof_info->total_exec_time += time_elapsed;
  3154. cur_frame->func_perf_prof_info->total_exec_cnt++;
  3155. /* parent function */
  3156. if (prev_frame)
  3157. prev_frame->func_perf_prof_info->children_exec_time += time_elapsed;
  3158. }
  3159. #endif
  3160. #if WASM_ENABLE_MEMORY_PROFILING != 0
  3161. if (alloc_frame) {
  3162. #if WASM_ENABLE_GC == 0
  3163. uint32 wasm_stack_used = (uint8 *)exec_env->cur_frame
  3164. + (uint32)offsetof(AOTFrame, lp)
  3165. - exec_env->wasm_stack.bottom;
  3166. #else
  3167. uint32 wasm_stack_used =
  3168. exec_env->wasm_stack.top - exec_env->wasm_stack.bottom;
  3169. #endif
  3170. if (wasm_stack_used > exec_env->max_wasm_stack_used)
  3171. exec_env->max_wasm_stack_used = wasm_stack_used;
  3172. }
  3173. #endif
  3174. }
  3175. #endif /* end of WASM_ENABLE_AOT_STACK_FRAME != 0 */
  3176. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3177. bool
  3178. aot_create_call_stack(struct WASMExecEnv *exec_env)
  3179. {
  3180. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame,
  3181. *first_frame = cur_frame;
  3182. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3183. AOTModule *module = (AOTModule *)module_inst->module;
  3184. uint32 n = 0;
  3185. while (cur_frame) {
  3186. cur_frame = cur_frame->prev_frame;
  3187. n++;
  3188. }
  3189. /* release previous stack frames and create new ones */
  3190. destroy_c_api_frames(module_inst->frames);
  3191. if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) {
  3192. return false;
  3193. }
  3194. cur_frame = first_frame;
  3195. while (cur_frame) {
  3196. WASMCApiFrame frame = { 0 };
  3197. uint32 max_local_cell_num, max_stack_cell_num;
  3198. uint32 all_cell_num, lp_size;
  3199. frame.instance = module_inst;
  3200. frame.module_offset = 0;
  3201. frame.func_index = cur_frame->func_index;
  3202. frame.func_offset = cur_frame->ip_offset;
  3203. frame.func_name_wp =
  3204. get_func_name_from_index(module_inst, cur_frame->func_index);
  3205. if (cur_frame->func_index >= module->import_func_count) {
  3206. uint32 aot_func_idx =
  3207. cur_frame->func_index - module->import_func_count;
  3208. max_local_cell_num = module->max_local_cell_nums[aot_func_idx];
  3209. max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx];
  3210. }
  3211. else {
  3212. AOTFuncType *func_type =
  3213. module->import_funcs[cur_frame->func_index].func_type;
  3214. max_local_cell_num =
  3215. func_type->param_cell_num > 2 ? func_type->param_cell_num : 2;
  3216. max_stack_cell_num = 0;
  3217. }
  3218. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3219. #if WASM_ENABLE_GC == 0
  3220. lp_size = all_cell_num * 4;
  3221. #else
  3222. lp_size = align_uint(all_cell_num * 5, 4);
  3223. #endif
  3224. if (lp_size > 0) {
  3225. if (!(frame.lp = wasm_runtime_malloc(lp_size))) {
  3226. destroy_c_api_frames(module_inst->frames);
  3227. return false;
  3228. }
  3229. bh_memcpy_s(frame.lp, lp_size, cur_frame->lp, lp_size);
  3230. #if WASM_ENABLE_GC != 0
  3231. uint32 local_ref_flags_cell_num =
  3232. module->func_local_ref_flags[frame.func_index]
  3233. .local_ref_flag_cell_num;
  3234. uint8 *local_ref_flags =
  3235. module->func_local_ref_flags[frame.func_index].local_ref_flags;
  3236. frame.sp = frame.lp + (cur_frame->sp - cur_frame->lp);
  3237. frame.frame_ref = (uint8 *)frame.lp
  3238. + (cur_frame->frame_ref - (uint8 *)cur_frame->lp);
  3239. /* copy local ref flags from AOT module */
  3240. bh_memcpy_s(frame.frame_ref, local_ref_flags_cell_num,
  3241. local_ref_flags, lp_size);
  3242. #endif
  3243. }
  3244. if (!bh_vector_append(module_inst->frames, &frame)) {
  3245. if (frame.lp)
  3246. wasm_runtime_free(frame.lp);
  3247. destroy_c_api_frames(module_inst->frames);
  3248. return false;
  3249. }
  3250. cur_frame = cur_frame->prev_frame;
  3251. }
  3252. return true;
  3253. }
  3254. #define PRINT_OR_DUMP() \
  3255. do { \
  3256. total_len += \
  3257. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  3258. if ((!print) && buf && (len == 0)) { \
  3259. exception_unlock(module_inst); \
  3260. return total_len; \
  3261. } \
  3262. } while (0)
  3263. uint32
  3264. aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len)
  3265. {
  3266. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3267. uint32 n = 0, total_len = 0, total_frames;
  3268. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  3269. * will be truncated */
  3270. char line_buf[256];
  3271. if (!module_inst->frames) {
  3272. return 0;
  3273. }
  3274. total_frames = (uint32)bh_vector_size(module_inst->frames);
  3275. if (total_frames == 0) {
  3276. return 0;
  3277. }
  3278. exception_lock(module_inst);
  3279. snprintf(line_buf, sizeof(line_buf), "\n");
  3280. PRINT_OR_DUMP();
  3281. while (n < total_frames) {
  3282. WASMCApiFrame frame = { 0 };
  3283. uint32 line_length, i;
  3284. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  3285. exception_unlock(module_inst);
  3286. return 0;
  3287. }
  3288. /* function name not exported, print number instead */
  3289. if (frame.func_name_wp == NULL) {
  3290. line_length = snprintf(line_buf, sizeof(line_buf),
  3291. "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n",
  3292. n, frame.func_offset, frame.func_index);
  3293. }
  3294. else {
  3295. line_length = snprintf(line_buf, sizeof(line_buf),
  3296. "#%02" PRIu32 ": 0x%04x - %s\n", n,
  3297. frame.func_offset, frame.func_name_wp);
  3298. }
  3299. if (line_length >= sizeof(line_buf)) {
  3300. uint32 line_buffer_len = sizeof(line_buf);
  3301. /* If line too long, ensure the last character is '\n' */
  3302. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  3303. line_buf[i] = '.';
  3304. }
  3305. line_buf[line_buffer_len - 2] = '\n';
  3306. }
  3307. PRINT_OR_DUMP();
  3308. n++;
  3309. }
  3310. snprintf(line_buf, sizeof(line_buf), "\n");
  3311. PRINT_OR_DUMP();
  3312. exception_unlock(module_inst);
  3313. return total_len + 1;
  3314. }
  3315. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 */
  3316. #if WASM_ENABLE_PERF_PROFILING != 0
  3317. void
  3318. aot_dump_perf_profiling(const AOTModuleInstance *module_inst)
  3319. {
  3320. AOTFuncPerfProfInfo *perf_prof =
  3321. (AOTFuncPerfProfInfo *)module_inst->func_perf_profilings;
  3322. AOTModule *module = (AOTModule *)module_inst->module;
  3323. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3324. const char *func_name;
  3325. os_printf("Performance profiler data:\n");
  3326. for (i = 0; i < total_func_count; i++, perf_prof++) {
  3327. if (perf_prof->total_exec_cnt == 0)
  3328. continue;
  3329. func_name = get_func_name_from_index(module_inst, i);
  3330. if (func_name)
  3331. os_printf(
  3332. " func %s, execution time: %.3f ms, execution count: %" PRIu32
  3333. " times, children execution time: %.3f ms\n",
  3334. func_name, perf_prof->total_exec_time / 1000.0f,
  3335. perf_prof->total_exec_cnt,
  3336. perf_prof->children_exec_time / 1000.0f);
  3337. else
  3338. os_printf(" func %" PRIu32
  3339. ", execution time: %.3f ms, execution count: %" PRIu32
  3340. " times, children execution time: %.3f ms\n",
  3341. i, perf_prof->total_exec_time / 1000.0f,
  3342. perf_prof->total_exec_cnt,
  3343. perf_prof->children_exec_time / 1000.0f);
  3344. }
  3345. }
  3346. double
  3347. aot_summarize_wasm_execute_time(const AOTModuleInstance *inst)
  3348. {
  3349. double ret = 0;
  3350. AOTModule *module = (AOTModule *)inst->module;
  3351. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3352. for (i = 0; i < total_func_count; i++) {
  3353. AOTFuncPerfProfInfo *perf_prof =
  3354. (AOTFuncPerfProfInfo *)inst->func_perf_profilings + i;
  3355. ret += (perf_prof->total_exec_time - perf_prof->children_exec_time)
  3356. / 1000.0f;
  3357. }
  3358. return ret;
  3359. }
  3360. double
  3361. aot_get_wasm_func_exec_time(const AOTModuleInstance *inst,
  3362. const char *func_name)
  3363. {
  3364. AOTModule *module = (AOTModule *)inst->module;
  3365. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3366. for (i = 0; i < total_func_count; i++) {
  3367. const char *name_in_wasm = get_func_name_from_index(inst, i);
  3368. if (name_in_wasm && strcmp(func_name, name_in_wasm) == 0) {
  3369. AOTFuncPerfProfInfo *perf_prof =
  3370. (AOTFuncPerfProfInfo *)inst->func_perf_profilings + i;
  3371. return (perf_prof->total_exec_time - perf_prof->children_exec_time)
  3372. / 1000.0f;
  3373. }
  3374. }
  3375. return -1.0;
  3376. }
  3377. #endif /* end of WASM_ENABLE_PERF_PROFILING != 0 */
  3378. #if WASM_ENABLE_STATIC_PGO != 0
  3379. /* indirect call target */
  3380. #define IPVK_IndirectCallTarget 0
  3381. /* memory intrinsic functions size */
  3382. #define IPVK_MemOPSize 1
  3383. #define IPVK_First IPVK_IndirectCallTarget
  3384. #define IPVK_Last IPVK_MemOPSize
  3385. #define INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE 24
  3386. #define INSTR_PROF_MAX_NUM_VAL_PER_SITE 255
  3387. static int hasNonDefaultValsPerSite = 0;
  3388. static uint32 VPMaxNumValsPerSite = INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE;
  3389. static bool
  3390. cmpxchg_ptr(void **ptr, void *old_val, void *new_val)
  3391. {
  3392. #if defined(os_atomic_cmpxchg)
  3393. return os_atomic_cmpxchg(ptr, &old_val, new_val);
  3394. #else
  3395. /* TODO: add lock when thread-manager is enabled */
  3396. void *read = *ptr;
  3397. if (read == old_val) {
  3398. *ptr = new_val;
  3399. return true;
  3400. }
  3401. return false;
  3402. #endif
  3403. }
  3404. static int
  3405. allocateValueProfileCounters(LLVMProfileData *Data)
  3406. {
  3407. ValueProfNode **Mem;
  3408. uint64 NumVSites = 0, total_size;
  3409. uint32 VKI;
  3410. /* When dynamic allocation is enabled, allow tracking the max number of
  3411. values allowed. */
  3412. if (!hasNonDefaultValsPerSite)
  3413. VPMaxNumValsPerSite = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
  3414. for (VKI = IPVK_First; VKI <= IPVK_Last; ++VKI)
  3415. NumVSites += Data->num_value_sites[VKI];
  3416. /* If NumVSites = 0, calloc is allowed to return a non-null pointer. */
  3417. bh_assert(NumVSites > 0 && "NumVSites can't be zero");
  3418. total_size = (uint64)sizeof(ValueProfNode *) * NumVSites;
  3419. if (total_size > UINT32_MAX
  3420. || !(Mem = (ValueProfNode **)wasm_runtime_malloc((uint32)total_size))) {
  3421. return 0;
  3422. }
  3423. memset(Mem, 0, (uint32)total_size);
  3424. if (!cmpxchg_ptr((void **)&Data->values, NULL, Mem)) {
  3425. wasm_runtime_free(Mem);
  3426. return 0;
  3427. }
  3428. return 1;
  3429. }
  3430. static ValueProfNode *
  3431. allocateOneNode(void)
  3432. {
  3433. ValueProfNode *Node;
  3434. Node = wasm_runtime_malloc((uint32)sizeof(ValueProfNode));
  3435. if (Node)
  3436. memset(Node, 0, sizeof(ValueProfNode));
  3437. return Node;
  3438. }
  3439. static void
  3440. instrumentTargetValueImpl(uint64 TargetValue, void *Data, uint32 CounterIndex,
  3441. uint64 CountValue)
  3442. {
  3443. ValueProfNode **ValueCounters;
  3444. ValueProfNode *PrevVNode = NULL, *MinCountVNode = NULL, *CurVNode;
  3445. LLVMProfileData *PData = (LLVMProfileData *)Data;
  3446. uint64 MinCount = UINT64_MAX;
  3447. uint8 VDataCount = 0;
  3448. bool success = false;
  3449. if (!PData)
  3450. return;
  3451. if (!CountValue)
  3452. return;
  3453. if (!PData->values) {
  3454. if (!allocateValueProfileCounters(PData))
  3455. return;
  3456. }
  3457. ValueCounters = (ValueProfNode **)PData->values;
  3458. CurVNode = ValueCounters[CounterIndex];
  3459. while (CurVNode) {
  3460. if (TargetValue == CurVNode->value) {
  3461. CurVNode->count += CountValue;
  3462. return;
  3463. }
  3464. if (CurVNode->count < MinCount) {
  3465. MinCount = CurVNode->count;
  3466. MinCountVNode = CurVNode;
  3467. }
  3468. PrevVNode = CurVNode;
  3469. CurVNode = CurVNode->next;
  3470. ++VDataCount;
  3471. }
  3472. if (VDataCount >= VPMaxNumValsPerSite) {
  3473. if (MinCountVNode->count <= CountValue) {
  3474. CurVNode = MinCountVNode;
  3475. CurVNode->value = TargetValue;
  3476. CurVNode->count = CountValue;
  3477. }
  3478. else
  3479. MinCountVNode->count -= CountValue;
  3480. return;
  3481. }
  3482. CurVNode = allocateOneNode();
  3483. if (!CurVNode)
  3484. return;
  3485. CurVNode->value = TargetValue;
  3486. CurVNode->count += CountValue;
  3487. if (!ValueCounters[CounterIndex]) {
  3488. success =
  3489. cmpxchg_ptr((void **)&ValueCounters[CounterIndex], NULL, CurVNode);
  3490. }
  3491. else if (PrevVNode && !PrevVNode->next) {
  3492. success = cmpxchg_ptr((void **)&PrevVNode->next, 0, CurVNode);
  3493. }
  3494. if (!success) {
  3495. wasm_runtime_free(CurVNode);
  3496. }
  3497. }
  3498. void
  3499. llvm_profile_instrument_target(uint64 target_value, void *data,
  3500. uint32 counter_idx)
  3501. {
  3502. instrumentTargetValueImpl(target_value, data, counter_idx, 1);
  3503. }
  3504. static inline uint32
  3505. popcount64(uint64 u)
  3506. {
  3507. uint32 ret = 0;
  3508. while (u) {
  3509. u = (u & (u - 1));
  3510. ret++;
  3511. }
  3512. return ret;
  3513. }
  3514. static inline uint32
  3515. clz64(uint64 type)
  3516. {
  3517. uint32 num = 0;
  3518. if (type == 0)
  3519. return 64;
  3520. while (!(type & 0x8000000000000000LL)) {
  3521. num++;
  3522. type <<= 1;
  3523. }
  3524. return num;
  3525. }
  3526. /* Map an (observed) memop size value to the representative value of its range.
  3527. For example, 5 -> 5, 22 -> 17, 99 -> 65, 256 -> 256, 1001 -> 513. */
  3528. static uint64
  3529. InstrProfGetRangeRepValue(uint64 Value)
  3530. {
  3531. if (Value <= 8)
  3532. /* The first ranges are individually tracked. Use the value as is. */
  3533. return Value;
  3534. else if (Value >= 513)
  3535. /* The last range is mapped to its lowest value. */
  3536. return 513;
  3537. else if (popcount64(Value) == 1)
  3538. /* If it's a power of two, use it as is. */
  3539. return Value;
  3540. else
  3541. /* Otherwise, take to the previous power of two + 1. */
  3542. return (((uint64)1) << (64 - clz64(Value) - 1)) + 1;
  3543. }
  3544. void
  3545. llvm_profile_instrument_memop(uint64 target_value, void *data,
  3546. uint32 counter_idx)
  3547. {
  3548. uint64 rep_value = InstrProfGetRangeRepValue(target_value);
  3549. instrumentTargetValueImpl(rep_value, data, counter_idx, 1);
  3550. }
  3551. static uint32
  3552. get_pgo_prof_data_size(AOTModuleInstance *module_inst, uint32 *p_num_prof_data,
  3553. uint32 *p_num_prof_counters, uint32 *p_padding_size,
  3554. uint32 *p_prof_counters_size, uint32 *p_prof_names_size,
  3555. uint32 *p_value_counters_size, uint8 **p_prof_names)
  3556. {
  3557. AOTModule *module = (AOTModule *)module_inst->module;
  3558. LLVMProfileData *prof_data;
  3559. uint8 *prof_names = NULL;
  3560. uint32 num_prof_data = 0, num_prof_counters = 0, padding_size, i;
  3561. uint32 prof_counters_size = 0, prof_names_size = 0;
  3562. uint32 total_size, total_size_wo_value_counters;
  3563. for (i = 0; i < module->data_section_count; i++) {
  3564. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  3565. bh_assert(module->data_sections[i].size == sizeof(LLVMProfileData));
  3566. num_prof_data++;
  3567. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  3568. num_prof_counters += prof_data->num_counters;
  3569. }
  3570. else if (!strncmp(module->data_sections[i].name, "__llvm_prf_cnts",
  3571. 15)) {
  3572. prof_counters_size += module->data_sections[i].size;
  3573. }
  3574. else if (!strncmp(module->data_sections[i].name, "__llvm_prf_names",
  3575. 16)) {
  3576. prof_names_size = module->data_sections[i].size;
  3577. prof_names = module->data_sections[i].data;
  3578. }
  3579. }
  3580. if (prof_counters_size != num_prof_counters * sizeof(uint64))
  3581. return 0;
  3582. total_size = sizeof(LLVMProfileRawHeader)
  3583. + num_prof_data * sizeof(LLVMProfileData_64)
  3584. + prof_counters_size + prof_names_size;
  3585. padding_size = sizeof(uint64) - (prof_names_size % sizeof(uint64));
  3586. if (padding_size != sizeof(uint64))
  3587. total_size += padding_size;
  3588. /* Total size excluding value counters */
  3589. total_size_wo_value_counters = total_size;
  3590. for (i = 0; i < module->data_section_count; i++) {
  3591. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  3592. uint32 j, k, num_value_sites, num_value_nodes;
  3593. ValueProfNode **values, *value_node;
  3594. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  3595. values = prof_data->values;
  3596. if (prof_data->num_value_sites[0] > 0
  3597. || prof_data->num_value_sites[1] > 0) {
  3598. /* TotalSize (uint32) and NumValueKinds (uint32) */
  3599. total_size += 8;
  3600. for (j = 0; j < 2; j++) {
  3601. if ((num_value_sites = prof_data->num_value_sites[j]) > 0) {
  3602. /* ValueKind (uint32) and NumValueSites (uint32) */
  3603. total_size += 8;
  3604. /* (Value + Counter) group counts of each value site,
  3605. each count is one byte */
  3606. total_size += align_uint(num_value_sites, 8);
  3607. if (values) {
  3608. for (k = 0; k < num_value_sites; k++) {
  3609. num_value_nodes = 0;
  3610. value_node = *values;
  3611. while (value_node) {
  3612. num_value_nodes++;
  3613. value_node = value_node->next;
  3614. }
  3615. if (num_value_nodes) {
  3616. /* (Value + Counter) groups */
  3617. total_size += num_value_nodes * 8 * 2;
  3618. }
  3619. values++;
  3620. }
  3621. }
  3622. }
  3623. }
  3624. }
  3625. }
  3626. }
  3627. if (p_num_prof_data)
  3628. *p_num_prof_data = num_prof_data;
  3629. if (p_num_prof_counters)
  3630. *p_num_prof_counters = num_prof_counters;
  3631. if (p_padding_size)
  3632. *p_padding_size = padding_size;
  3633. if (p_prof_counters_size)
  3634. *p_prof_counters_size = prof_counters_size;
  3635. if (p_prof_names_size)
  3636. *p_prof_names_size = prof_names_size;
  3637. if (p_value_counters_size)
  3638. *p_value_counters_size = total_size - total_size_wo_value_counters;
  3639. if (p_prof_names)
  3640. *p_prof_names = prof_names;
  3641. return total_size;
  3642. }
  3643. uint32
  3644. aot_get_pgo_prof_data_size(AOTModuleInstance *module_inst)
  3645. {
  3646. return get_pgo_prof_data_size(module_inst, NULL, NULL, NULL, NULL, NULL,
  3647. NULL, NULL);
  3648. }
  3649. static union {
  3650. int a;
  3651. char b;
  3652. } __ue = { .a = 1 };
  3653. #define is_little_endian() (__ue.b == 1)
  3654. uint32
  3655. aot_dump_pgo_prof_data_to_buf(AOTModuleInstance *module_inst, char *buf,
  3656. uint32 len)
  3657. {
  3658. AOTModule *module = (AOTModule *)module_inst->module;
  3659. LLVMProfileRawHeader prof_header = { 0 };
  3660. LLVMProfileData *prof_data;
  3661. uint8 *prof_names = NULL;
  3662. uint32 num_prof_data = 0, num_prof_counters = 0, padding_size, i;
  3663. uint32 prof_counters_size = 0, prof_names_size = 0;
  3664. uint32 value_counters_size = 0, value_counters_size_backup = 0;
  3665. uint32 total_size, size;
  3666. int64 counters_delta, offset_counters;
  3667. total_size = get_pgo_prof_data_size(module_inst, &num_prof_data,
  3668. &num_prof_counters, &padding_size,
  3669. &prof_counters_size, &prof_names_size,
  3670. &value_counters_size, &prof_names);
  3671. if (len < total_size)
  3672. return 0;
  3673. value_counters_size_backup = value_counters_size;
  3674. value_counters_size = 0;
  3675. prof_header.counters_delta = counters_delta =
  3676. sizeof(LLVMProfileData_64) * num_prof_data;
  3677. offset_counters = 0;
  3678. for (i = 0; i < module->data_section_count; i++) {
  3679. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  3680. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  3681. prof_data->offset_counters = counters_delta + offset_counters;
  3682. offset_counters += prof_data->num_counters * sizeof(uint64);
  3683. counters_delta -= sizeof(LLVMProfileData_64);
  3684. }
  3685. }
  3686. prof_header.magic = 0xFF6C70726F667281LL;
  3687. /* Version 8 */
  3688. prof_header.version = 0x0000000000000008LL;
  3689. /* with VARIANT_MASK_IR_PROF (IR Instrumentation) */
  3690. prof_header.version |= 0x1ULL << 56;
  3691. /* with VARIANT_MASK_MEMPROF (Memory Profile) */
  3692. prof_header.version |= 0x1ULL << 62;
  3693. prof_header.num_prof_data = num_prof_data;
  3694. prof_header.num_prof_counters = num_prof_counters;
  3695. prof_header.names_size = prof_names_size;
  3696. prof_header.value_kind_last = 1;
  3697. if (!is_little_endian()) {
  3698. aot_exchange_uint64((uint8 *)&prof_header.magic);
  3699. aot_exchange_uint64((uint8 *)&prof_header.version);
  3700. aot_exchange_uint64((uint8 *)&prof_header.num_prof_data);
  3701. aot_exchange_uint64((uint8 *)&prof_header.num_prof_counters);
  3702. aot_exchange_uint64((uint8 *)&prof_header.names_size);
  3703. aot_exchange_uint64((uint8 *)&prof_header.counters_delta);
  3704. aot_exchange_uint64((uint8 *)&prof_header.value_kind_last);
  3705. }
  3706. size = sizeof(LLVMProfileRawHeader);
  3707. bh_memcpy_s(buf, size, &prof_header, size);
  3708. buf += size;
  3709. for (i = 0; i < module->data_section_count; i++) {
  3710. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  3711. LLVMProfileData_64 *prof_data_64 = (LLVMProfileData_64 *)buf;
  3712. /* Convert LLVMProfileData to LLVMProfileData_64, the pointer width
  3713. in the output file is alawys 8 bytes */
  3714. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  3715. prof_data_64->func_md5 = prof_data->func_md5;
  3716. prof_data_64->func_hash = prof_data->func_hash;
  3717. prof_data_64->offset_counters = prof_data->offset_counters;
  3718. prof_data_64->func_ptr = prof_data->func_ptr;
  3719. prof_data_64->values = (uint64)(uintptr_t)prof_data->values;
  3720. prof_data_64->num_counters = prof_data->num_counters;
  3721. prof_data_64->num_value_sites[0] = prof_data->num_value_sites[0];
  3722. prof_data_64->num_value_sites[1] = prof_data->num_value_sites[1];
  3723. if (!is_little_endian()) {
  3724. aot_exchange_uint64((uint8 *)&prof_data_64->func_hash);
  3725. aot_exchange_uint64((uint8 *)&prof_data_64->offset_counters);
  3726. aot_exchange_uint64((uint8 *)&prof_data_64->offset_counters);
  3727. aot_exchange_uint64((uint8 *)&prof_data_64->func_ptr);
  3728. aot_exchange_uint64((uint8 *)&prof_data_64->values);
  3729. aot_exchange_uint32((uint8 *)&prof_data_64->num_counters);
  3730. aot_exchange_uint16((uint8 *)&prof_data_64->num_value_sites[0]);
  3731. aot_exchange_uint16((uint8 *)&prof_data_64->num_value_sites[1]);
  3732. }
  3733. buf += sizeof(LLVMProfileData_64);
  3734. }
  3735. }
  3736. for (i = 0; i < module->data_section_count; i++) {
  3737. if (!strncmp(module->data_sections[i].name, "__llvm_prf_cnts", 15)) {
  3738. size = module->data_sections[i].size;
  3739. bh_memcpy_s(buf, size, module->data_sections[i].data, size);
  3740. buf += size;
  3741. }
  3742. }
  3743. if (prof_names && prof_names_size > 0) {
  3744. size = prof_names_size;
  3745. bh_memcpy_s(buf, size, prof_names, size);
  3746. buf += size;
  3747. padding_size = sizeof(uint64) - (prof_names_size % sizeof(uint64));
  3748. if (padding_size != sizeof(uint64)) {
  3749. char padding_buf[8] = { 0 };
  3750. bh_memcpy_s(buf, padding_size, padding_buf, padding_size);
  3751. buf += padding_size;
  3752. }
  3753. }
  3754. for (i = 0; i < module->data_section_count; i++) {
  3755. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  3756. uint32 j, k, num_value_sites, num_value_nodes;
  3757. ValueProfNode **values, **values_tmp, *value_node;
  3758. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  3759. values = values_tmp = prof_data->values;
  3760. if (prof_data->num_value_sites[0] > 0
  3761. || prof_data->num_value_sites[1] > 0) {
  3762. uint32 *buf_total_size = (uint32 *)buf;
  3763. buf += 4; /* emit TotalSize later */
  3764. *(uint32 *)buf = (prof_data->num_value_sites[0] > 0
  3765. && prof_data->num_value_sites[1] > 0)
  3766. ? 2
  3767. : 1;
  3768. if (!is_little_endian())
  3769. aot_exchange_uint32((uint8 *)buf);
  3770. buf += 4;
  3771. for (j = 0; j < 2; j++) {
  3772. if ((num_value_sites = prof_data->num_value_sites[j]) > 0) {
  3773. /* ValueKind */
  3774. *(uint32 *)buf = j;
  3775. if (!is_little_endian())
  3776. aot_exchange_uint32((uint8 *)buf);
  3777. buf += 4;
  3778. /* NumValueSites */
  3779. *(uint32 *)buf = num_value_sites;
  3780. if (!is_little_endian())
  3781. aot_exchange_uint32((uint8 *)buf);
  3782. buf += 4;
  3783. for (k = 0; k < num_value_sites; k++) {
  3784. num_value_nodes = 0;
  3785. if (values_tmp) {
  3786. value_node = *values_tmp;
  3787. while (value_node) {
  3788. num_value_nodes++;
  3789. value_node = value_node->next;
  3790. }
  3791. values_tmp++;
  3792. }
  3793. bh_assert(num_value_nodes < 255);
  3794. *(uint8 *)buf++ = (uint8)num_value_nodes;
  3795. }
  3796. if (num_value_sites % 8) {
  3797. buf += 8 - (num_value_sites % 8);
  3798. }
  3799. for (k = 0; k < num_value_sites; k++) {
  3800. if (values) {
  3801. value_node = *values;
  3802. while (value_node) {
  3803. *(uint64 *)buf = value_node->value;
  3804. if (!is_little_endian())
  3805. aot_exchange_uint64((uint8 *)buf);
  3806. buf += 8;
  3807. *(uint64 *)buf = value_node->count;
  3808. if (!is_little_endian())
  3809. aot_exchange_uint64((uint8 *)buf);
  3810. buf += 8;
  3811. value_node = value_node->next;
  3812. }
  3813. values++;
  3814. }
  3815. }
  3816. }
  3817. }
  3818. /* TotalSize */
  3819. *(uint32 *)buf_total_size =
  3820. (uint8 *)buf - (uint8 *)buf_total_size;
  3821. if (!is_little_endian())
  3822. aot_exchange_uint64((uint8 *)buf_total_size);
  3823. value_counters_size += (uint8 *)buf - (uint8 *)buf_total_size;
  3824. }
  3825. }
  3826. }
  3827. bh_assert(value_counters_size == value_counters_size_backup);
  3828. (void)value_counters_size_backup;
  3829. return total_size;
  3830. }
  3831. #endif /* end of WASM_ENABLE_STATIC_PGO != 0 */
  3832. #if WASM_ENABLE_GC != 0
  3833. void *
  3834. aot_create_func_obj(AOTModuleInstance *module_inst, uint32 func_idx,
  3835. bool throw_exce, char *error_buf, uint32 error_buf_size)
  3836. {
  3837. AOTModule *module = (AOTModule *)module_inst->module;
  3838. WASMRttTypeRef rtt_type;
  3839. WASMFuncObjectRef func_obj;
  3840. AOTFuncType *func_type;
  3841. uint32 type_idx;
  3842. if (throw_exce) {
  3843. error_buf = module_inst->cur_exception;
  3844. error_buf_size = sizeof(module_inst->cur_exception);
  3845. }
  3846. if (func_idx >= module->import_func_count + module->func_count) {
  3847. set_error_buf_v(error_buf, error_buf_size, "unknown function %d",
  3848. func_idx);
  3849. return NULL;
  3850. }
  3851. type_idx = module_inst->func_type_indexes[func_idx];
  3852. func_type = (AOTFuncType *)module->types[type_idx];
  3853. if (!(rtt_type = wasm_rtt_type_new((AOTType *)func_type, type_idx,
  3854. module->rtt_types, module->type_count,
  3855. &module->rtt_type_lock))) {
  3856. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  3857. return NULL;
  3858. }
  3859. if (!(func_obj = wasm_func_obj_new_internal(
  3860. ((AOTModuleInstanceExtra *)module_inst->e)->common.gc_heap_handle,
  3861. rtt_type, func_idx))) {
  3862. set_error_buf(error_buf, error_buf_size, "create func object failed");
  3863. return NULL;
  3864. }
  3865. return func_obj;
  3866. }
  3867. bool
  3868. aot_obj_is_instance_of(AOTModuleInstance *module_inst, WASMObjectRef gc_obj,
  3869. uint32 type_index)
  3870. {
  3871. AOTModule *aot_module = (AOTModule *)module_inst->module;
  3872. AOTType **types = aot_module->types;
  3873. uint32 type_count = aot_module->type_count;
  3874. return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count);
  3875. }
  3876. WASMRttTypeRef
  3877. aot_rtt_type_new(AOTModuleInstance *module_inst, uint32 type_index)
  3878. {
  3879. AOTModule *aot_module = (AOTModule *)module_inst->module;
  3880. AOTType *defined_type = aot_module->types[type_index];
  3881. WASMRttType **rtt_types = aot_module->rtt_types;
  3882. uint32 rtt_type_count = aot_module->type_count;
  3883. korp_mutex *rtt_type_lock = &aot_module->rtt_type_lock;
  3884. return wasm_rtt_type_new(defined_type, type_index, rtt_types,
  3885. rtt_type_count, rtt_type_lock);
  3886. }
  3887. bool
  3888. aot_array_init_with_data(AOTModuleInstance *module_inst, uint32 seg_index,
  3889. uint32 data_seg_offset, WASMArrayObjectRef array_obj,
  3890. uint32 elem_size, uint32 array_len)
  3891. {
  3892. AOTModule *aot_module;
  3893. uint8 *data = NULL;
  3894. uint8 *array_elem_base;
  3895. uint64 seg_len = 0;
  3896. uint64 total_size = (int64)elem_size * array_len;
  3897. aot_module = (AOTModule *)module_inst->module;
  3898. seg_len = aot_module->mem_init_data_list[seg_index]->byte_count;
  3899. data = aot_module->mem_init_data_list[seg_index]->bytes;
  3900. if (data_seg_offset >= seg_len || total_size > seg_len - data_seg_offset) {
  3901. aot_set_exception(module_inst, "out of bounds memory access");
  3902. return false;
  3903. }
  3904. array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj);
  3905. bh_memcpy_s(array_elem_base, (uint32)total_size, data + data_seg_offset,
  3906. (uint32)total_size);
  3907. return true;
  3908. }
  3909. static bool
  3910. aot_global_traverse_gc_rootset(AOTModuleInstance *module_inst, void *heap)
  3911. {
  3912. AOTModule *module = (AOTModule *)module_inst->module;
  3913. uint8 *global_data = module_inst->global_data;
  3914. AOTImportGlobal *import_global = module->import_globals;
  3915. AOTGlobal *global = module->globals;
  3916. WASMObjectRef gc_obj;
  3917. uint32 i;
  3918. for (i = 0; i < module->import_global_count; i++, import_global++) {
  3919. if (wasm_is_type_reftype(import_global->type)) {
  3920. gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data);
  3921. if (wasm_obj_is_created_from_heap(gc_obj)) {
  3922. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  3923. return false;
  3924. }
  3925. }
  3926. global_data += import_global->size;
  3927. }
  3928. for (i = 0; i < module->global_count; i++, global++) {
  3929. if (wasm_is_type_reftype(global->type)) {
  3930. gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data);
  3931. if (wasm_obj_is_created_from_heap(gc_obj)) {
  3932. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  3933. return false;
  3934. }
  3935. }
  3936. global_data += global->size;
  3937. }
  3938. return true;
  3939. }
  3940. static bool
  3941. aot_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  3942. {
  3943. AOTTableInstance **tables = (AOTTableInstance **)module_inst->tables;
  3944. AOTTableInstance *table;
  3945. uint32 table_count = module_inst->table_count, i, j;
  3946. WASMObjectRef gc_obj, *table_elems;
  3947. for (i = 0; i < table_count; i++) {
  3948. table = tables[i];
  3949. table_elems = (WASMObjectRef *)table->elems;
  3950. for (j = 0; j < table->cur_size; j++) {
  3951. gc_obj = table_elems[j];
  3952. if (wasm_obj_is_created_from_heap(gc_obj)) {
  3953. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  3954. return false;
  3955. }
  3956. }
  3957. }
  3958. return true;
  3959. }
  3960. static bool
  3961. local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  3962. {
  3963. WASMLocalObjectRef *r;
  3964. WASMObjectRef gc_obj;
  3965. for (r = exec_env->cur_local_object_ref; r; r = r->prev) {
  3966. gc_obj = r->val;
  3967. if (wasm_obj_is_created_from_heap(gc_obj)) {
  3968. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  3969. return false;
  3970. }
  3971. }
  3972. return true;
  3973. }
  3974. static bool
  3975. aot_frame_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  3976. {
  3977. AOTFrame *frame;
  3978. AOTModule *module;
  3979. LocalRefFlag frame_local_flags;
  3980. WASMObjectRef gc_obj;
  3981. uint32 i, local_ref_flag_cell_num;
  3982. module = (AOTModule *)wasm_exec_env_get_module(exec_env);
  3983. frame = (AOTFrame *)wasm_exec_env_get_cur_frame(exec_env);
  3984. for (; frame; frame = frame->prev_frame) {
  3985. /* local ref flags */
  3986. frame_local_flags = module->func_local_ref_flags[frame->func_index];
  3987. local_ref_flag_cell_num = frame_local_flags.local_ref_flag_cell_num;
  3988. for (i = 0; i < local_ref_flag_cell_num; i++) {
  3989. if (frame_local_flags.local_ref_flags[i]) {
  3990. gc_obj = GET_REF_FROM_ADDR(frame->lp + i);
  3991. if (wasm_obj_is_created_from_heap(gc_obj)) {
  3992. if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) {
  3993. return false;
  3994. }
  3995. }
  3996. #if UINTPTR_MAX == UINT64_MAX
  3997. bh_assert(frame_local_flags.local_ref_flags[i + 1]);
  3998. i++;
  3999. #endif
  4000. }
  4001. }
  4002. /* stack ref flags */
  4003. uint8 *frame_ref = frame->frame_ref;
  4004. for (i = local_ref_flag_cell_num; i < (uint32)(frame->sp - frame->lp);
  4005. i++) {
  4006. if (frame_ref[i]) {
  4007. gc_obj = GET_REF_FROM_ADDR(frame->lp + i);
  4008. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4009. if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) {
  4010. return false;
  4011. }
  4012. }
  4013. #if UINTPTR_MAX == UINT64_MAX
  4014. bh_assert(frame_ref[i + 1]);
  4015. i++;
  4016. #endif
  4017. }
  4018. }
  4019. }
  4020. return true;
  4021. }
  4022. bool
  4023. aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  4024. {
  4025. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  4026. bool ret;
  4027. ret = aot_global_traverse_gc_rootset(module_inst, heap);
  4028. if (!ret)
  4029. return ret;
  4030. ret = aot_table_traverse_gc_rootset(module_inst, heap);
  4031. if (!ret)
  4032. return ret;
  4033. ret = local_object_refs_traverse_gc_rootset(exec_env, heap);
  4034. if (!ret)
  4035. return ret;
  4036. ret = aot_frame_traverse_gc_rootset(exec_env, heap);
  4037. if (!ret)
  4038. return ret;
  4039. return true;
  4040. }
  4041. #endif /* end of WASM_ENABLE_GC != 0 */