wasm_runtime.c 172 KB

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