wasm_runtime.c 162 KB

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