wasm_runtime.c 175 KB

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