wasm_runtime.c 162 KB

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