aot_runtime.c 170 KB

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