wasm_runtime.c 165 KB

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