aot_runtime.c 163 KB

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