aot_runtime.c 162 KB

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