wasm_runtime.c 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083
  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. heap_offset = num_bytes_per_page;
  307. num_bytes_per_page += heap_size;
  308. if (num_bytes_per_page < heap_size) {
  309. set_error_buf(error_buf, error_buf_size,
  310. "failed to insert app heap into linear memory, "
  311. "try using `--heap-size=0` option");
  312. return NULL;
  313. }
  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. /**
  1037. * Instantiate globals in a module.
  1038. */
  1039. static WASMGlobalInstance *
  1040. globals_instantiate(WASMModule *module, WASMModuleInstance *module_inst,
  1041. char *error_buf, uint32 error_buf_size)
  1042. {
  1043. WASMImport *import;
  1044. uint32 global_data_offset = 0;
  1045. uint32 i, global_count = module->import_global_count + module->global_count;
  1046. uint64 total_size = sizeof(WASMGlobalInstance) * (uint64)global_count;
  1047. WASMGlobalInstance *globals, *global;
  1048. if (!(globals = runtime_malloc(total_size, error_buf, error_buf_size))) {
  1049. return NULL;
  1050. }
  1051. /* instantiate globals from import section */
  1052. global = globals;
  1053. import = module->import_globals;
  1054. for (i = 0; i < module->import_global_count; i++, import++) {
  1055. WASMGlobalImport *global_import = &import->u.global;
  1056. global->type = global_import->type.val_type;
  1057. global->is_mutable = global_import->type.is_mutable;
  1058. #if WASM_ENABLE_GC != 0
  1059. global->ref_type = global_import->ref_type;
  1060. #endif
  1061. #if WASM_ENABLE_MULTI_MODULE != 0
  1062. if (global_import->import_module) {
  1063. if (!(global->import_module_inst = get_sub_module_inst(
  1064. module_inst, global_import->import_module))) {
  1065. set_error_buf(error_buf, error_buf_size, "unknown global");
  1066. goto fail;
  1067. }
  1068. if (!(global->import_global_inst = wasm_lookup_global(
  1069. global->import_module_inst, global_import->field_name))) {
  1070. set_error_buf(error_buf, error_buf_size, "unknown global");
  1071. goto fail;
  1072. }
  1073. /* The linked global instance has been initialized, we
  1074. just need to copy the value. */
  1075. global->initial_value =
  1076. global_import->import_global_linked->init_expr.u;
  1077. }
  1078. else
  1079. #endif
  1080. {
  1081. /* native globals share their initial_values in one module */
  1082. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  1083. &(global_import->global_data_linked),
  1084. sizeof(WASMValue));
  1085. }
  1086. #if WASM_ENABLE_FAST_JIT != 0
  1087. bh_assert(global_data_offset == global_import->data_offset);
  1088. #endif
  1089. global->data_offset = global_data_offset;
  1090. global_data_offset += wasm_value_type_size(global->type);
  1091. global++;
  1092. }
  1093. /* instantiate globals from global section */
  1094. for (i = 0; i < module->global_count; i++) {
  1095. InitializerExpression *init_expr = &(module->globals[i].init_expr);
  1096. uint8 flag = init_expr->init_expr_type;
  1097. global->type = module->globals[i].type.val_type;
  1098. global->is_mutable = module->globals[i].type.is_mutable;
  1099. #if WASM_ENABLE_FAST_JIT != 0
  1100. bh_assert(global_data_offset == module->globals[i].data_offset);
  1101. #endif
  1102. global->data_offset = global_data_offset;
  1103. global_data_offset += wasm_value_type_size(global->type);
  1104. #if WASM_ENABLE_GC != 0
  1105. global->ref_type = module->globals[i].ref_type;
  1106. #endif
  1107. switch (flag) {
  1108. case INIT_EXPR_TYPE_GET_GLOBAL:
  1109. {
  1110. if (!check_global_init_expr(module, init_expr->u.global_index,
  1111. error_buf, error_buf_size)) {
  1112. goto fail;
  1113. }
  1114. bh_memcpy_s(
  1115. &(global->initial_value), sizeof(WASMValue),
  1116. &(globals[init_expr->u.global_index].initial_value),
  1117. sizeof(globals[init_expr->u.global_index].initial_value));
  1118. break;
  1119. }
  1120. #if WASM_ENABLE_GC != 0
  1121. case INIT_EXPR_TYPE_STRUCT_NEW:
  1122. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  1123. {
  1124. WASMStructObjectRef struct_obj;
  1125. WASMStructNewInitValues *init_values = NULL;
  1126. uint32 type_idx;
  1127. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  1128. init_values = (WASMStructNewInitValues *)init_expr->u.data;
  1129. type_idx = init_values->type_idx;
  1130. }
  1131. else {
  1132. type_idx = init_expr->u.type_index;
  1133. }
  1134. struct_obj = instantiate_struct_global_recursive(
  1135. module, module_inst, type_idx, flag, init_values, error_buf,
  1136. error_buf_size);
  1137. if (!struct_obj) {
  1138. goto fail;
  1139. }
  1140. global->initial_value.gc_obj = (void *)struct_obj;
  1141. break;
  1142. }
  1143. case INIT_EXPR_TYPE_ARRAY_NEW:
  1144. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  1145. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  1146. {
  1147. WASMArrayObjectRef array_obj;
  1148. WASMArrayNewInitValues *init_values = NULL;
  1149. WASMValue *array_init_value = NULL, empty_value = { 0 };
  1150. uint32 type_idx, len;
  1151. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  1152. type_idx = init_expr->u.array_new_default.type_index;
  1153. len = init_expr->u.array_new_default.length;
  1154. array_init_value = &empty_value;
  1155. }
  1156. else {
  1157. init_values = (WASMArrayNewInitValues *)init_expr->u.data;
  1158. type_idx = init_values->type_idx;
  1159. len = init_values->length;
  1160. if (flag == INIT_EXPR_TYPE_ARRAY_NEW) {
  1161. array_init_value = init_values->elem_data;
  1162. }
  1163. }
  1164. array_obj = instantiate_array_global_recursive(
  1165. module, module_inst, type_idx, flag, len, array_init_value,
  1166. init_values, error_buf, error_buf_size);
  1167. global->initial_value.gc_obj = (void *)array_obj;
  1168. break;
  1169. }
  1170. case INIT_EXPR_TYPE_I31_NEW:
  1171. {
  1172. global->initial_value.gc_obj =
  1173. (wasm_obj_t)wasm_i31_obj_new(init_expr->u.i32);
  1174. break;
  1175. }
  1176. #endif /* end of WASM_ENABLE_GC != 0 */
  1177. default:
  1178. bh_memcpy_s(&(global->initial_value), sizeof(WASMValue),
  1179. &(init_expr->u), sizeof(init_expr->u));
  1180. break;
  1181. }
  1182. global++;
  1183. }
  1184. bh_assert((uint32)(global - globals) == global_count);
  1185. bh_assert(global_data_offset == module->global_data_size);
  1186. (void)module_inst;
  1187. return globals;
  1188. fail:
  1189. wasm_runtime_free(globals);
  1190. return NULL;
  1191. }
  1192. /**
  1193. * Return export function count in module export section.
  1194. */
  1195. static uint32
  1196. get_export_count(const WASMModule *module, uint8 kind)
  1197. {
  1198. WASMExport *export = module->exports;
  1199. uint32 count = 0, i;
  1200. for (i = 0; i < module->export_count; i++, export ++)
  1201. if (export->kind == kind)
  1202. count++;
  1203. return count;
  1204. }
  1205. /**
  1206. * Destroy export function instances.
  1207. */
  1208. static void
  1209. export_functions_deinstantiate(WASMExportFuncInstance *functions)
  1210. {
  1211. if (functions)
  1212. wasm_runtime_free(functions);
  1213. }
  1214. static int
  1215. cmp_export_func_inst(const void *a, const void *b)
  1216. {
  1217. const WASMExportFuncInstance *export_func1 =
  1218. (const WASMExportFuncInstance *)a;
  1219. const WASMExportFuncInstance *export_func2 =
  1220. (const WASMExportFuncInstance *)b;
  1221. return strcmp(export_func1->name, export_func2->name);
  1222. }
  1223. /**
  1224. * Instantiate export functions in a module.
  1225. */
  1226. static WASMExportFuncInstance *
  1227. export_functions_instantiate(const WASMModule *module,
  1228. WASMModuleInstance *module_inst,
  1229. uint32 export_func_count, char *error_buf,
  1230. uint32 error_buf_size)
  1231. {
  1232. WASMExportFuncInstance *export_funcs, *export_func;
  1233. WASMExport *export = module->exports;
  1234. uint32 i;
  1235. uint64 total_size =
  1236. sizeof(WASMExportFuncInstance) * (uint64)export_func_count;
  1237. if (!(export_func = export_funcs =
  1238. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1239. return NULL;
  1240. }
  1241. for (i = 0; i < module->export_count; i++, export ++)
  1242. if (export->kind == EXPORT_KIND_FUNC) {
  1243. export_func->name = export->name;
  1244. export_func->function = &module_inst->e->functions[export->index];
  1245. export_func++;
  1246. }
  1247. bh_assert((uint32)(export_func - export_funcs) == export_func_count);
  1248. qsort(export_funcs, export_func_count, sizeof(WASMExportFuncInstance),
  1249. cmp_export_func_inst);
  1250. return export_funcs;
  1251. }
  1252. #if WASM_ENABLE_TAGS != 0
  1253. /**
  1254. * Destroy export function instances.
  1255. */
  1256. static void
  1257. export_tags_deinstantiate(WASMExportTagInstance *tags)
  1258. {
  1259. if (tags)
  1260. wasm_runtime_free(tags);
  1261. }
  1262. /**
  1263. * Instantiate export functions in a module.
  1264. */
  1265. static WASMExportTagInstance *
  1266. export_tags_instantiate(const WASMModule *module,
  1267. WASMModuleInstance *module_inst,
  1268. uint32 export_tag_count, char *error_buf,
  1269. uint32 error_buf_size)
  1270. {
  1271. WASMExportTagInstance *export_tags, *export_tag;
  1272. WASMExport *export = module->exports;
  1273. uint32 i;
  1274. uint64 total_size =
  1275. sizeof(WASMExportTagInstance) * (uint64)export_tag_count;
  1276. if (!(export_tag = export_tags =
  1277. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1278. return NULL;
  1279. }
  1280. for (i = 0; i < module->export_count; i++, export ++)
  1281. if (export->kind == EXPORT_KIND_TAG) {
  1282. export_tag->name = export->name;
  1283. bh_assert(module_inst->e->tags);
  1284. export_tag->tag = &module_inst->e->tags[export->index];
  1285. export_tag++;
  1286. }
  1287. bh_assert((uint32)(export_tag - export_tags) == export_tag_count);
  1288. return export_tags;
  1289. }
  1290. #endif /* end of WASM_ENABLE_TAGS != 0 */
  1291. #if WASM_ENABLE_MULTI_MEMORY != 0
  1292. static void
  1293. export_memories_deinstantiate(WASMExportMemInstance *memories)
  1294. {
  1295. if (memories)
  1296. wasm_runtime_free(memories);
  1297. }
  1298. static WASMExportMemInstance *
  1299. export_memories_instantiate(const WASMModule *module,
  1300. WASMModuleInstance *module_inst,
  1301. uint32 export_mem_count, char *error_buf,
  1302. uint32 error_buf_size)
  1303. {
  1304. WASMExportMemInstance *export_memories, *export_memory;
  1305. WASMExport *export = module->exports;
  1306. uint32 i;
  1307. uint64 total_size =
  1308. sizeof(WASMExportMemInstance) * (uint64)export_mem_count;
  1309. if (!(export_memory = export_memories =
  1310. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1311. return NULL;
  1312. }
  1313. for (i = 0; i < module->export_count; i++, export ++)
  1314. if (export->kind == EXPORT_KIND_MEMORY) {
  1315. export_memory->name = export->name;
  1316. export_memory->memory = module_inst->memories[export->index];
  1317. export_memory++;
  1318. }
  1319. bh_assert((uint32)(export_memory - export_memories) == export_mem_count);
  1320. return export_memories;
  1321. }
  1322. #endif /* end of if WASM_ENABLE_MULTI_MEMORY != 0 */
  1323. #if WASM_ENABLE_MULTI_MODULE != 0
  1324. static void
  1325. export_globals_deinstantiate(WASMExportGlobInstance *globals)
  1326. {
  1327. if (globals)
  1328. wasm_runtime_free(globals);
  1329. }
  1330. static WASMExportGlobInstance *
  1331. export_globals_instantiate(const WASMModule *module,
  1332. WASMModuleInstance *module_inst,
  1333. uint32 export_glob_count, char *error_buf,
  1334. uint32 error_buf_size)
  1335. {
  1336. WASMExportGlobInstance *export_globals, *export_global;
  1337. WASMExport *export = module->exports;
  1338. uint32 i;
  1339. uint64 total_size =
  1340. sizeof(WASMExportGlobInstance) * (uint64)export_glob_count;
  1341. if (!(export_global = export_globals =
  1342. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1343. return NULL;
  1344. }
  1345. for (i = 0; i < module->export_count; i++, export ++)
  1346. if (export->kind == EXPORT_KIND_GLOBAL) {
  1347. export_global->name = export->name;
  1348. export_global->global = &module_inst->e->globals[export->index];
  1349. export_global++;
  1350. }
  1351. bh_assert((uint32)(export_global - export_globals) == export_glob_count);
  1352. return export_globals;
  1353. }
  1354. #endif /* end of if WASM_ENABLE_MULTI_MODULE != 0 */
  1355. static WASMFunctionInstance *
  1356. lookup_post_instantiate_func(WASMModuleInstance *module_inst,
  1357. const char *func_name)
  1358. {
  1359. WASMFunctionInstance *func;
  1360. WASMFuncType *func_type;
  1361. if (!(func = wasm_lookup_function(module_inst, func_name)))
  1362. /* Not found */
  1363. return NULL;
  1364. func_type = func->u.func->func_type;
  1365. if (!(func_type->param_count == 0 && func_type->result_count == 0))
  1366. /* Not a valid function type, ignore it */
  1367. return NULL;
  1368. return func;
  1369. }
  1370. static bool
  1371. execute_post_instantiate_functions(WASMModuleInstance *module_inst,
  1372. bool is_sub_inst, WASMExecEnv *exec_env_main)
  1373. {
  1374. WASMFunctionInstance *start_func = module_inst->e->start_function;
  1375. WASMFunctionInstance *initialize_func = NULL;
  1376. WASMFunctionInstance *post_inst_func = NULL;
  1377. WASMFunctionInstance *call_ctors_func = NULL;
  1378. #if WASM_ENABLE_LIBC_WASI != 0
  1379. WASMModule *module = module_inst->module;
  1380. #endif
  1381. WASMModuleInstanceCommon *module_inst_main = NULL;
  1382. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1383. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1384. #endif
  1385. WASMExecEnv *exec_env = NULL, *exec_env_created = NULL;
  1386. bool ret = false;
  1387. #if WASM_ENABLE_LIBC_WASI != 0
  1388. /*
  1389. * WASI reactor instances may assume that _initialize will be called by
  1390. * the environment at most once, and that none of their other exports
  1391. * are accessed before that call.
  1392. */
  1393. if (!is_sub_inst && module->import_wasi_api) {
  1394. initialize_func =
  1395. lookup_post_instantiate_func(module_inst, "_initialize");
  1396. }
  1397. #endif
  1398. /* Execute possible "__post_instantiate" function if wasm app is
  1399. compiled by emsdk's early version */
  1400. if (!is_sub_inst) {
  1401. post_inst_func =
  1402. lookup_post_instantiate_func(module_inst, "__post_instantiate");
  1403. }
  1404. #if WASM_ENABLE_BULK_MEMORY != 0
  1405. /* Only execute the memory init function for main instance since
  1406. the data segments will be dropped once initialized */
  1407. if (!is_sub_inst
  1408. #if WASM_ENABLE_LIBC_WASI != 0
  1409. && !module->import_wasi_api
  1410. #endif
  1411. ) {
  1412. call_ctors_func =
  1413. lookup_post_instantiate_func(module_inst, "__wasm_call_ctors");
  1414. }
  1415. #endif
  1416. if (!start_func && !initialize_func && !post_inst_func
  1417. && !call_ctors_func) {
  1418. /* No post instantiation functions to call */
  1419. return true;
  1420. }
  1421. if (is_sub_inst) {
  1422. bh_assert(exec_env_main);
  1423. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1424. /* May come from pthread_create_wrapper, thread_spawn_wrapper and
  1425. wasm_cluster_spawn_exec_env. If it comes from the former two,
  1426. the exec_env_tls must be not NULL and equal to exec_env_main,
  1427. else if it comes from the last one, it may be NULL. */
  1428. if (exec_env_tls)
  1429. bh_assert(exec_env_tls == exec_env_main);
  1430. #endif
  1431. exec_env = exec_env_main;
  1432. /* Temporarily replace parent exec_env's module inst to current
  1433. module inst to avoid checking failure when calling the
  1434. wasm functions, and ensure that the exec_env's module inst
  1435. is the correct one. */
  1436. module_inst_main = exec_env_main->module_inst;
  1437. wasm_exec_env_set_module_inst(exec_env,
  1438. (WASMModuleInstanceCommon *)module_inst);
  1439. }
  1440. else {
  1441. /* Try using the existing exec_env */
  1442. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1443. exec_env = exec_env_tls;
  1444. #endif
  1445. #if WASM_ENABLE_THREAD_MGR != 0
  1446. if (!exec_env)
  1447. exec_env = wasm_clusters_search_exec_env(
  1448. (WASMModuleInstanceCommon *)module_inst);
  1449. #endif
  1450. if (!exec_env) {
  1451. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1452. (WASMModuleInstanceCommon *)module_inst,
  1453. module_inst->default_wasm_stack_size))) {
  1454. wasm_set_exception(module_inst, "allocate memory failed");
  1455. return false;
  1456. }
  1457. }
  1458. else {
  1459. /* Temporarily replace exec_env's module inst with current
  1460. module inst to ensure that the exec_env's module inst
  1461. is the correct one. */
  1462. module_inst_main = exec_env->module_inst;
  1463. wasm_exec_env_set_module_inst(
  1464. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1465. }
  1466. }
  1467. /* Execute start function for both main instance and sub instance */
  1468. if (start_func && !wasm_call_function(exec_env, start_func, 0, NULL)) {
  1469. goto fail;
  1470. }
  1471. #if WASM_ENABLE_LIBC_WASI != 0
  1472. if (initialize_func
  1473. && !wasm_call_function(exec_env, initialize_func, 0, NULL)) {
  1474. goto fail;
  1475. }
  1476. #else
  1477. (void)initialize_func;
  1478. #endif
  1479. if (post_inst_func
  1480. && !wasm_call_function(exec_env, post_inst_func, 0, NULL)) {
  1481. goto fail;
  1482. }
  1483. if (call_ctors_func
  1484. && !wasm_call_function(exec_env, call_ctors_func, 0, NULL)) {
  1485. goto fail;
  1486. }
  1487. ret = true;
  1488. fail:
  1489. if (is_sub_inst) {
  1490. /* Restore the parent exec_env's module inst */
  1491. wasm_exec_env_restore_module_inst(exec_env_main, module_inst_main);
  1492. }
  1493. else {
  1494. if (module_inst_main)
  1495. /* Restore the existing exec_env's module inst */
  1496. wasm_exec_env_restore_module_inst(exec_env, module_inst_main);
  1497. if (exec_env_created)
  1498. wasm_exec_env_destroy(exec_env_created);
  1499. }
  1500. return ret;
  1501. }
  1502. static bool
  1503. execute_malloc_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1504. WASMFunctionInstance *malloc_func,
  1505. WASMFunctionInstance *retain_func, uint64 size,
  1506. uint64 *p_result)
  1507. {
  1508. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1509. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1510. #endif
  1511. WASMExecEnv *exec_env_created = NULL;
  1512. WASMModuleInstanceCommon *module_inst_old = NULL;
  1513. union {
  1514. uint32 u32[3];
  1515. uint64 u64;
  1516. } argv;
  1517. uint32 argc;
  1518. bool ret;
  1519. #if WASM_ENABLE_MEMORY64 != 0
  1520. bool is_memory64 = module_inst->memories[0]->is_memory64;
  1521. if (is_memory64) {
  1522. argc = 2;
  1523. PUT_I64_TO_ADDR(&argv.u64, size);
  1524. }
  1525. else
  1526. #endif
  1527. {
  1528. argc = 1;
  1529. argv.u32[0] = (uint32)size;
  1530. }
  1531. /* if __retain is exported, then this module is compiled by
  1532. assemblyscript, the memory should be managed by as's runtime,
  1533. in this case we need to call the retain function after malloc
  1534. the memory */
  1535. if (retain_func) {
  1536. /* the malloc function from assemblyscript is:
  1537. function __new(size: usize, id: u32)
  1538. id = 0 means this is an ArrayBuffer object */
  1539. argv.u32[argc] = 0;
  1540. argc++;
  1541. }
  1542. if (exec_env) {
  1543. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1544. if (exec_env_tls) {
  1545. bh_assert(exec_env_tls == exec_env);
  1546. }
  1547. #endif
  1548. bh_assert(exec_env->module_inst
  1549. == (WASMModuleInstanceCommon *)module_inst);
  1550. }
  1551. else {
  1552. /* Try using the existing exec_env */
  1553. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1554. exec_env = exec_env_tls;
  1555. #endif
  1556. #if WASM_ENABLE_THREAD_MGR != 0
  1557. if (!exec_env)
  1558. exec_env = wasm_clusters_search_exec_env(
  1559. (WASMModuleInstanceCommon *)module_inst);
  1560. #endif
  1561. if (!exec_env) {
  1562. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1563. (WASMModuleInstanceCommon *)module_inst,
  1564. module_inst->default_wasm_stack_size))) {
  1565. wasm_set_exception(module_inst, "allocate memory failed");
  1566. return false;
  1567. }
  1568. }
  1569. else {
  1570. /* Temporarily replace exec_env's module inst with current
  1571. module inst to ensure that the exec_env's module inst
  1572. is the correct one. */
  1573. module_inst_old = exec_env->module_inst;
  1574. wasm_exec_env_set_module_inst(
  1575. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1576. }
  1577. }
  1578. ret = wasm_call_function(exec_env, malloc_func, argc, argv.u32);
  1579. if (retain_func && ret)
  1580. ret = wasm_call_function(exec_env, retain_func, 1, argv.u32);
  1581. if (module_inst_old)
  1582. /* Restore the existing exec_env's module inst */
  1583. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  1584. if (exec_env_created)
  1585. wasm_exec_env_destroy(exec_env_created);
  1586. if (ret) {
  1587. #if WASM_ENABLE_MEMORY64 != 0
  1588. if (is_memory64)
  1589. *p_result = argv.u64;
  1590. else
  1591. #endif
  1592. {
  1593. *p_result = argv.u32[0];
  1594. }
  1595. }
  1596. return ret;
  1597. }
  1598. static bool
  1599. execute_free_function(WASMModuleInstance *module_inst, WASMExecEnv *exec_env,
  1600. WASMFunctionInstance *free_func, uint64 offset)
  1601. {
  1602. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1603. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  1604. #endif
  1605. WASMExecEnv *exec_env_created = NULL;
  1606. WASMModuleInstanceCommon *module_inst_old = NULL;
  1607. union {
  1608. uint32 u32[2];
  1609. uint64 u64;
  1610. } argv;
  1611. uint32 argc;
  1612. bool ret;
  1613. #if WASM_ENABLE_MEMORY64 != 0
  1614. if (module_inst->memories[0]->is_memory64) {
  1615. PUT_I64_TO_ADDR(&argv.u64, offset);
  1616. argc = 2;
  1617. }
  1618. else
  1619. #endif
  1620. {
  1621. argv.u32[0] = (uint32)offset;
  1622. argc = 1;
  1623. }
  1624. if (exec_env) {
  1625. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1626. if (exec_env_tls) {
  1627. bh_assert(exec_env_tls == exec_env);
  1628. }
  1629. #endif
  1630. bh_assert(exec_env->module_inst
  1631. == (WASMModuleInstanceCommon *)module_inst);
  1632. }
  1633. else {
  1634. /* Try using the existing exec_env */
  1635. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1636. exec_env = exec_env_tls;
  1637. #endif
  1638. #if WASM_ENABLE_THREAD_MGR != 0
  1639. if (!exec_env)
  1640. exec_env = wasm_clusters_search_exec_env(
  1641. (WASMModuleInstanceCommon *)module_inst);
  1642. #endif
  1643. if (!exec_env) {
  1644. if (!(exec_env = exec_env_created = wasm_exec_env_create(
  1645. (WASMModuleInstanceCommon *)module_inst,
  1646. module_inst->default_wasm_stack_size))) {
  1647. wasm_set_exception(module_inst, "allocate memory failed");
  1648. return false;
  1649. }
  1650. }
  1651. else {
  1652. /* Temporarily replace exec_env's module inst with current
  1653. module inst to ensure that the exec_env's module inst
  1654. is the correct one. */
  1655. module_inst_old = exec_env->module_inst;
  1656. wasm_exec_env_set_module_inst(
  1657. exec_env, (WASMModuleInstanceCommon *)module_inst);
  1658. }
  1659. }
  1660. ret = wasm_call_function(exec_env, free_func, argc, argv.u32);
  1661. if (module_inst_old)
  1662. /* Restore the existing exec_env's module inst */
  1663. wasm_exec_env_restore_module_inst(exec_env, module_inst_old);
  1664. if (exec_env_created)
  1665. wasm_exec_env_destroy(exec_env_created);
  1666. return ret;
  1667. }
  1668. static bool
  1669. check_linked_symbol(WASMModuleInstance *module_inst, char *error_buf,
  1670. uint32 error_buf_size)
  1671. {
  1672. WASMModule *module = module_inst->module;
  1673. uint32 i;
  1674. for (i = 0; i < module->import_function_count; i++) {
  1675. WASMFunctionImport *func =
  1676. &((module->import_functions + i)->u.function);
  1677. if (!func->func_ptr_linked
  1678. #if WASM_ENABLE_MULTI_MODULE != 0
  1679. && !func->import_func_linked
  1680. #endif
  1681. ) {
  1682. LOG_WARNING("warning: failed to link import function (%s, %s)",
  1683. func->module_name, func->field_name);
  1684. }
  1685. }
  1686. for (i = 0; i < module->import_global_count; i++) {
  1687. WASMGlobalImport *global = &((module->import_globals + i)->u.global);
  1688. if (!global->is_linked) {
  1689. #if WASM_ENABLE_SPEC_TEST != 0
  1690. set_error_buf(error_buf, error_buf_size,
  1691. "unknown import or incompatible import type");
  1692. return false;
  1693. #else
  1694. set_error_buf_v(error_buf, error_buf_size,
  1695. "failed to link import global (%s, %s)",
  1696. global->module_name, global->field_name);
  1697. return false;
  1698. #endif /* WASM_ENABLE_SPEC_TEST != 0 */
  1699. }
  1700. }
  1701. for (i = 0; i < module->import_table_count; i++) {
  1702. WASMTableImport *table = &((module->import_tables + i)->u.table);
  1703. if (!wasm_runtime_is_built_in_module(table->module_name)
  1704. #if WASM_ENABLE_MULTI_MODULE != 0
  1705. && !table->import_table_linked
  1706. #endif
  1707. ) {
  1708. set_error_buf_v(error_buf, error_buf_size,
  1709. "failed to link import table (%s, %s)",
  1710. table->module_name, table->field_name);
  1711. return false;
  1712. }
  1713. }
  1714. for (i = 0; i < module->import_memory_count; i++) {
  1715. WASMMemoryImport *memory = &((module->import_memories + i)->u.memory);
  1716. if (!wasm_runtime_is_built_in_module(memory->module_name)
  1717. #if WASM_ENABLE_MULTI_MODULE != 0
  1718. && !memory->import_memory_linked
  1719. #endif
  1720. ) {
  1721. set_error_buf_v(error_buf, error_buf_size,
  1722. "failed to link import memory (%s, %s)",
  1723. memory->module_name, memory->field_name);
  1724. return false;
  1725. }
  1726. }
  1727. #if WASM_ENABLE_MULTI_MODULE != 0
  1728. #if WASM_ENABLE_TAGS != 0
  1729. for (i = 0; i < module->import_tag_count; i++) {
  1730. WASMTagImport *tag = &((module->import_tags + i)->u.tag);
  1731. if (!tag->import_tag_linked) {
  1732. set_error_buf_v(error_buf, error_buf_size,
  1733. "failed to link import tag (%s, %s)",
  1734. tag->module_name, tag->field_name);
  1735. return false;
  1736. }
  1737. }
  1738. #endif /* WASM_ENABLE_TAGS != 0 */
  1739. #endif
  1740. return true;
  1741. }
  1742. #if WASM_ENABLE_JIT != 0
  1743. static bool
  1744. init_func_ptrs(WASMModuleInstance *module_inst, WASMModule *module,
  1745. char *error_buf, uint32 error_buf_size)
  1746. {
  1747. uint32 i;
  1748. void **func_ptrs;
  1749. uint64 total_size = (uint64)sizeof(void *) * module_inst->e->function_count;
  1750. /* Allocate memory */
  1751. if (!(func_ptrs = module_inst->func_ptrs =
  1752. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1753. return false;
  1754. }
  1755. /* Set import function pointers */
  1756. for (i = 0; i < module->import_function_count; i++, func_ptrs++) {
  1757. WASMFunctionImport *import_func =
  1758. &module->import_functions[i].u.function;
  1759. /* TODO: handle multi module */
  1760. *func_ptrs = import_func->func_ptr_linked;
  1761. }
  1762. /* The defined function pointers will be set in
  1763. wasm_runtime_set_running_mode, no need to set them here */
  1764. return true;
  1765. }
  1766. #endif /* end of WASM_ENABLE_JIT != 0 */
  1767. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  1768. static uint32
  1769. get_smallest_type_idx(WASMModule *module, WASMFuncType *func_type)
  1770. {
  1771. uint32 i;
  1772. for (i = 0; i < module->type_count; i++) {
  1773. if (func_type == (WASMFuncType *)module->types[i])
  1774. return i;
  1775. }
  1776. bh_assert(0);
  1777. return -1;
  1778. }
  1779. static bool
  1780. init_func_type_indexes(WASMModuleInstance *module_inst, char *error_buf,
  1781. uint32 error_buf_size)
  1782. {
  1783. uint32 i;
  1784. uint64 total_size = (uint64)sizeof(uint32) * module_inst->e->function_count;
  1785. /* Allocate memory */
  1786. if (!(module_inst->func_type_indexes =
  1787. runtime_malloc(total_size, error_buf, error_buf_size))) {
  1788. return false;
  1789. }
  1790. for (i = 0; i < module_inst->e->function_count; i++) {
  1791. WASMFunctionInstance *func_inst = module_inst->e->functions + i;
  1792. WASMFuncType *func_type = func_inst->is_import_func
  1793. ? func_inst->u.func_import->func_type
  1794. : func_inst->u.func->func_type;
  1795. module_inst->func_type_indexes[i] =
  1796. get_smallest_type_idx(module_inst->module, func_type);
  1797. }
  1798. return true;
  1799. }
  1800. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 */
  1801. #if WASM_ENABLE_GC != 0
  1802. void *
  1803. wasm_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx,
  1804. bool throw_exce, char *error_buf, uint32 error_buf_size)
  1805. {
  1806. WASMModule *module = module_inst->module;
  1807. WASMRttTypeRef rtt_type;
  1808. WASMFuncObjectRef func_obj;
  1809. WASMFuncType *func_type;
  1810. uint32 type_idx;
  1811. if (throw_exce) {
  1812. error_buf = module_inst->cur_exception;
  1813. error_buf_size = sizeof(module_inst->cur_exception);
  1814. }
  1815. if (func_idx >= module->import_function_count + module->function_count) {
  1816. set_error_buf_v(error_buf, error_buf_size, "unknown function %d",
  1817. func_idx);
  1818. return NULL;
  1819. }
  1820. if (func_idx < module->import_function_count) {
  1821. func_type = module->import_functions[func_idx].u.function.func_type;
  1822. type_idx = module->import_functions[func_idx].u.function.type_idx;
  1823. }
  1824. else {
  1825. func_type = module->functions[func_idx - module->import_function_count]
  1826. ->func_type;
  1827. type_idx = module->functions[func_idx - module->import_function_count]
  1828. ->type_idx;
  1829. }
  1830. if (!(rtt_type = wasm_rtt_type_new((WASMType *)func_type, type_idx,
  1831. module->rtt_types, module->type_count,
  1832. &module->rtt_type_lock))) {
  1833. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  1834. return NULL;
  1835. }
  1836. if (!(func_obj = wasm_func_obj_new_internal(
  1837. module_inst->e->common.gc_heap_handle, rtt_type, func_idx))) {
  1838. set_error_buf(error_buf, error_buf_size, "create func object failed");
  1839. return NULL;
  1840. }
  1841. return func_obj;
  1842. }
  1843. static bool
  1844. wasm_global_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1845. {
  1846. WASMGlobalInstance *global = module_inst->e->globals;
  1847. WASMGlobalInstance *global_end = global + module_inst->e->global_count;
  1848. uint8 *global_data = module_inst->global_data;
  1849. WASMObjectRef gc_obj;
  1850. while (global < global_end) {
  1851. if (wasm_is_type_reftype(global->type)) {
  1852. gc_obj = GET_REF_FROM_ADDR(
  1853. (uint32 *)(global_data + global->data_offset));
  1854. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1855. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1856. return false;
  1857. }
  1858. }
  1859. global++;
  1860. }
  1861. return true;
  1862. }
  1863. static bool
  1864. wasm_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  1865. {
  1866. WASMTableInstance **tables = module_inst->tables, *table;
  1867. uint32 table_count = module_inst->table_count, i, j;
  1868. WASMObjectRef gc_obj, *table_elems;
  1869. for (i = 0; i < table_count; i++) {
  1870. table = tables[i];
  1871. table_elems = (WASMObjectRef *)table->elems;
  1872. for (j = 0; j < table->cur_size; j++) {
  1873. gc_obj = table_elems[j];
  1874. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1875. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1876. return false;
  1877. }
  1878. }
  1879. }
  1880. return true;
  1881. }
  1882. static bool
  1883. local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1884. {
  1885. WASMLocalObjectRef *r;
  1886. WASMObjectRef gc_obj;
  1887. for (r = exec_env->cur_local_object_ref; r; r = r->prev) {
  1888. gc_obj = r->val;
  1889. if (wasm_obj_is_created_from_heap(gc_obj)) {
  1890. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  1891. return false;
  1892. }
  1893. }
  1894. return true;
  1895. }
  1896. bool
  1897. wasm_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  1898. {
  1899. WASMModuleInstance *module_inst =
  1900. (WASMModuleInstance *)exec_env->module_inst;
  1901. bool ret;
  1902. ret = wasm_global_traverse_gc_rootset(module_inst, heap);
  1903. if (!ret)
  1904. return ret;
  1905. ret = wasm_table_traverse_gc_rootset(module_inst, heap);
  1906. if (!ret)
  1907. return ret;
  1908. ret = local_object_refs_traverse_gc_rootset(exec_env, heap);
  1909. if (!ret)
  1910. return ret;
  1911. return wasm_interp_traverse_gc_rootset(exec_env, heap);
  1912. }
  1913. #endif /* end of WASM_ENABLE_GC != 0 */
  1914. static bool
  1915. set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode,
  1916. bool first_time_set)
  1917. {
  1918. WASMModule *module = module_inst->module;
  1919. if (running_mode == Mode_Default) {
  1920. #if WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT == 0
  1921. running_mode = Mode_Interp;
  1922. #elif WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT == 0
  1923. running_mode = Mode_Fast_JIT;
  1924. #elif WASM_ENABLE_FAST_JIT == 0 && WASM_ENABLE_JIT != 0
  1925. running_mode = Mode_LLVM_JIT;
  1926. #else /* WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 */
  1927. #if WASM_ENABLE_LAZY_JIT == 0
  1928. running_mode = Mode_LLVM_JIT;
  1929. #else
  1930. running_mode = Mode_Multi_Tier_JIT;
  1931. #endif
  1932. #endif
  1933. }
  1934. if (!wasm_runtime_is_running_mode_supported(running_mode))
  1935. return false;
  1936. #if !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  1937. && WASM_ENABLE_LAZY_JIT != 0) /* No possible multi-tier JIT */
  1938. (void)first_time_set;
  1939. module_inst->e->running_mode = running_mode;
  1940. if (running_mode == Mode_Interp) {
  1941. /* Do nothing for Mode_Interp */
  1942. }
  1943. else if (running_mode == Mode_Fast_JIT) {
  1944. /* Do nothing for Mode_Fast_JIT since
  1945. module_inst->fast_jit_func_ptrs is same as
  1946. module->fast_jit_func_ptrs */
  1947. }
  1948. #if WASM_ENABLE_JIT != 0
  1949. else if (running_mode == Mode_LLVM_JIT) {
  1950. /* Set defined function pointers */
  1951. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  1952. sizeof(void *) * module->function_count, module->func_ptrs,
  1953. sizeof(void *) * module->function_count);
  1954. }
  1955. #endif
  1956. else {
  1957. bh_assert(0);
  1958. }
  1959. #else /* Possible multi-tier JIT */
  1960. os_mutex_lock(&module->instance_list_lock);
  1961. module_inst->e->running_mode = running_mode;
  1962. if (running_mode == Mode_Interp) {
  1963. /* Do nothing for Mode_Interp */
  1964. }
  1965. #if WASM_ENABLE_FAST_JIT != 0
  1966. else if (running_mode == Mode_Fast_JIT) {
  1967. JitGlobals *jit_globals = jit_compiler_get_jit_globals();
  1968. uint32 i;
  1969. /* Allocate memory for fast_jit_func_ptrs if needed */
  1970. if (!module_inst->fast_jit_func_ptrs
  1971. || module_inst->fast_jit_func_ptrs == module->fast_jit_func_ptrs) {
  1972. uint64 total_size = (uint64)sizeof(void *) * module->function_count;
  1973. if (!(module_inst->fast_jit_func_ptrs =
  1974. runtime_malloc(total_size, NULL, 0))) {
  1975. os_mutex_unlock(&module->instance_list_lock);
  1976. return false;
  1977. }
  1978. }
  1979. for (i = 0; i < module->function_count; i++) {
  1980. if (module->functions[i]->fast_jit_jitted_code) {
  1981. /* current fast jit function has been compiled */
  1982. module_inst->fast_jit_func_ptrs[i] =
  1983. module->functions[i]->fast_jit_jitted_code;
  1984. }
  1985. else {
  1986. module_inst->fast_jit_func_ptrs[i] =
  1987. jit_globals->compile_fast_jit_and_then_call;
  1988. }
  1989. }
  1990. }
  1991. #endif
  1992. #if WASM_ENABLE_JIT != 0
  1993. else if (running_mode == Mode_LLVM_JIT) {
  1994. void **llvm_jit_func_ptrs;
  1995. uint32 i;
  1996. /* Notify backend threads to start llvm jit compilation */
  1997. module->enable_llvm_jit_compilation = true;
  1998. /* Wait until llvm jit finishes initialization */
  1999. os_mutex_lock(&module->tierup_wait_lock);
  2000. while (!module->llvm_jit_inited) {
  2001. os_cond_reltimedwait(&module->tierup_wait_cond,
  2002. &module->tierup_wait_lock, 10000);
  2003. if (module->orcjit_stop_compiling) {
  2004. /* init_llvm_jit_functions_stage2 failed */
  2005. os_mutex_unlock(&module->tierup_wait_lock);
  2006. os_mutex_unlock(&module->instance_list_lock);
  2007. return false;
  2008. }
  2009. }
  2010. os_mutex_unlock(&module->tierup_wait_lock);
  2011. llvm_jit_func_ptrs =
  2012. module_inst->func_ptrs + module->import_function_count;
  2013. for (i = 0; i < module->function_count; i++) {
  2014. llvm_jit_func_ptrs[i] = module->functions[i]->llvm_jit_func_ptr;
  2015. }
  2016. }
  2017. #endif
  2018. else if (running_mode == Mode_Multi_Tier_JIT) {
  2019. /* Notify backend threads to start llvm jit compilation */
  2020. module->enable_llvm_jit_compilation = true;
  2021. /* Free fast_jit_func_ptrs if it is allocated before */
  2022. if (module_inst->fast_jit_func_ptrs
  2023. && module_inst->fast_jit_func_ptrs != module->fast_jit_func_ptrs) {
  2024. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  2025. }
  2026. module_inst->fast_jit_func_ptrs = module->fast_jit_func_ptrs;
  2027. /* Copy all llvm jit func ptrs from the module */
  2028. bh_memcpy_s(module_inst->func_ptrs + module->import_function_count,
  2029. sizeof(void *) * module->function_count, module->func_ptrs,
  2030. sizeof(void *) * module->function_count);
  2031. }
  2032. else {
  2033. bh_assert(0);
  2034. }
  2035. /* Add module instance into module's instance list if not added */
  2036. if (first_time_set) {
  2037. bool found = false;
  2038. WASMModuleInstance *node = module->instance_list;
  2039. while (node) {
  2040. if (node == module_inst) {
  2041. found = true;
  2042. break;
  2043. }
  2044. node = node->e->next;
  2045. }
  2046. if (!found) {
  2047. module_inst->e->next = module->instance_list;
  2048. module->instance_list = module_inst;
  2049. }
  2050. }
  2051. os_mutex_unlock(&module->instance_list_lock);
  2052. #endif /* end of !(WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2053. && WASM_ENABLE_LAZY_JIT != 0) */
  2054. (void)module;
  2055. return true;
  2056. }
  2057. bool
  2058. wasm_set_running_mode(WASMModuleInstance *module_inst, RunningMode running_mode)
  2059. {
  2060. return set_running_mode(module_inst, running_mode, false);
  2061. }
  2062. /**
  2063. * Instantiate module
  2064. */
  2065. WASMModuleInstance *
  2066. wasm_instantiate(WASMModule *module, WASMModuleInstance *parent,
  2067. WASMExecEnv *exec_env_main, uint32 stack_size,
  2068. uint32 heap_size, uint32 max_memory_pages, char *error_buf,
  2069. uint32 error_buf_size)
  2070. {
  2071. WASMModuleInstance *module_inst;
  2072. WASMGlobalInstance *globals = NULL, *global;
  2073. WASMTableInstance *first_table;
  2074. uint32 global_count, i;
  2075. uint32 length, extra_info_offset;
  2076. mem_offset_t base_offset;
  2077. uint32 module_inst_struct_size =
  2078. offsetof(WASMModuleInstance, global_table_data.bytes);
  2079. uint64 module_inst_mem_inst_size;
  2080. uint64 total_size, table_size = 0;
  2081. uint8 *global_data, *global_data_end;
  2082. #if WASM_ENABLE_MULTI_MODULE != 0
  2083. bool ret = false;
  2084. #endif
  2085. const bool is_sub_inst = parent != NULL;
  2086. if (!module)
  2087. return NULL;
  2088. /* Check the heap size */
  2089. heap_size = align_uint(heap_size, 8);
  2090. if (heap_size > APP_HEAP_SIZE_MAX)
  2091. heap_size = APP_HEAP_SIZE_MAX;
  2092. module_inst_mem_inst_size =
  2093. sizeof(WASMMemoryInstance)
  2094. * ((uint64)module->import_memory_count + module->memory_count);
  2095. #if WASM_ENABLE_JIT != 0
  2096. /* If the module doesn't have memory, reserve one mem_info space
  2097. with empty content to align with llvm jit compiler */
  2098. if (module_inst_mem_inst_size == 0)
  2099. module_inst_mem_inst_size = (uint64)sizeof(WASMMemoryInstance);
  2100. #endif
  2101. /* Size of module inst, memory instances and global data */
  2102. total_size = (uint64)module_inst_struct_size + module_inst_mem_inst_size
  2103. + module->global_data_size;
  2104. /* Calculate the size of table data */
  2105. for (i = 0; i < module->import_table_count; i++) {
  2106. WASMTableImport *import_table = &module->import_tables[i].u.table;
  2107. table_size += offsetof(WASMTableInstance, elems);
  2108. #if WASM_ENABLE_MULTI_MODULE != 0
  2109. table_size += (uint64)sizeof(table_elem_type_t)
  2110. * import_table->table_type.max_size;
  2111. #else
  2112. table_size += (uint64)sizeof(table_elem_type_t)
  2113. * (import_table->table_type.possible_grow
  2114. ? import_table->table_type.max_size
  2115. : import_table->table_type.init_size);
  2116. #endif
  2117. }
  2118. for (i = 0; i < module->table_count; i++) {
  2119. WASMTable *table = module->tables + i;
  2120. table_size += offsetof(WASMTableInstance, elems);
  2121. #if WASM_ENABLE_MULTI_MODULE != 0
  2122. table_size +=
  2123. (uint64)sizeof(table_elem_type_t) * table->table_type.max_size;
  2124. #else
  2125. table_size +=
  2126. (uint64)sizeof(table_elem_type_t)
  2127. * (table->table_type.possible_grow ? table->table_type.max_size
  2128. : table->table_type.init_size);
  2129. #endif
  2130. }
  2131. total_size += table_size;
  2132. /* The offset of WASMModuleInstanceExtra, make it 8-byte aligned */
  2133. total_size = (total_size + 7LL) & ~7LL;
  2134. extra_info_offset = (uint32)total_size;
  2135. total_size += sizeof(WASMModuleInstanceExtra);
  2136. /* Allocate the memory for module instance with memory instances,
  2137. global data, table data appended at the end */
  2138. if (!(module_inst =
  2139. runtime_malloc(total_size, error_buf, error_buf_size))) {
  2140. return NULL;
  2141. }
  2142. module_inst->module_type = Wasm_Module_Bytecode;
  2143. module_inst->module = module;
  2144. module_inst->e =
  2145. (WASMModuleInstanceExtra *)((uint8 *)module_inst + extra_info_offset);
  2146. #if WASM_ENABLE_MULTI_MODULE != 0
  2147. module_inst->e->sub_module_inst_list =
  2148. &module_inst->e->sub_module_inst_list_head;
  2149. ret = wasm_runtime_sub_module_instantiate(
  2150. (WASMModuleCommon *)module, (WASMModuleInstanceCommon *)module_inst,
  2151. stack_size, heap_size, max_memory_pages, error_buf, error_buf_size);
  2152. if (!ret) {
  2153. LOG_DEBUG("build a sub module list failed");
  2154. goto fail;
  2155. }
  2156. #endif
  2157. #if WASM_ENABLE_BULK_MEMORY != 0
  2158. if (module->data_seg_count > 0) {
  2159. module_inst->e->common.data_dropped =
  2160. bh_bitmap_new(0, module->data_seg_count);
  2161. if (module_inst->e->common.data_dropped == NULL) {
  2162. LOG_DEBUG("failed to allocate bitmaps");
  2163. set_error_buf(error_buf, error_buf_size,
  2164. "failed to allocate bitmaps");
  2165. goto fail;
  2166. }
  2167. for (i = 0; i < module->data_seg_count; i++) {
  2168. if (!module->data_segments[i]->is_passive)
  2169. bh_bitmap_set_bit(module_inst->e->common.data_dropped, i);
  2170. }
  2171. }
  2172. #endif
  2173. #if WASM_ENABLE_REF_TYPES != 0
  2174. if (module->table_seg_count > 0) {
  2175. module_inst->e->common.elem_dropped =
  2176. bh_bitmap_new(0, module->table_seg_count);
  2177. if (module_inst->e->common.elem_dropped == NULL) {
  2178. LOG_DEBUG("failed to allocate bitmaps");
  2179. set_error_buf(error_buf, error_buf_size,
  2180. "failed to allocate bitmaps");
  2181. goto fail;
  2182. }
  2183. for (i = 0; i < module->table_seg_count; i++) {
  2184. if (wasm_elem_is_active(module->table_segments[i].mode)
  2185. || wasm_elem_is_declarative(module->table_segments[i].mode))
  2186. bh_bitmap_set_bit(module_inst->e->common.elem_dropped, i);
  2187. }
  2188. }
  2189. #endif
  2190. #if WASM_ENABLE_GC != 0
  2191. if (!is_sub_inst) {
  2192. uint32 gc_heap_size = wasm_runtime_get_gc_heap_size_default();
  2193. if (gc_heap_size < GC_HEAP_SIZE_MIN)
  2194. gc_heap_size = GC_HEAP_SIZE_MIN;
  2195. if (gc_heap_size > GC_HEAP_SIZE_MAX)
  2196. gc_heap_size = GC_HEAP_SIZE_MAX;
  2197. module_inst->e->common.gc_heap_pool =
  2198. runtime_malloc(gc_heap_size, error_buf, error_buf_size);
  2199. if (!module_inst->e->common.gc_heap_pool)
  2200. goto fail;
  2201. module_inst->e->common.gc_heap_handle = mem_allocator_create(
  2202. module_inst->e->common.gc_heap_pool, gc_heap_size);
  2203. if (!module_inst->e->common.gc_heap_handle)
  2204. goto fail;
  2205. }
  2206. #endif
  2207. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2208. if (!(module_inst->frames = runtime_malloc((uint64)sizeof(Vector),
  2209. error_buf, error_buf_size))) {
  2210. goto fail;
  2211. }
  2212. #endif
  2213. /* Instantiate global firstly to get the mutable data size */
  2214. global_count = module->import_global_count + module->global_count;
  2215. if (global_count
  2216. && !(globals = globals_instantiate(module, module_inst, error_buf,
  2217. error_buf_size))) {
  2218. goto fail;
  2219. }
  2220. module_inst->e->global_count = global_count;
  2221. module_inst->e->globals = globals;
  2222. module_inst->global_data = (uint8 *)module_inst + module_inst_struct_size
  2223. + module_inst_mem_inst_size;
  2224. module_inst->global_data_size = module->global_data_size;
  2225. first_table = (WASMTableInstance *)(module_inst->global_data
  2226. + module->global_data_size);
  2227. module_inst->memory_count =
  2228. module->import_memory_count + module->memory_count;
  2229. module_inst->table_count = module->import_table_count + module->table_count;
  2230. module_inst->e->function_count =
  2231. module->import_function_count + module->function_count;
  2232. #if WASM_ENABLE_TAGS != 0
  2233. module_inst->e->tag_count = module->import_tag_count + module->tag_count;
  2234. #endif
  2235. /* export */
  2236. module_inst->export_func_count = get_export_count(module, EXPORT_KIND_FUNC);
  2237. #if WASM_ENABLE_MULTI_MEMORY != 0
  2238. module_inst->export_memory_count =
  2239. get_export_count(module, EXPORT_KIND_MEMORY);
  2240. #endif
  2241. #if WASM_ENABLE_MULTI_MODULE != 0
  2242. module_inst->export_table_count =
  2243. get_export_count(module, EXPORT_KIND_TABLE);
  2244. #if WASM_ENABLE_TAGS != 0
  2245. module_inst->e->export_tag_count =
  2246. get_export_count(module, EXPORT_KIND_TAG);
  2247. #endif
  2248. module_inst->export_global_count =
  2249. get_export_count(module, EXPORT_KIND_GLOBAL);
  2250. #endif
  2251. /* Instantiate memories/tables/functions/tags */
  2252. if ((module_inst->memory_count > 0
  2253. && !(module_inst->memories = memories_instantiate(
  2254. module, module_inst, parent, heap_size, max_memory_pages,
  2255. error_buf, error_buf_size)))
  2256. || (module_inst->table_count > 0
  2257. && !(module_inst->tables =
  2258. tables_instantiate(module, module_inst, first_table,
  2259. error_buf, error_buf_size)))
  2260. || (module_inst->e->function_count > 0
  2261. && !(module_inst->e->functions = functions_instantiate(
  2262. module, module_inst, error_buf, error_buf_size)))
  2263. || (module_inst->export_func_count > 0
  2264. && !(module_inst->export_functions = export_functions_instantiate(
  2265. module, module_inst, module_inst->export_func_count,
  2266. error_buf, error_buf_size)))
  2267. #if WASM_ENABLE_TAGS != 0
  2268. || (module_inst->e->tag_count > 0
  2269. && !(module_inst->e->tags = tags_instantiate(
  2270. module, module_inst, error_buf, error_buf_size)))
  2271. || (module_inst->e->export_tag_count > 0
  2272. && !(module_inst->e->export_tags = export_tags_instantiate(
  2273. module, module_inst, module_inst->e->export_tag_count,
  2274. error_buf, error_buf_size)))
  2275. #endif
  2276. #if WASM_ENABLE_MULTI_MODULE != 0
  2277. || (module_inst->export_global_count > 0
  2278. && !(module_inst->export_globals = export_globals_instantiate(
  2279. module, module_inst, module_inst->export_global_count,
  2280. error_buf, error_buf_size)))
  2281. #endif
  2282. #if WASM_ENABLE_MULTI_MEMORY != 0
  2283. || (module_inst->export_memory_count > 0
  2284. && !(module_inst->export_memories = export_memories_instantiate(
  2285. module, module_inst, module_inst->export_memory_count,
  2286. error_buf, error_buf_size)))
  2287. #endif
  2288. #if WASM_ENABLE_JIT != 0
  2289. || (module_inst->e->function_count > 0
  2290. && !init_func_ptrs(module_inst, module, error_buf, error_buf_size))
  2291. #endif
  2292. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  2293. || (module_inst->e->function_count > 0
  2294. && !init_func_type_indexes(module_inst, error_buf, error_buf_size))
  2295. #endif
  2296. ) {
  2297. goto fail;
  2298. }
  2299. if (global_count > 0) {
  2300. /* Initialize the global data */
  2301. global_data = module_inst->global_data;
  2302. global_data_end = global_data + module->global_data_size;
  2303. global = globals;
  2304. for (i = 0; i < global_count; i++, global++) {
  2305. switch (global->type) {
  2306. case VALUE_TYPE_I32:
  2307. case VALUE_TYPE_F32:
  2308. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  2309. case VALUE_TYPE_FUNCREF:
  2310. case VALUE_TYPE_EXTERNREF:
  2311. #endif
  2312. *(int32 *)global_data = global->initial_value.i32;
  2313. global_data += sizeof(int32);
  2314. break;
  2315. case VALUE_TYPE_I64:
  2316. case VALUE_TYPE_F64:
  2317. bh_memcpy_s(global_data,
  2318. (uint32)(global_data_end - global_data),
  2319. &global->initial_value.i64, sizeof(int64));
  2320. global_data += sizeof(int64);
  2321. break;
  2322. #if WASM_ENABLE_SIMD != 0
  2323. case VALUE_TYPE_V128:
  2324. bh_memcpy_s(global_data, (uint32)sizeof(V128),
  2325. &global->initial_value.v128, sizeof(V128));
  2326. global_data += sizeof(V128);
  2327. break;
  2328. #endif
  2329. #if WASM_ENABLE_GC != 0
  2330. case VALUE_TYPE_EXTERNREF:
  2331. /* the initial value should be a null reference */
  2332. bh_assert(global->initial_value.gc_obj == NULL_REF);
  2333. STORE_PTR((void **)global_data, NULL_REF);
  2334. global_data += sizeof(void *);
  2335. break;
  2336. #endif
  2337. default:
  2338. {
  2339. #if WASM_ENABLE_GC != 0
  2340. InitializerExpression *global_init = NULL;
  2341. bh_assert(wasm_is_type_reftype(global->type));
  2342. if (i >= module->import_global_count) {
  2343. global_init =
  2344. &module->globals[i - module->import_global_count]
  2345. .init_expr;
  2346. }
  2347. if (global->type == REF_TYPE_NULLFUNCREF
  2348. || global->type == REF_TYPE_NULLEXTERNREF
  2349. || global->type == REF_TYPE_NULLREF) {
  2350. STORE_PTR((void **)global_data, NULL_REF);
  2351. global_data += sizeof(void *);
  2352. break;
  2353. }
  2354. /* We can't create funcref obj during global instantiation
  2355. * since the functions are not instantiated yet, so we need
  2356. * to defer the initialization here */
  2357. if (global_init
  2358. && (global_init->init_expr_type
  2359. == INIT_EXPR_TYPE_FUNCREF_CONST)
  2360. && wasm_reftype_is_subtype_of(
  2361. global->type, global->ref_type, REF_TYPE_FUNCREF,
  2362. NULL, module_inst->module->types,
  2363. module_inst->module->type_count)) {
  2364. WASMFuncObjectRef func_obj = NULL;
  2365. /* UINT32_MAX indicates that it is a null reference */
  2366. if ((uint32)global->initial_value.i32 != UINT32_MAX) {
  2367. if (!(func_obj = wasm_create_func_obj(
  2368. module_inst, global->initial_value.i32,
  2369. false, error_buf, error_buf_size)))
  2370. goto fail;
  2371. }
  2372. STORE_PTR((void **)global_data, func_obj);
  2373. global_data += sizeof(void *);
  2374. /* Also update the inital_value since other globals may
  2375. * refer to this */
  2376. global->initial_value.gc_obj = (wasm_obj_t)func_obj;
  2377. break;
  2378. }
  2379. else {
  2380. STORE_PTR((void **)global_data,
  2381. global->initial_value.gc_obj);
  2382. global_data += sizeof(void *);
  2383. break;
  2384. }
  2385. #endif
  2386. bh_assert(0);
  2387. break;
  2388. }
  2389. }
  2390. }
  2391. bh_assert(global_data == global_data_end);
  2392. }
  2393. if (!check_linked_symbol(module_inst, error_buf, error_buf_size)) {
  2394. goto fail;
  2395. }
  2396. /* Initialize the memory data with data segment section */
  2397. for (i = 0; i < module->data_seg_count; i++) {
  2398. WASMMemoryInstance *memory = NULL;
  2399. uint8 *memory_data = NULL;
  2400. uint64 memory_size = 0;
  2401. WASMDataSeg *data_seg = module->data_segments[i];
  2402. #if WASM_ENABLE_BULK_MEMORY != 0
  2403. if (data_seg->is_passive)
  2404. continue;
  2405. #endif
  2406. if (is_sub_inst)
  2407. /* Ignore setting memory init data if the memory has been
  2408. initialized */
  2409. continue;
  2410. /* has check it in loader */
  2411. memory = module_inst->memories[data_seg->memory_index];
  2412. bh_assert(memory);
  2413. memory_data = memory->memory_data;
  2414. memory_size =
  2415. (uint64)memory->num_bytes_per_page * memory->cur_page_count;
  2416. bh_assert(memory_data || memory_size == 0);
  2417. bh_assert(data_seg->base_offset.init_expr_type
  2418. == INIT_EXPR_TYPE_GET_GLOBAL
  2419. || data_seg->base_offset.init_expr_type
  2420. == (memory->is_memory64 ? INIT_EXPR_TYPE_I64_CONST
  2421. : INIT_EXPR_TYPE_I32_CONST));
  2422. if (data_seg->base_offset.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  2423. if (!check_global_init_expr(module,
  2424. data_seg->base_offset.u.global_index,
  2425. error_buf, error_buf_size)) {
  2426. goto fail;
  2427. }
  2428. if (!globals
  2429. || globals[data_seg->base_offset.u.global_index].type
  2430. != (memory->is_memory64 ? VALUE_TYPE_I64
  2431. : VALUE_TYPE_I32)) {
  2432. set_error_buf(error_buf, error_buf_size,
  2433. "data segment does not fit");
  2434. goto fail;
  2435. }
  2436. #if WASM_ENABLE_MEMORY64 != 0
  2437. if (memory->is_memory64) {
  2438. base_offset =
  2439. (uint64)globals[data_seg->base_offset.u.global_index]
  2440. .initial_value.i64;
  2441. }
  2442. else
  2443. #endif
  2444. {
  2445. base_offset =
  2446. (uint32)globals[data_seg->base_offset.u.global_index]
  2447. .initial_value.i32;
  2448. }
  2449. }
  2450. else {
  2451. #if WASM_ENABLE_MEMORY64 != 0
  2452. if (memory->is_memory64) {
  2453. base_offset = (uint64)data_seg->base_offset.u.i64;
  2454. }
  2455. else
  2456. #endif
  2457. {
  2458. base_offset = (uint32)data_seg->base_offset.u.i32;
  2459. }
  2460. }
  2461. /* check offset */
  2462. if (base_offset > memory_size) {
  2463. #if WASM_ENABLE_MEMORY64 != 0
  2464. LOG_DEBUG("base_offset(%" PRIu64 ") > memory_size(%" PRIu64 ")",
  2465. base_offset, memory_size);
  2466. #else
  2467. LOG_DEBUG("base_offset(%u) > memory_size(%" PRIu64 ")", base_offset,
  2468. memory_size);
  2469. #endif
  2470. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2471. set_error_buf(error_buf, error_buf_size,
  2472. "out of bounds memory access");
  2473. #else
  2474. set_error_buf(error_buf, error_buf_size,
  2475. "data segment does not fit");
  2476. #endif
  2477. goto fail;
  2478. }
  2479. /* check offset + length(could be zero) */
  2480. length = data_seg->data_length;
  2481. if ((uint64)base_offset + length > memory_size) {
  2482. #if WASM_ENABLE_MEMORY64 != 0
  2483. LOG_DEBUG("base_offset(%" PRIu64
  2484. ") + length(%d) > memory_size(%" PRIu64 ")",
  2485. base_offset, length, memory_size);
  2486. #else
  2487. LOG_DEBUG("base_offset(%u) + length(%d) > memory_size(%" PRIu64 ")",
  2488. base_offset, length, memory_size);
  2489. #endif
  2490. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2491. set_error_buf(error_buf, error_buf_size,
  2492. "out of bounds memory access");
  2493. #else
  2494. set_error_buf(error_buf, error_buf_size,
  2495. "data segment does not fit");
  2496. #endif
  2497. goto fail;
  2498. }
  2499. if (memory_data) {
  2500. bh_memcpy_s(memory_data + base_offset,
  2501. (uint32)(memory_size - base_offset), data_seg->data,
  2502. length);
  2503. }
  2504. }
  2505. #if WASM_ENABLE_JIT != 0 && WASM_ENABLE_SHARED_HEAP != 0
  2506. #if UINTPTR_MAX == UINT64_MAX
  2507. module_inst->e->shared_heap_start_off.u64 = UINT64_MAX;
  2508. #else
  2509. module_inst->e->shared_heap_start_off.u32[0] = UINT32_MAX;
  2510. #endif
  2511. #endif
  2512. #if WASM_ENABLE_GC != 0
  2513. /* Initialize the table data with init expr */
  2514. for (i = 0; i < module->table_count; i++) {
  2515. WASMTable *table = module->tables + i;
  2516. WASMTableInstance *table_inst = module_inst->tables[i];
  2517. table_elem_type_t *table_data;
  2518. uint32 j;
  2519. if (table->init_expr.init_expr_type == 0) {
  2520. /* No table initializer */
  2521. continue;
  2522. }
  2523. table_data = table_inst->elems;
  2524. bh_assert(
  2525. table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL
  2526. || table->init_expr.init_expr_type == INIT_EXPR_TYPE_FUNCREF_CONST
  2527. || table->init_expr.init_expr_type == INIT_EXPR_TYPE_REFNULL_CONST);
  2528. if (table->init_expr.init_expr_type == INIT_EXPR_TYPE_GET_GLOBAL) {
  2529. if (!check_global_init_expr(module, table->init_expr.u.global_index,
  2530. error_buf, error_buf_size)) {
  2531. goto fail;
  2532. }
  2533. table->init_expr.u.gc_obj =
  2534. globals[table->init_expr.u.global_index].initial_value.gc_obj;
  2535. }
  2536. else if (table->init_expr.init_expr_type
  2537. == INIT_EXPR_TYPE_FUNCREF_CONST) {
  2538. uint32 func_idx = table->init_expr.u.ref_index;
  2539. if (func_idx != UINT32_MAX) {
  2540. if (!(table->init_expr.u.gc_obj =
  2541. wasm_create_func_obj(module_inst, func_idx, false,
  2542. error_buf, error_buf_size)))
  2543. goto fail;
  2544. }
  2545. else {
  2546. table->init_expr.u.gc_obj = NULL_REF;
  2547. }
  2548. }
  2549. else if (table->init_expr.init_expr_type
  2550. == INIT_EXPR_TYPE_REFNULL_CONST) {
  2551. table->init_expr.u.gc_obj = NULL_REF;
  2552. }
  2553. LOG_DEBUG("Init table [%d] elements from [%d] to [%d] as: %p", i, 0,
  2554. table_inst->cur_size, (void *)table->init_expr.u.gc_obj);
  2555. for (j = 0; j < table_inst->cur_size; j++) {
  2556. *(table_data + j) = table->init_expr.u.gc_obj;
  2557. }
  2558. }
  2559. #endif /* end of WASM_ENABLE_GC != 0 */
  2560. /* Initialize the table data with table segment section */
  2561. for (i = 0; module_inst->table_count > 0 && i < module->table_seg_count;
  2562. i++) {
  2563. WASMTableSeg *table_seg = module->table_segments + i;
  2564. /* has check it in loader */
  2565. WASMTableInstance *table = module_inst->tables[table_seg->table_index];
  2566. table_elem_type_t *table_data;
  2567. uint32 j;
  2568. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2569. uint8 tbl_elem_type;
  2570. uint32 tbl_init_size, tbl_max_size;
  2571. #endif
  2572. #if WASM_ENABLE_GC != 0
  2573. WASMRefType *tbl_elem_ref_type;
  2574. #endif
  2575. bh_assert(table);
  2576. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2577. (void)wasm_runtime_get_table_inst_elem_type(
  2578. (WASMModuleInstanceCommon *)module_inst, table_seg->table_index,
  2579. &tbl_elem_type,
  2580. #if WASM_ENABLE_GC != 0
  2581. &tbl_elem_ref_type,
  2582. #endif
  2583. &tbl_init_size, &tbl_max_size);
  2584. #if WASM_ENABLE_GC == 0
  2585. if (tbl_elem_type != VALUE_TYPE_FUNCREF
  2586. && tbl_elem_type != VALUE_TYPE_EXTERNREF) {
  2587. set_error_buf(error_buf, error_buf_size,
  2588. "type mismatch: elements segment does not fit");
  2589. goto fail;
  2590. }
  2591. #elif WASM_ENABLE_GC != 0
  2592. if (!wasm_elem_is_declarative(table_seg->mode)
  2593. && !wasm_reftype_is_subtype_of(
  2594. table_seg->elem_type, table_seg->elem_ref_type,
  2595. table->elem_type, table->elem_ref_type.elem_ref_type,
  2596. module->types, module->type_count)) {
  2597. set_error_buf(error_buf, error_buf_size,
  2598. "type mismatch: elements segment does not fit");
  2599. goto fail;
  2600. }
  2601. #endif
  2602. (void)tbl_init_size;
  2603. (void)tbl_max_size;
  2604. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  2605. table_data = table->elems;
  2606. #if WASM_ENABLE_MULTI_MODULE != 0
  2607. if (table_seg->table_index < module->import_table_count
  2608. && module_inst->e->table_insts_linked[table_seg->table_index]) {
  2609. table_data =
  2610. module_inst->e->table_insts_linked[table_seg->table_index]
  2611. ->elems;
  2612. }
  2613. #endif
  2614. bh_assert(table_data);
  2615. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2616. if (!wasm_elem_is_active(table_seg->mode))
  2617. continue;
  2618. #endif
  2619. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2620. bh_assert(table_seg->base_offset.init_expr_type
  2621. == INIT_EXPR_TYPE_I32_CONST
  2622. || table_seg->base_offset.init_expr_type
  2623. == INIT_EXPR_TYPE_GET_GLOBAL
  2624. || table_seg->base_offset.init_expr_type
  2625. == INIT_EXPR_TYPE_FUNCREF_CONST
  2626. || table_seg->base_offset.init_expr_type
  2627. == INIT_EXPR_TYPE_REFNULL_CONST);
  2628. #else
  2629. bh_assert(table_seg->base_offset.init_expr_type
  2630. == INIT_EXPR_TYPE_I32_CONST
  2631. || table_seg->base_offset.init_expr_type
  2632. == INIT_EXPR_TYPE_GET_GLOBAL);
  2633. #endif
  2634. /* init vec(funcidx) or vec(expr) */
  2635. if (table_seg->base_offset.init_expr_type
  2636. == INIT_EXPR_TYPE_GET_GLOBAL) {
  2637. if (!check_global_init_expr(module,
  2638. table_seg->base_offset.u.global_index,
  2639. error_buf, error_buf_size)) {
  2640. goto fail;
  2641. }
  2642. if (!globals
  2643. || globals[table_seg->base_offset.u.global_index].type
  2644. != VALUE_TYPE_I32) {
  2645. set_error_buf(error_buf, error_buf_size,
  2646. "type mismatch: elements segment does not fit");
  2647. goto fail;
  2648. }
  2649. table_seg->base_offset.u.i32 =
  2650. globals[table_seg->base_offset.u.global_index]
  2651. .initial_value.i32;
  2652. }
  2653. /* check offset since length might negative */
  2654. if ((uint32)table_seg->base_offset.u.i32 > table->cur_size) {
  2655. LOG_DEBUG("base_offset(%d) > table->cur_size(%d)",
  2656. table_seg->base_offset.u.i32, table->cur_size);
  2657. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2658. set_error_buf(error_buf, error_buf_size,
  2659. "out of bounds table access");
  2660. #else
  2661. set_error_buf(error_buf, error_buf_size,
  2662. "type mismatch: elements segment does not fit");
  2663. #endif
  2664. goto fail;
  2665. }
  2666. /* check offset + length(could be zero) */
  2667. length = table_seg->value_count;
  2668. if ((uint32)table_seg->base_offset.u.i32 + length > table->cur_size) {
  2669. LOG_DEBUG("base_offset(%d) + length(%d)> table->cur_size(%d)",
  2670. table_seg->base_offset.u.i32, length, table->cur_size);
  2671. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  2672. set_error_buf(error_buf, error_buf_size,
  2673. "out of bounds table access");
  2674. #else
  2675. set_error_buf(error_buf, error_buf_size,
  2676. "type mismatch: elements segment does not fit");
  2677. #endif
  2678. goto fail;
  2679. }
  2680. for (j = 0; j < length; j++) {
  2681. InitializerExpression *init_expr = &table_seg->init_values[j];
  2682. uint8 flag = init_expr->init_expr_type;
  2683. void *ref = NULL;
  2684. /* const and get global init values should be resolved during
  2685. * loading */
  2686. bh_assert((flag == INIT_EXPR_TYPE_GET_GLOBAL)
  2687. || (flag == INIT_EXPR_TYPE_REFNULL_CONST)
  2688. || ((flag >= INIT_EXPR_TYPE_FUNCREF_CONST)
  2689. && (flag <= INIT_EXPR_TYPE_EXTERN_CONVERT_ANY)));
  2690. switch (flag) {
  2691. case INIT_EXPR_TYPE_REFNULL_CONST:
  2692. ref = NULL;
  2693. break;
  2694. case INIT_EXPR_TYPE_FUNCREF_CONST:
  2695. {
  2696. #if WASM_ENABLE_GC == 0
  2697. ref = (void *)(uintptr_t)init_expr->u.ref_index;
  2698. #else
  2699. WASMFuncObjectRef func_obj;
  2700. uint32 func_idx = init_expr->u.ref_index;
  2701. /* UINT32_MAX indicates that it is a null reference */
  2702. if (func_idx != UINT32_MAX) {
  2703. if (!(func_obj = wasm_create_func_obj(
  2704. module_inst, func_idx, false, error_buf,
  2705. error_buf_size))) {
  2706. goto fail;
  2707. }
  2708. ref = func_obj;
  2709. }
  2710. else {
  2711. ref = NULL_REF;
  2712. }
  2713. #endif /* end of WASM_ENABLE_GC != 0 */
  2714. break;
  2715. }
  2716. #if WASM_ENABLE_GC != 0
  2717. case INIT_EXPR_TYPE_GET_GLOBAL:
  2718. {
  2719. if (!check_global_init_expr(module,
  2720. init_expr->u.global_index,
  2721. error_buf, error_buf_size)) {
  2722. goto fail;
  2723. }
  2724. ref =
  2725. globals[init_expr->u.global_index].initial_value.gc_obj;
  2726. break;
  2727. }
  2728. case INIT_EXPR_TYPE_STRUCT_NEW:
  2729. case INIT_EXPR_TYPE_STRUCT_NEW_DEFAULT:
  2730. {
  2731. WASMRttType *rtt_type;
  2732. WASMStructObjectRef struct_obj;
  2733. WASMStructType *struct_type;
  2734. WASMStructNewInitValues *init_values = NULL;
  2735. uint32 type_idx;
  2736. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  2737. init_values =
  2738. (WASMStructNewInitValues *)init_expr->u.data;
  2739. type_idx = init_values->type_idx;
  2740. }
  2741. else {
  2742. type_idx = init_expr->u.type_index;
  2743. }
  2744. struct_type = (WASMStructType *)module->types[type_idx];
  2745. if (!(rtt_type = wasm_rtt_type_new(
  2746. (WASMType *)struct_type, type_idx,
  2747. module->rtt_types, module->type_count,
  2748. &module->rtt_type_lock))) {
  2749. set_error_buf(error_buf, error_buf_size,
  2750. "create rtt object failed");
  2751. goto fail;
  2752. }
  2753. if (!(struct_obj = wasm_struct_obj_new_internal(
  2754. module_inst->e->common.gc_heap_handle,
  2755. rtt_type))) {
  2756. set_error_buf(error_buf, error_buf_size,
  2757. "create struct object failed");
  2758. goto fail;
  2759. }
  2760. if (flag == INIT_EXPR_TYPE_STRUCT_NEW) {
  2761. uint32 field_idx;
  2762. bh_assert(init_values->count
  2763. == struct_type->field_count);
  2764. for (field_idx = 0; field_idx < init_values->count;
  2765. field_idx++) {
  2766. wasm_struct_obj_set_field(
  2767. struct_obj, field_idx,
  2768. &init_values->fields[field_idx]);
  2769. }
  2770. }
  2771. ref = struct_obj;
  2772. break;
  2773. }
  2774. case INIT_EXPR_TYPE_ARRAY_NEW:
  2775. case INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT:
  2776. case INIT_EXPR_TYPE_ARRAY_NEW_FIXED:
  2777. {
  2778. WASMRttType *rtt_type;
  2779. WASMArrayObjectRef array_obj;
  2780. WASMArrayType *array_type;
  2781. WASMArrayNewInitValues *init_values = NULL;
  2782. WASMValue *arr_init_val = NULL, empty_val = { 0 };
  2783. uint32 type_idx, len;
  2784. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_DEFAULT) {
  2785. type_idx = init_expr->u.array_new_default.type_index;
  2786. len = init_expr->u.array_new_default.length;
  2787. arr_init_val = &empty_val;
  2788. }
  2789. else {
  2790. init_values =
  2791. (WASMArrayNewInitValues *)init_expr->u.data;
  2792. type_idx = init_values->type_idx;
  2793. len = init_values->length;
  2794. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  2795. arr_init_val = init_values->elem_data;
  2796. }
  2797. }
  2798. array_type = (WASMArrayType *)module->types[type_idx];
  2799. if (!(rtt_type = wasm_rtt_type_new(
  2800. (WASMType *)array_type, type_idx,
  2801. module->rtt_types, module->type_count,
  2802. &module->rtt_type_lock))) {
  2803. set_error_buf(error_buf, error_buf_size,
  2804. "create rtt object failed");
  2805. goto fail;
  2806. }
  2807. if (!(array_obj = wasm_array_obj_new_internal(
  2808. module_inst->e->common.gc_heap_handle, rtt_type,
  2809. len, arr_init_val))) {
  2810. set_error_buf(error_buf, error_buf_size,
  2811. "create array object failed");
  2812. goto fail;
  2813. }
  2814. if (flag == INIT_EXPR_TYPE_ARRAY_NEW_FIXED) {
  2815. uint32 elem_idx;
  2816. bh_assert(init_values);
  2817. for (elem_idx = 0; elem_idx < len; elem_idx++) {
  2818. wasm_array_obj_set_elem(
  2819. array_obj, elem_idx,
  2820. &init_values->elem_data[elem_idx]);
  2821. }
  2822. }
  2823. ref = array_obj;
  2824. break;
  2825. }
  2826. case INIT_EXPR_TYPE_I31_NEW:
  2827. {
  2828. ref = (wasm_obj_t)wasm_i31_obj_new(init_expr->u.i32);
  2829. break;
  2830. }
  2831. #endif /* end of WASM_ENABLE_GC != 0 */
  2832. }
  2833. *(table_data + table_seg->base_offset.u.i32 + j) =
  2834. (table_elem_type_t)ref;
  2835. }
  2836. }
  2837. /* Initialize the thread related data */
  2838. if (stack_size == 0)
  2839. stack_size = DEFAULT_WASM_STACK_SIZE;
  2840. module_inst->default_wasm_stack_size = stack_size;
  2841. if (module->malloc_function != (uint32)-1) {
  2842. module_inst->e->malloc_function =
  2843. &module_inst->e->functions[module->malloc_function];
  2844. }
  2845. if (module->free_function != (uint32)-1) {
  2846. module_inst->e->free_function =
  2847. &module_inst->e->functions[module->free_function];
  2848. }
  2849. if (module->retain_function != (uint32)-1) {
  2850. module_inst->e->retain_function =
  2851. &module_inst->e->functions[module->retain_function];
  2852. }
  2853. #if WASM_ENABLE_LIBC_WASI != 0
  2854. /* The sub-instance will get the wasi_ctx from main-instance */
  2855. if (!is_sub_inst) {
  2856. if (!wasm_runtime_init_wasi(
  2857. (WASMModuleInstanceCommon *)module_inst,
  2858. module->wasi_args.dir_list, module->wasi_args.dir_count,
  2859. module->wasi_args.map_dir_list, module->wasi_args.map_dir_count,
  2860. module->wasi_args.env, module->wasi_args.env_count,
  2861. module->wasi_args.addr_pool, module->wasi_args.addr_count,
  2862. module->wasi_args.ns_lookup_pool,
  2863. module->wasi_args.ns_lookup_count, module->wasi_args.argv,
  2864. module->wasi_args.argc, module->wasi_args.stdio[0],
  2865. module->wasi_args.stdio[1], module->wasi_args.stdio[2],
  2866. error_buf, error_buf_size)) {
  2867. goto fail;
  2868. }
  2869. }
  2870. #endif
  2871. #if WASM_ENABLE_DEBUG_INTERP != 0
  2872. if (!is_sub_inst) {
  2873. /* Add module instance into module's instance list */
  2874. os_mutex_lock(&module->instance_list_lock);
  2875. if (module->instance_list) {
  2876. LOG_WARNING(
  2877. "warning: multiple instances referencing to the same module "
  2878. "may cause unexpected behaviour during debugging");
  2879. }
  2880. module_inst->e->next = module->instance_list;
  2881. module->instance_list = module_inst;
  2882. os_mutex_unlock(&module->instance_list_lock);
  2883. }
  2884. #endif
  2885. /* Set running mode before executing wasm functions */
  2886. if (!set_running_mode(module_inst, wasm_runtime_get_default_running_mode(),
  2887. true)) {
  2888. set_error_buf(error_buf, error_buf_size,
  2889. "set instance running mode failed");
  2890. goto fail;
  2891. }
  2892. if (module->start_function != (uint32)-1) {
  2893. /* TODO: fix start function can be import function issue */
  2894. if (module->start_function >= module->import_function_count)
  2895. module_inst->e->start_function =
  2896. &module_inst->e->functions[module->start_function];
  2897. }
  2898. if (!execute_post_instantiate_functions(module_inst, is_sub_inst,
  2899. exec_env_main)) {
  2900. set_error_buf(error_buf, error_buf_size, module_inst->cur_exception);
  2901. goto fail;
  2902. }
  2903. #if WASM_ENABLE_MEMORY_TRACING != 0
  2904. wasm_runtime_dump_module_inst_mem_consumption(
  2905. (WASMModuleInstanceCommon *)module_inst);
  2906. #endif
  2907. (void)global_data_end;
  2908. return module_inst;
  2909. fail:
  2910. wasm_deinstantiate(module_inst, false);
  2911. return NULL;
  2912. }
  2913. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  2914. static void
  2915. destroy_c_api_frames(Vector *frames)
  2916. {
  2917. WASMCApiFrame frame = { 0 };
  2918. uint32 i, total_frames, ret;
  2919. total_frames = (uint32)bh_vector_size(frames);
  2920. for (i = 0; i < total_frames; i++) {
  2921. ret = bh_vector_get(frames, i, &frame);
  2922. bh_assert(ret);
  2923. if (frame.lp)
  2924. wasm_runtime_free(frame.lp);
  2925. }
  2926. ret = bh_vector_destroy(frames);
  2927. bh_assert(ret);
  2928. (void)ret;
  2929. }
  2930. #endif
  2931. void
  2932. wasm_deinstantiate(WASMModuleInstance *module_inst, bool is_sub_inst)
  2933. {
  2934. if (!module_inst)
  2935. return;
  2936. if (module_inst->exec_env_singleton) {
  2937. /* wasm_exec_env_destroy will call
  2938. wasm_cluster_wait_for_all_except_self to wait for other
  2939. threads, so as to destroy their exec_envs and module
  2940. instances first, and avoid accessing the shared resources
  2941. of current module instance after it is deinstantiated. */
  2942. wasm_exec_env_destroy(module_inst->exec_env_singleton);
  2943. }
  2944. #if WASM_ENABLE_DEBUG_INTERP != 0 \
  2945. || (WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2946. && WASM_ENABLE_LAZY_JIT != 0)
  2947. /* Remove instance from module's instance list before freeing
  2948. func_ptrs and fast_jit_func_ptrs of the instance, to avoid
  2949. accessing the freed memory in the jit backend compilation
  2950. threads */
  2951. {
  2952. WASMModule *module = module_inst->module;
  2953. WASMModuleInstance *instance_prev = NULL, *instance;
  2954. os_mutex_lock(&module->instance_list_lock);
  2955. instance = module->instance_list;
  2956. while (instance) {
  2957. if (instance == module_inst) {
  2958. if (!instance_prev)
  2959. module->instance_list = instance->e->next;
  2960. else
  2961. instance_prev->e->next = instance->e->next;
  2962. break;
  2963. }
  2964. instance_prev = instance;
  2965. instance = instance->e->next;
  2966. }
  2967. os_mutex_unlock(&module->instance_list_lock);
  2968. }
  2969. #endif
  2970. #if WASM_ENABLE_JIT != 0
  2971. if (module_inst->func_ptrs)
  2972. wasm_runtime_free(module_inst->func_ptrs);
  2973. #endif
  2974. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  2975. && WASM_ENABLE_LAZY_JIT != 0
  2976. if (module_inst->fast_jit_func_ptrs
  2977. && module_inst->fast_jit_func_ptrs
  2978. != module_inst->module->fast_jit_func_ptrs)
  2979. wasm_runtime_free(module_inst->fast_jit_func_ptrs);
  2980. #endif
  2981. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0
  2982. if (module_inst->func_type_indexes)
  2983. wasm_runtime_free(module_inst->func_type_indexes);
  2984. #endif
  2985. #if WASM_ENABLE_MULTI_MODULE != 0
  2986. wasm_runtime_sub_module_deinstantiate(
  2987. (WASMModuleInstanceCommon *)module_inst);
  2988. #endif
  2989. if (module_inst->memory_count > 0)
  2990. memories_deinstantiate(module_inst, module_inst->memories,
  2991. module_inst->memory_count);
  2992. if (module_inst->import_func_ptrs) {
  2993. wasm_runtime_free(module_inst->import_func_ptrs);
  2994. }
  2995. tables_deinstantiate(module_inst);
  2996. functions_deinstantiate(module_inst->e->functions);
  2997. #if WASM_ENABLE_TAGS != 0
  2998. tags_deinstantiate(module_inst->e->tags, module_inst->e->import_tag_ptrs);
  2999. #endif
  3000. globals_deinstantiate(module_inst->e->globals);
  3001. export_functions_deinstantiate(module_inst->export_functions);
  3002. #if WASM_ENABLE_TAGS != 0
  3003. export_tags_deinstantiate(module_inst->e->export_tags);
  3004. #endif
  3005. #if WASM_ENABLE_MULTI_MODULE != 0
  3006. export_globals_deinstantiate(module_inst->export_globals);
  3007. #endif
  3008. #if WASM_ENABLE_MULTI_MEMORY != 0
  3009. export_memories_deinstantiate(module_inst->export_memories);
  3010. #endif
  3011. #if WASM_ENABLE_GC == 0 && WASM_ENABLE_REF_TYPES != 0
  3012. wasm_externref_cleanup((WASMModuleInstanceCommon *)module_inst);
  3013. #endif
  3014. #if WASM_ENABLE_GC != 0
  3015. if (!is_sub_inst) {
  3016. if (module_inst->e->common.gc_heap_handle)
  3017. mem_allocator_destroy(module_inst->e->common.gc_heap_handle);
  3018. if (module_inst->e->common.gc_heap_pool)
  3019. wasm_runtime_free(module_inst->e->common.gc_heap_pool);
  3020. }
  3021. #endif
  3022. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3023. if (module_inst->frames) {
  3024. destroy_c_api_frames(module_inst->frames);
  3025. wasm_runtime_free(module_inst->frames);
  3026. module_inst->frames = NULL;
  3027. }
  3028. #endif
  3029. if (module_inst->c_api_func_imports)
  3030. wasm_runtime_free(module_inst->c_api_func_imports);
  3031. if (!is_sub_inst) {
  3032. wasm_native_call_context_dtors((WASMModuleInstanceCommon *)module_inst);
  3033. }
  3034. #if WASM_ENABLE_BULK_MEMORY != 0
  3035. bh_bitmap_delete(module_inst->e->common.data_dropped);
  3036. #endif
  3037. #if WASM_ENABLE_REF_TYPES != 0
  3038. bh_bitmap_delete(module_inst->e->common.elem_dropped);
  3039. #endif
  3040. wasm_runtime_free(module_inst);
  3041. }
  3042. WASMFunctionInstance *
  3043. wasm_lookup_function(const WASMModuleInstance *module_inst, const char *name)
  3044. {
  3045. WASMExportFuncInstance key = { .name = (char *)name };
  3046. WASMExportFuncInstance *export_func_inst;
  3047. if (!module_inst->export_functions)
  3048. return NULL;
  3049. export_func_inst = bsearch(
  3050. &key, module_inst->export_functions, module_inst->export_func_count,
  3051. sizeof(WASMExportFuncInstance), cmp_export_func_inst);
  3052. if (!export_func_inst)
  3053. return NULL;
  3054. return export_func_inst->function;
  3055. }
  3056. WASMMemoryInstance *
  3057. wasm_lookup_memory(const WASMModuleInstance *module_inst, const char *name)
  3058. {
  3059. #if WASM_ENABLE_MULTI_MEMORY != 0
  3060. uint32 i;
  3061. for (i = 0; i < module_inst->export_memory_count; i++)
  3062. if (!strcmp(module_inst->export_memories[i].name, name))
  3063. return module_inst->export_memories[i].memory;
  3064. return NULL;
  3065. #else
  3066. (void)module_inst->export_memories;
  3067. if (!module_inst->memories)
  3068. return NULL;
  3069. return module_inst->memories[0];
  3070. #endif
  3071. }
  3072. #if WASM_ENABLE_MULTI_MODULE != 0
  3073. WASMGlobalInstance *
  3074. wasm_lookup_global(const WASMModuleInstance *module_inst, const char *name)
  3075. {
  3076. uint32 i;
  3077. for (i = 0; i < module_inst->export_global_count; i++)
  3078. if (!strcmp(module_inst->export_globals[i].name, name))
  3079. return module_inst->export_globals[i].global;
  3080. return NULL;
  3081. }
  3082. WASMTableInstance *
  3083. wasm_lookup_table(const WASMModuleInstance *module_inst, const char *name)
  3084. {
  3085. /**
  3086. * using a strong assumption that one module instance only has
  3087. * one table instance
  3088. */
  3089. (void)module_inst->export_tables;
  3090. return module_inst->tables[0];
  3091. }
  3092. #if WASM_ENABLE_TAGS != 0
  3093. WASMTagInstance *
  3094. wasm_lookup_tag(const WASMModuleInstance *module_inst, const char *name,
  3095. const char *signature)
  3096. {
  3097. uint32 i;
  3098. for (i = 0; i < module_inst->e->export_tag_count; i++)
  3099. if (!strcmp(module_inst->e->export_tags[i].name, name))
  3100. return module_inst->e->export_tags[i].tag;
  3101. (void)signature;
  3102. return NULL;
  3103. }
  3104. #endif
  3105. #endif
  3106. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3107. static void
  3108. call_wasm_with_hw_bound_check(WASMModuleInstance *module_inst,
  3109. WASMExecEnv *exec_env,
  3110. WASMFunctionInstance *function, unsigned argc,
  3111. uint32 argv[])
  3112. {
  3113. WASMExecEnv *exec_env_tls = wasm_runtime_get_exec_env_tls();
  3114. WASMJmpBuf jmpbuf_node = { 0 }, *jmpbuf_node_pop;
  3115. WASMRuntimeFrame *prev_frame = wasm_exec_env_get_cur_frame(exec_env);
  3116. uint8 *prev_top = exec_env->wasm_stack.top;
  3117. #ifdef BH_PLATFORM_WINDOWS
  3118. int result;
  3119. bool has_exception;
  3120. char exception[EXCEPTION_BUF_LEN];
  3121. #endif
  3122. bool ret = true;
  3123. if (!exec_env_tls) {
  3124. if (!os_thread_signal_inited()) {
  3125. wasm_set_exception(module_inst, "thread signal env not inited");
  3126. return;
  3127. }
  3128. /* Set thread handle and stack boundary if they haven't been set */
  3129. wasm_exec_env_set_thread_info(exec_env);
  3130. wasm_runtime_set_exec_env_tls(exec_env);
  3131. }
  3132. else {
  3133. if (exec_env_tls != exec_env) {
  3134. wasm_set_exception(module_inst, "invalid exec env");
  3135. return;
  3136. }
  3137. }
  3138. /* Check native stack overflow firstly to ensure we have enough
  3139. native stack to run the following codes before actually calling
  3140. the aot function in invokeNative function. */
  3141. if (!wasm_runtime_detect_native_stack_overflow(exec_env)) {
  3142. return;
  3143. }
  3144. wasm_exec_env_push_jmpbuf(exec_env, &jmpbuf_node);
  3145. if (os_setjmp(jmpbuf_node.jmpbuf) == 0) {
  3146. #ifndef BH_PLATFORM_WINDOWS
  3147. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3148. #else
  3149. __try {
  3150. wasm_interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3151. } __except (wasm_copy_exception(module_inst, NULL)
  3152. ? EXCEPTION_EXECUTE_HANDLER
  3153. : EXCEPTION_CONTINUE_SEARCH) {
  3154. /* Exception was thrown in wasm_exception_handler */
  3155. ret = false;
  3156. }
  3157. has_exception = wasm_copy_exception(module_inst, exception);
  3158. if (has_exception && strstr(exception, "native stack overflow")) {
  3159. /* After a stack overflow, the stack was left
  3160. in a damaged state, let the CRT repair it */
  3161. result = _resetstkoflw();
  3162. bh_assert(result != 0);
  3163. }
  3164. #endif
  3165. }
  3166. else {
  3167. /* Exception has been set in signal handler before calling longjmp */
  3168. ret = false;
  3169. }
  3170. /* Note: can't check wasm_get_exception(module_inst) here, there may be
  3171. * exception which is not caught by hardware (e.g. uninitialized elements),
  3172. * then the stack-frame is already freed inside wasm_interp_call_wasm */
  3173. if (!ret) {
  3174. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3175. if (wasm_interp_create_call_stack(exec_env)) {
  3176. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  3177. }
  3178. #endif
  3179. /* Restore operand frames */
  3180. wasm_exec_env_set_cur_frame(exec_env, prev_frame);
  3181. exec_env->wasm_stack.top = prev_top;
  3182. }
  3183. jmpbuf_node_pop = wasm_exec_env_pop_jmpbuf(exec_env);
  3184. bh_assert(&jmpbuf_node == jmpbuf_node_pop);
  3185. if (!exec_env->jmpbuf_stack_top) {
  3186. wasm_runtime_set_exec_env_tls(NULL);
  3187. }
  3188. if (!ret) {
  3189. os_sigreturn();
  3190. os_signal_unmask();
  3191. }
  3192. (void)jmpbuf_node_pop;
  3193. }
  3194. #define interp_call_wasm call_wasm_with_hw_bound_check
  3195. #else
  3196. #define interp_call_wasm wasm_interp_call_wasm
  3197. #endif
  3198. bool
  3199. wasm_call_function(WASMExecEnv *exec_env, WASMFunctionInstance *function,
  3200. unsigned argc, uint32 argv[])
  3201. {
  3202. WASMModuleInstance *module_inst =
  3203. (WASMModuleInstance *)exec_env->module_inst;
  3204. #ifndef OS_ENABLE_HW_BOUND_CHECK
  3205. /* Set thread handle and stack boundary */
  3206. wasm_exec_env_set_thread_info(exec_env);
  3207. #else
  3208. /* Set thread info in call_wasm_with_hw_bound_check when
  3209. hw bound check is enabled */
  3210. #endif
  3211. /* Set exec env, so it can be later retrieved from instance */
  3212. module_inst->cur_exec_env = exec_env;
  3213. interp_call_wasm(module_inst, exec_env, function, argc, argv);
  3214. return !wasm_copy_exception(module_inst, NULL);
  3215. }
  3216. #if WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0
  3217. /* look for the function name */
  3218. static char *
  3219. get_func_name_from_index(const WASMModuleInstance *inst, uint32 func_index)
  3220. {
  3221. char *func_name = NULL;
  3222. WASMFunctionInstance *func_inst = inst->e->functions + func_index;
  3223. if (func_inst->is_import_func) {
  3224. func_name = func_inst->u.func_import->field_name;
  3225. }
  3226. else {
  3227. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  3228. func_name = func_inst->u.func->field_name;
  3229. #endif
  3230. /* if custom name section is not generated,
  3231. search symbols from export table */
  3232. if (!func_name) {
  3233. unsigned j;
  3234. for (j = 0; j < inst->export_func_count; j++) {
  3235. WASMExportFuncInstance *export_func =
  3236. inst->export_functions + j;
  3237. if (export_func->function == func_inst) {
  3238. func_name = export_func->name;
  3239. break;
  3240. }
  3241. }
  3242. }
  3243. }
  3244. return func_name;
  3245. }
  3246. #endif /*WASM_ENABLE_PERF_PROFILING != 0 || WASM_ENABLE_DUMP_CALL_STACK != 0*/
  3247. #if WASM_ENABLE_PERF_PROFILING != 0
  3248. void
  3249. wasm_dump_perf_profiling(const WASMModuleInstance *module_inst)
  3250. {
  3251. WASMFunctionInstance *func_inst;
  3252. char *func_name;
  3253. uint32 i;
  3254. os_printf("Performance profiler data:\n");
  3255. for (i = 0; i < module_inst->e->function_count; i++) {
  3256. func_inst = module_inst->e->functions + i;
  3257. if (func_inst->total_exec_cnt == 0)
  3258. continue;
  3259. func_name = get_func_name_from_index(module_inst, i);
  3260. if (func_name)
  3261. os_printf(
  3262. " func %s, execution time: %.3f ms, execution count: %" PRIu32
  3263. " times, children execution time: %.3f ms\n",
  3264. func_name, func_inst->total_exec_time / 1000.0f,
  3265. func_inst->total_exec_cnt,
  3266. func_inst->children_exec_time / 1000.0f);
  3267. else
  3268. os_printf(" func %" PRIu32
  3269. ", execution time: %.3f ms, execution count: %" PRIu32
  3270. " times, children execution time: %.3f ms\n",
  3271. i, func_inst->total_exec_time / 1000.0f,
  3272. func_inst->total_exec_cnt,
  3273. func_inst->children_exec_time / 1000.0f);
  3274. }
  3275. }
  3276. double
  3277. wasm_summarize_wasm_execute_time(const WASMModuleInstance *inst)
  3278. {
  3279. double ret = 0;
  3280. unsigned i;
  3281. for (i = 0; i < inst->e->function_count; i++) {
  3282. WASMFunctionInstance *func = inst->e->functions + i;
  3283. ret += (func->total_exec_time - func->children_exec_time) / 1000.0f;
  3284. }
  3285. return ret;
  3286. }
  3287. double
  3288. wasm_get_wasm_func_exec_time(const WASMModuleInstance *inst,
  3289. const char *func_name)
  3290. {
  3291. unsigned i;
  3292. for (i = 0; i < inst->e->function_count; i++) {
  3293. char *name_in_wasm = get_func_name_from_index(inst, i);
  3294. if (name_in_wasm && strcmp(name_in_wasm, func_name) == 0) {
  3295. WASMFunctionInstance *func = inst->e->functions + i;
  3296. return (func->total_exec_time - func->children_exec_time) / 1000.0f;
  3297. }
  3298. }
  3299. return -1.0;
  3300. }
  3301. #endif /*WASM_ENABLE_PERF_PROFILING != 0*/
  3302. uint64
  3303. wasm_module_malloc_internal(WASMModuleInstance *module_inst,
  3304. WASMExecEnv *exec_env, uint64 size,
  3305. void **p_native_addr)
  3306. {
  3307. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3308. uint8 *addr = NULL;
  3309. uint64 offset = 0;
  3310. /* TODO: Memory64 size check based on memory idx type */
  3311. bh_assert(size <= UINT32_MAX);
  3312. if (!memory) {
  3313. wasm_set_exception(module_inst, "uninitialized memory");
  3314. return 0;
  3315. }
  3316. if (memory->heap_handle) {
  3317. addr = mem_allocator_malloc(memory->heap_handle, (uint32)size);
  3318. }
  3319. else if (module_inst->e->malloc_function && module_inst->e->free_function) {
  3320. if (!execute_malloc_function(
  3321. module_inst, exec_env, module_inst->e->malloc_function,
  3322. module_inst->e->retain_function, size, &offset)) {
  3323. return 0;
  3324. }
  3325. /* If we use app's malloc function,
  3326. the default memory may be changed while memory growing */
  3327. memory = wasm_get_default_memory(module_inst);
  3328. addr = offset ? memory->memory_data + offset : NULL;
  3329. }
  3330. if (!addr) {
  3331. if (memory->heap_handle
  3332. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  3333. wasm_runtime_show_app_heap_corrupted_prompt();
  3334. wasm_set_exception(module_inst, "app heap corrupted");
  3335. }
  3336. else {
  3337. LOG_WARNING("warning: allocate %" PRIu64 " bytes memory failed",
  3338. size);
  3339. }
  3340. return 0;
  3341. }
  3342. if (p_native_addr)
  3343. *p_native_addr = addr;
  3344. return (uint64)(addr - memory->memory_data);
  3345. }
  3346. uint64
  3347. wasm_module_realloc_internal(WASMModuleInstance *module_inst,
  3348. WASMExecEnv *exec_env, uint64 ptr, uint64 size,
  3349. void **p_native_addr)
  3350. {
  3351. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3352. uint8 *addr = NULL;
  3353. /* TODO: Memory64 ptr and size check based on memory idx type */
  3354. bh_assert(ptr <= UINT32_MAX);
  3355. bh_assert(size <= UINT32_MAX);
  3356. if (!memory) {
  3357. wasm_set_exception(module_inst, "uninitialized memory");
  3358. return 0;
  3359. }
  3360. if (memory->heap_handle) {
  3361. addr = mem_allocator_realloc(
  3362. memory->heap_handle,
  3363. (uint32)ptr ? memory->memory_data + (uint32)ptr : NULL,
  3364. (uint32)size);
  3365. }
  3366. /* Only support realloc in WAMR's app heap */
  3367. (void)exec_env;
  3368. if (!addr) {
  3369. if (memory->heap_handle
  3370. && mem_allocator_is_heap_corrupted(memory->heap_handle)) {
  3371. wasm_set_exception(module_inst, "app heap corrupted");
  3372. }
  3373. else {
  3374. wasm_set_exception(module_inst, "out of memory");
  3375. }
  3376. return 0;
  3377. }
  3378. if (p_native_addr)
  3379. *p_native_addr = addr;
  3380. return (uint64)(addr - memory->memory_data);
  3381. }
  3382. void
  3383. wasm_module_free_internal(WASMModuleInstance *module_inst,
  3384. WASMExecEnv *exec_env, uint64 ptr)
  3385. {
  3386. WASMMemoryInstance *memory = wasm_get_default_memory(module_inst);
  3387. /* TODO: Memory64 ptr and size check based on memory idx type */
  3388. bh_assert(ptr <= UINT32_MAX);
  3389. if (!memory) {
  3390. return;
  3391. }
  3392. if (ptr) {
  3393. uint8 *addr = memory->memory_data + (uint32)ptr;
  3394. uint8 *memory_data_end;
  3395. /* memory->memory_data_end may be changed in memory grow */
  3396. SHARED_MEMORY_LOCK(memory);
  3397. memory_data_end = memory->memory_data_end;
  3398. SHARED_MEMORY_UNLOCK(memory);
  3399. if (memory->heap_handle && memory->heap_data <= addr
  3400. && addr < memory->heap_data_end) {
  3401. mem_allocator_free(memory->heap_handle, addr);
  3402. }
  3403. else if (module_inst->e->malloc_function
  3404. && module_inst->e->free_function && memory->memory_data <= addr
  3405. && addr < memory_data_end) {
  3406. execute_free_function(module_inst, exec_env,
  3407. module_inst->e->free_function, ptr);
  3408. }
  3409. }
  3410. }
  3411. uint64
  3412. wasm_module_malloc(WASMModuleInstance *module_inst, uint64 size,
  3413. void **p_native_addr)
  3414. {
  3415. return wasm_module_malloc_internal(module_inst, NULL, size, p_native_addr);
  3416. }
  3417. uint64
  3418. wasm_module_realloc(WASMModuleInstance *module_inst, uint64 ptr, uint64 size,
  3419. void **p_native_addr)
  3420. {
  3421. return wasm_module_realloc_internal(module_inst, NULL, ptr, size,
  3422. p_native_addr);
  3423. }
  3424. void
  3425. wasm_module_free(WASMModuleInstance *module_inst, uint64 ptr)
  3426. {
  3427. wasm_module_free_internal(module_inst, NULL, ptr);
  3428. }
  3429. uint64
  3430. wasm_module_dup_data(WASMModuleInstance *module_inst, const char *src,
  3431. uint64 size)
  3432. {
  3433. char *buffer;
  3434. uint64 buffer_offset;
  3435. /* TODO: Memory64 size check based on memory idx type */
  3436. bh_assert(size <= UINT32_MAX);
  3437. buffer_offset = wasm_module_malloc(module_inst, size, (void **)&buffer);
  3438. if (buffer_offset != 0) {
  3439. buffer = wasm_runtime_addr_app_to_native(
  3440. (WASMModuleInstanceCommon *)module_inst, buffer_offset);
  3441. bh_memcpy_s(buffer, (uint32)size, src, (uint32)size);
  3442. }
  3443. return buffer_offset;
  3444. }
  3445. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  3446. bool
  3447. wasm_enlarge_table(WASMModuleInstance *module_inst, uint32 table_idx,
  3448. uint32 inc_size, table_elem_type_t init_val)
  3449. {
  3450. uint32 total_size, i;
  3451. table_elem_type_t *new_table_data_start;
  3452. WASMTableInstance *table_inst;
  3453. if (!inc_size) {
  3454. return true;
  3455. }
  3456. bh_assert(table_idx < module_inst->table_count);
  3457. table_inst = wasm_get_table_inst(module_inst, table_idx);
  3458. if (!table_inst) {
  3459. return false;
  3460. }
  3461. if (inc_size > UINT32_MAX - table_inst->cur_size) {
  3462. return false;
  3463. }
  3464. total_size = table_inst->cur_size + inc_size;
  3465. if (total_size > table_inst->max_size) {
  3466. return false;
  3467. }
  3468. /* fill in */
  3469. new_table_data_start = table_inst->elems + table_inst->cur_size;
  3470. for (i = 0; i < inc_size; ++i) {
  3471. new_table_data_start[i] = init_val;
  3472. }
  3473. table_inst->cur_size = total_size;
  3474. return true;
  3475. }
  3476. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  3477. static bool
  3478. call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 tbl_elem_idx,
  3479. uint32 argc, uint32 argv[], bool check_type_idx, uint32 type_idx)
  3480. {
  3481. WASMModuleInstance *module_inst = NULL;
  3482. WASMTableInstance *table_inst = NULL;
  3483. table_elem_type_t tbl_elem_val = NULL_REF;
  3484. uint32 func_idx = 0;
  3485. WASMFunctionInstance *func_inst = NULL;
  3486. module_inst = (WASMModuleInstance *)exec_env->module_inst;
  3487. bh_assert(module_inst);
  3488. table_inst = module_inst->tables[tbl_idx];
  3489. if (!table_inst) {
  3490. wasm_set_exception(module_inst, "unknown table");
  3491. goto got_exception;
  3492. }
  3493. if (tbl_elem_idx >= table_inst->cur_size) {
  3494. wasm_set_exception(module_inst, "undefined element");
  3495. goto got_exception;
  3496. }
  3497. tbl_elem_val = ((table_elem_type_t *)table_inst->elems)[tbl_elem_idx];
  3498. if (tbl_elem_val == NULL_REF) {
  3499. wasm_set_exception(module_inst, "uninitialized element");
  3500. goto got_exception;
  3501. }
  3502. #if WASM_ENABLE_GC == 0
  3503. func_idx = (uint32)tbl_elem_val;
  3504. #else
  3505. func_idx =
  3506. wasm_func_obj_get_func_idx_bound((WASMFuncObjectRef)tbl_elem_val);
  3507. #endif
  3508. /**
  3509. * we insist to call functions owned by the module itself
  3510. **/
  3511. if (func_idx >= module_inst->e->function_count) {
  3512. wasm_set_exception(module_inst, "unknown function");
  3513. goto got_exception;
  3514. }
  3515. func_inst = module_inst->e->functions + func_idx;
  3516. if (check_type_idx) {
  3517. WASMType *cur_type = module_inst->module->types[type_idx];
  3518. WASMType *cur_func_type;
  3519. if (func_inst->is_import_func)
  3520. cur_func_type = (WASMType *)func_inst->u.func_import->func_type;
  3521. else
  3522. cur_func_type = (WASMType *)func_inst->u.func->func_type;
  3523. if (cur_type != cur_func_type) {
  3524. wasm_set_exception(module_inst, "indirect call type mismatch");
  3525. goto got_exception;
  3526. }
  3527. }
  3528. interp_call_wasm(module_inst, exec_env, func_inst, argc, argv);
  3529. return !wasm_copy_exception(module_inst, NULL);
  3530. got_exception:
  3531. return false;
  3532. }
  3533. bool
  3534. wasm_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3535. uint32 argc, uint32 argv[])
  3536. {
  3537. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  3538. }
  3539. #if WASM_ENABLE_THREAD_MGR != 0
  3540. bool
  3541. wasm_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size)
  3542. {
  3543. WASMModuleInstance *module_inst =
  3544. (WASMModuleInstance *)exec_env->module_inst;
  3545. uint32 stack_top_idx = module_inst->module->aux_stack_top_global_index;
  3546. #if WASM_ENABLE_HEAP_AUX_STACK_ALLOCATION == 0
  3547. /* Check the aux stack space */
  3548. uint64 data_end = module_inst->module->aux_data_end;
  3549. uint64 stack_bottom = module_inst->module->aux_stack_bottom;
  3550. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  3551. if ((is_stack_before_data && (size > start_offset))
  3552. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  3553. return false;
  3554. #endif
  3555. if (stack_top_idx != (uint32)-1) {
  3556. /* The aux stack top is a wasm global,
  3557. set the initial value for the global */
  3558. uint8 *global_addr =
  3559. module_inst->global_data
  3560. + module_inst->e->globals[stack_top_idx].data_offset;
  3561. *(int32 *)global_addr = (uint32)start_offset;
  3562. /* The aux stack boundary is a constant value,
  3563. set the value to exec_env */
  3564. exec_env->aux_stack_boundary = (uintptr_t)start_offset - size;
  3565. exec_env->aux_stack_bottom = (uintptr_t)start_offset;
  3566. return true;
  3567. }
  3568. return false;
  3569. }
  3570. bool
  3571. wasm_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size)
  3572. {
  3573. WASMModuleInstance *module_inst =
  3574. (WASMModuleInstance *)exec_env->module_inst;
  3575. /* The aux stack information is resolved in loader
  3576. and store in module */
  3577. uint64 stack_bottom = module_inst->module->aux_stack_bottom;
  3578. uint32 total_aux_stack_size = module_inst->module->aux_stack_size;
  3579. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  3580. if (start_offset)
  3581. *start_offset = stack_bottom;
  3582. if (size)
  3583. *size = total_aux_stack_size;
  3584. return true;
  3585. }
  3586. return false;
  3587. }
  3588. #endif
  3589. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  3590. void
  3591. wasm_get_module_mem_consumption(const WASMModule *module,
  3592. WASMModuleMemConsumption *mem_conspn)
  3593. {
  3594. uint32 i, size;
  3595. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3596. mem_conspn->module_struct_size = sizeof(WASMModule);
  3597. mem_conspn->types_size = sizeof(WASMFuncType *) * module->type_count;
  3598. for (i = 0; i < module->type_count; i++) {
  3599. WASMFuncType *type = module->types[i];
  3600. size = offsetof(WASMFuncType, types)
  3601. + sizeof(uint8) * (type->param_count + type->result_count);
  3602. mem_conspn->types_size += size;
  3603. }
  3604. mem_conspn->imports_size = sizeof(WASMImport) * module->import_count;
  3605. mem_conspn->functions_size =
  3606. sizeof(WASMFunction *) * module->function_count;
  3607. for (i = 0; i < module->function_count; i++) {
  3608. WASMFunction *func = module->functions[i];
  3609. WASMFuncType *type = func->func_type;
  3610. size = sizeof(WASMFunction) + func->local_count
  3611. + sizeof(uint16) * (type->param_count + func->local_count);
  3612. #if WASM_ENABLE_FAST_INTERP != 0
  3613. size +=
  3614. func->code_compiled_size + sizeof(uint32) * func->const_cell_num;
  3615. #endif
  3616. mem_conspn->functions_size += size;
  3617. }
  3618. mem_conspn->tables_size = sizeof(WASMTable) * module->table_count;
  3619. mem_conspn->memories_size = sizeof(WASMMemory) * module->memory_count;
  3620. mem_conspn->globals_size = sizeof(WASMGlobal) * module->global_count;
  3621. mem_conspn->exports_size = sizeof(WASMExport) * module->export_count;
  3622. mem_conspn->table_segs_size =
  3623. sizeof(WASMTableSeg) * module->table_seg_count;
  3624. for (i = 0; i < module->table_seg_count; i++) {
  3625. WASMTableSeg *table_seg = &module->table_segments[i];
  3626. mem_conspn->tables_size +=
  3627. sizeof(InitializerExpression *) * table_seg->value_count;
  3628. }
  3629. mem_conspn->data_segs_size = sizeof(WASMDataSeg *) * module->data_seg_count;
  3630. for (i = 0; i < module->data_seg_count; i++) {
  3631. mem_conspn->data_segs_size += sizeof(WASMDataSeg);
  3632. }
  3633. if (module->const_str_list) {
  3634. StringNode *node = module->const_str_list, *node_next;
  3635. while (node) {
  3636. node_next = node->next;
  3637. mem_conspn->const_strs_size +=
  3638. sizeof(StringNode) + strlen(node->str) + 1;
  3639. node = node_next;
  3640. }
  3641. }
  3642. mem_conspn->total_size += mem_conspn->module_struct_size;
  3643. mem_conspn->total_size += mem_conspn->types_size;
  3644. mem_conspn->total_size += mem_conspn->imports_size;
  3645. mem_conspn->total_size += mem_conspn->functions_size;
  3646. mem_conspn->total_size += mem_conspn->tables_size;
  3647. mem_conspn->total_size += mem_conspn->memories_size;
  3648. mem_conspn->total_size += mem_conspn->globals_size;
  3649. mem_conspn->total_size += mem_conspn->exports_size;
  3650. mem_conspn->total_size += mem_conspn->table_segs_size;
  3651. mem_conspn->total_size += mem_conspn->data_segs_size;
  3652. mem_conspn->total_size += mem_conspn->const_strs_size;
  3653. }
  3654. void
  3655. wasm_get_module_inst_mem_consumption(const WASMModuleInstance *module_inst,
  3656. WASMModuleInstMemConsumption *mem_conspn)
  3657. {
  3658. uint32 i;
  3659. uint64 size;
  3660. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3661. mem_conspn->module_inst_struct_size = (uint8 *)module_inst->e
  3662. - (uint8 *)module_inst
  3663. + sizeof(WASMModuleInstanceExtra);
  3664. mem_conspn->memories_size =
  3665. sizeof(WASMMemoryInstance *) * module_inst->memory_count;
  3666. for (i = 0; i < module_inst->memory_count; i++) {
  3667. WASMMemoryInstance *memory = module_inst->memories[i];
  3668. size = memory->num_bytes_per_page * memory->cur_page_count;
  3669. mem_conspn->memories_size += size;
  3670. mem_conspn->app_heap_size += memory->heap_data_end - memory->heap_data;
  3671. /* size of app heap structure */
  3672. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  3673. /* Module instance structures have been appended into the end of
  3674. module instance */
  3675. }
  3676. mem_conspn->tables_size =
  3677. sizeof(WASMTableInstance *) * module_inst->table_count;
  3678. /* Table instance structures and table elements have been appended into
  3679. the end of module instance */
  3680. mem_conspn->functions_size =
  3681. sizeof(WASMFunctionInstance) * module_inst->e->function_count;
  3682. mem_conspn->globals_size =
  3683. sizeof(WASMGlobalInstance) * module_inst->e->global_count;
  3684. /* Global data has been appended into the end of module instance */
  3685. mem_conspn->exports_size =
  3686. sizeof(WASMExportFuncInstance) * module_inst->export_func_count;
  3687. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  3688. mem_conspn->total_size += mem_conspn->memories_size;
  3689. mem_conspn->total_size += mem_conspn->functions_size;
  3690. mem_conspn->total_size += mem_conspn->tables_size;
  3691. mem_conspn->total_size += mem_conspn->globals_size;
  3692. mem_conspn->total_size += mem_conspn->exports_size;
  3693. }
  3694. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  3695. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  3696. #if WAMR_ENABLE_COPY_CALLSTACK != 0
  3697. uint32
  3698. wasm_interp_copy_callstack(WASMExecEnv *exec_env, wasm_frame_t *buffer,
  3699. uint32 length, uint32 skip_n, char *error_buf,
  3700. uint32_t error_buf_size)
  3701. {
  3702. /*
  3703. * Note for devs: please refrain from such modifications inside of
  3704. * wasm_interp_copy_callstack
  3705. * - any allocations/freeing memory
  3706. * - dereferencing any pointers other than: exec_env, exec_env->module_inst,
  3707. * exec_env->module_inst->module, pointers between stack's bottom and
  3708. * top_boundary For more details check wasm_copy_callstack in
  3709. * wasm_export.h
  3710. */
  3711. WASMModuleInstance *module_inst =
  3712. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3713. WASMInterpFrame *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  3714. uint8 *top_boundary = exec_env->wasm_stack.top_boundary;
  3715. uint8 *bottom = exec_env->wasm_stack.bottom;
  3716. uint32 count = 0;
  3717. WASMCApiFrame record_frame;
  3718. while (cur_frame && (uint8_t *)cur_frame >= bottom
  3719. && (uint8_t *)cur_frame + sizeof(WASMInterpFrame) <= top_boundary
  3720. && count < (skip_n + length)) {
  3721. if (!cur_frame->function) {
  3722. cur_frame = cur_frame->prev_frame;
  3723. continue;
  3724. }
  3725. if (count < skip_n) {
  3726. ++count;
  3727. cur_frame = cur_frame->prev_frame;
  3728. continue;
  3729. }
  3730. record_frame.instance = module_inst;
  3731. record_frame.module_offset = 0;
  3732. // It's safe to dereference module_inst->e because "e" is asigned only
  3733. // once in wasm_instantiate
  3734. record_frame.func_index =
  3735. (uint32)(cur_frame->function - module_inst->e->functions);
  3736. buffer[count - skip_n] = record_frame;
  3737. cur_frame = cur_frame->prev_frame;
  3738. ++count;
  3739. }
  3740. return count >= skip_n ? count - skip_n : 0;
  3741. }
  3742. #endif // WAMR_ENABLE_COPY_CALLSTACK
  3743. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3744. bool
  3745. wasm_interp_create_call_stack(struct WASMExecEnv *exec_env)
  3746. {
  3747. WASMModuleInstance *module_inst =
  3748. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3749. WASMModule *module = module_inst->module;
  3750. WASMInterpFrame *first_frame,
  3751. *cur_frame = wasm_exec_env_get_cur_frame(exec_env);
  3752. uint32 n = 0;
  3753. /* count frames includes a function */
  3754. first_frame = cur_frame;
  3755. while (cur_frame) {
  3756. if (cur_frame->function) {
  3757. n++;
  3758. }
  3759. cur_frame = cur_frame->prev_frame;
  3760. }
  3761. /* release previous stack frames and create new ones */
  3762. destroy_c_api_frames(module_inst->frames);
  3763. if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) {
  3764. return false;
  3765. }
  3766. cur_frame = first_frame;
  3767. n = 0;
  3768. while (cur_frame) {
  3769. WASMCApiFrame frame = { 0 };
  3770. WASMFunctionInstance *func_inst = cur_frame->function;
  3771. const char *func_name = NULL;
  3772. const uint8 *func_code_base = NULL;
  3773. uint32 max_local_cell_num, max_stack_cell_num;
  3774. uint32 all_cell_num, lp_size;
  3775. if (!func_inst) {
  3776. cur_frame = cur_frame->prev_frame;
  3777. continue;
  3778. }
  3779. /* place holder, will overwrite it in wasm_c_api */
  3780. frame.instance = module_inst;
  3781. frame.module_offset = 0;
  3782. frame.func_index = (uint32)(func_inst - module_inst->e->functions);
  3783. func_code_base = wasm_get_func_code(func_inst);
  3784. if (!cur_frame->ip || !func_code_base) {
  3785. frame.func_offset = 0;
  3786. }
  3787. else {
  3788. #if WASM_ENABLE_FAST_INTERP == 0
  3789. frame.func_offset = (uint32)(cur_frame->ip - module->load_addr);
  3790. #else
  3791. frame.func_offset = (uint32)(cur_frame->ip - func_code_base);
  3792. #endif
  3793. }
  3794. func_name = get_func_name_from_index(module_inst, frame.func_index);
  3795. frame.func_name_wp = func_name;
  3796. if (frame.func_index >= module->import_function_count) {
  3797. uint32 wasm_func_idx =
  3798. frame.func_index - module->import_function_count;
  3799. max_local_cell_num =
  3800. module->functions[wasm_func_idx]->param_cell_num
  3801. + module->functions[wasm_func_idx]->local_cell_num;
  3802. max_stack_cell_num =
  3803. module->functions[wasm_func_idx]->max_stack_cell_num;
  3804. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3805. #if WASM_ENABLE_FAST_INTERP != 0
  3806. all_cell_num += module->functions[wasm_func_idx]->const_cell_num;
  3807. #endif
  3808. }
  3809. else {
  3810. WASMFuncType *func_type =
  3811. module->import_functions[frame.func_index].u.function.func_type;
  3812. max_local_cell_num =
  3813. func_type->param_cell_num > 2 ? func_type->param_cell_num : 2;
  3814. max_stack_cell_num = 0;
  3815. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3816. }
  3817. #if WASM_ENABLE_GC == 0
  3818. lp_size = all_cell_num * 4;
  3819. #else
  3820. lp_size = align_uint(all_cell_num * 5, 4);
  3821. #endif
  3822. if (lp_size > 0) {
  3823. if (!(frame.lp = wasm_runtime_malloc(lp_size))) {
  3824. destroy_c_api_frames(module_inst->frames);
  3825. return false;
  3826. }
  3827. bh_memcpy_s(frame.lp, lp_size, cur_frame->lp, lp_size);
  3828. #if WASM_ENABLE_GC != 0
  3829. #if WASM_ENABLE_FAST_INTERP == 0
  3830. frame.sp = frame.lp + (cur_frame->sp - cur_frame->lp);
  3831. #else
  3832. /* for fast-interp, let frame sp point to the end of the frame */
  3833. frame.sp = frame.lp + all_cell_num;
  3834. #endif
  3835. frame.frame_ref = (uint8 *)frame.lp
  3836. + (wasm_interp_get_frame_ref(cur_frame)
  3837. - (uint8 *)cur_frame->lp);
  3838. #endif
  3839. }
  3840. if (!bh_vector_append(module_inst->frames, &frame)) {
  3841. if (frame.lp)
  3842. wasm_runtime_free(frame.lp);
  3843. destroy_c_api_frames(module_inst->frames);
  3844. return false;
  3845. }
  3846. cur_frame = cur_frame->prev_frame;
  3847. n++;
  3848. }
  3849. return true;
  3850. }
  3851. #define PRINT_OR_DUMP() \
  3852. do { \
  3853. total_len += \
  3854. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  3855. if ((!print) && buf && (len == 0)) { \
  3856. exception_unlock(module_inst); \
  3857. return total_len; \
  3858. } \
  3859. } while (0)
  3860. uint32
  3861. wasm_interp_dump_call_stack(struct WASMExecEnv *exec_env, bool print, char *buf,
  3862. uint32 len)
  3863. {
  3864. WASMModuleInstance *module_inst =
  3865. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3866. uint32 n = 0, total_len = 0, total_frames;
  3867. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  3868. * will be truncated */
  3869. char line_buf[256];
  3870. if (!module_inst->frames) {
  3871. return 0;
  3872. }
  3873. total_frames = (uint32)bh_vector_size(module_inst->frames);
  3874. if (total_frames == 0) {
  3875. return 0;
  3876. }
  3877. exception_lock(module_inst);
  3878. snprintf(line_buf, sizeof(line_buf), "\n");
  3879. PRINT_OR_DUMP();
  3880. while (n < total_frames) {
  3881. WASMCApiFrame frame = { 0 };
  3882. uint32 line_length, i;
  3883. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  3884. exception_unlock(module_inst);
  3885. return 0;
  3886. }
  3887. #if WASM_ENABLE_FAST_JIT != 0
  3888. /* Fast JIT doesn't support committing ip (instruction pointer) yet */
  3889. if (module_inst->e->running_mode == Mode_Fast_JIT
  3890. || module_inst->e->running_mode == Mode_Multi_Tier_JIT) {
  3891. /* function name not exported, print number instead */
  3892. if (frame.func_name_wp == NULL) {
  3893. line_length = snprintf(line_buf, sizeof(line_buf),
  3894. "#%02" PRIu32 " $f%" PRIu32 "\n", n,
  3895. frame.func_index);
  3896. }
  3897. else {
  3898. line_length =
  3899. snprintf(line_buf, sizeof(line_buf), "#%02" PRIu32 " %s\n",
  3900. n, frame.func_name_wp);
  3901. }
  3902. }
  3903. else
  3904. #endif
  3905. {
  3906. /* function name not exported, print number instead */
  3907. if (frame.func_name_wp == NULL) {
  3908. line_length =
  3909. snprintf(line_buf, sizeof(line_buf),
  3910. "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n", n,
  3911. frame.func_offset, frame.func_index);
  3912. }
  3913. else {
  3914. line_length = snprintf(line_buf, sizeof(line_buf),
  3915. "#%02" PRIu32 ": 0x%04x - %s\n", n,
  3916. frame.func_offset, frame.func_name_wp);
  3917. }
  3918. }
  3919. if (line_length >= sizeof(line_buf)) {
  3920. uint32 line_buffer_len = sizeof(line_buf);
  3921. /* If line too long, ensure the last character is '\n' */
  3922. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  3923. line_buf[i] = '.';
  3924. }
  3925. line_buf[line_buffer_len - 2] = '\n';
  3926. }
  3927. PRINT_OR_DUMP();
  3928. n++;
  3929. }
  3930. snprintf(line_buf, sizeof(line_buf), "\n");
  3931. PRINT_OR_DUMP();
  3932. exception_unlock(module_inst);
  3933. return total_len + 1;
  3934. }
  3935. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  3936. #if WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  3937. || WASM_ENABLE_WAMR_COMPILER != 0
  3938. void
  3939. jit_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  3940. {
  3941. if (id != EXCE_ALREADY_THROWN)
  3942. wasm_set_exception_with_id(module_inst, id);
  3943. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3944. wasm_runtime_access_exce_check_guard_page();
  3945. #endif
  3946. }
  3947. bool
  3948. jit_check_app_addr_and_convert(WASMModuleInstance *module_inst, bool is_str,
  3949. uint64 app_buf_addr, uint64 app_buf_size,
  3950. void **p_native_addr)
  3951. {
  3952. bool ret = wasm_check_app_addr_and_convert(
  3953. module_inst, is_str, app_buf_addr, app_buf_size, p_native_addr);
  3954. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3955. if (!ret)
  3956. wasm_runtime_access_exce_check_guard_page();
  3957. #endif
  3958. return ret;
  3959. }
  3960. #endif /* end of WASM_ENABLE_FAST_JIT != 0 || WASM_ENABLE_JIT != 0 \
  3961. || WASM_ENABLE_WAMR_COMPILER != 0 */
  3962. #if WASM_ENABLE_FAST_JIT != 0
  3963. bool
  3964. fast_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3965. uint32 type_idx, uint32 argc, uint32 *argv)
  3966. {
  3967. return call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, true,
  3968. type_idx);
  3969. }
  3970. #endif /* end of WASM_ENABLE_FAST_JIT != 0 */
  3971. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  3972. bool
  3973. llvm_jit_call_indirect(WASMExecEnv *exec_env, uint32 tbl_idx, uint32 elem_idx,
  3974. uint32 argc, uint32 *argv)
  3975. {
  3976. bool ret;
  3977. bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode);
  3978. ret = call_indirect(exec_env, tbl_idx, elem_idx, argc, argv, false, 0);
  3979. #ifdef OS_ENABLE_HW_BOUND_CHECK
  3980. if (!ret)
  3981. wasm_runtime_access_exce_check_guard_page();
  3982. #endif
  3983. return ret;
  3984. }
  3985. bool
  3986. llvm_jit_invoke_native(WASMExecEnv *exec_env, uint32 func_idx, uint32 argc,
  3987. uint32 *argv)
  3988. {
  3989. WASMModuleInstance *module_inst;
  3990. WASMModule *module;
  3991. uint32 *func_type_indexes;
  3992. uint32 func_type_idx;
  3993. WASMFuncType *func_type;
  3994. void *func_ptr;
  3995. WASMFunctionImport *import_func;
  3996. CApiFuncImport *c_api_func_import = NULL;
  3997. const char *signature;
  3998. void *attachment;
  3999. char buf[96];
  4000. bool ret = false;
  4001. bh_assert(exec_env->module_inst->module_type == Wasm_Module_Bytecode);
  4002. module_inst = (WASMModuleInstance *)wasm_runtime_get_module_inst(exec_env);
  4003. module = module_inst->module;
  4004. func_type_indexes = module_inst->func_type_indexes;
  4005. func_type_idx = func_type_indexes[func_idx];
  4006. func_type = (WASMFuncType *)module->types[func_type_idx];
  4007. func_ptr = module_inst->func_ptrs[func_idx];
  4008. bh_assert(func_idx < module->import_function_count);
  4009. import_func = &module->import_functions[func_idx].u.function;
  4010. if (import_func->call_conv_wasm_c_api) {
  4011. if (module_inst->c_api_func_imports) {
  4012. c_api_func_import = module_inst->c_api_func_imports + func_idx;
  4013. func_ptr = c_api_func_import->func_ptr_linked;
  4014. }
  4015. else {
  4016. c_api_func_import = NULL;
  4017. func_ptr = NULL;
  4018. }
  4019. }
  4020. if (!func_ptr) {
  4021. snprintf(buf, sizeof(buf),
  4022. "failed to call unlinked import function (%s, %s)",
  4023. import_func->module_name, import_func->field_name);
  4024. wasm_set_exception(module_inst, buf);
  4025. goto fail;
  4026. }
  4027. attachment = import_func->attachment;
  4028. if (import_func->call_conv_wasm_c_api) {
  4029. ret = wasm_runtime_invoke_c_api_native(
  4030. (WASMModuleInstanceCommon *)module_inst, func_ptr, func_type, argc,
  4031. argv, c_api_func_import->with_env_arg, c_api_func_import->env_arg);
  4032. }
  4033. else if (!import_func->call_conv_raw) {
  4034. signature = import_func->signature;
  4035. ret =
  4036. wasm_runtime_invoke_native(exec_env, func_ptr, func_type, signature,
  4037. attachment, argv, argc, argv);
  4038. }
  4039. else {
  4040. signature = import_func->signature;
  4041. ret = wasm_runtime_invoke_native_raw(exec_env, func_ptr, func_type,
  4042. signature, attachment, argv, argc,
  4043. argv);
  4044. }
  4045. fail:
  4046. #ifdef OS_ENABLE_HW_BOUND_CHECK
  4047. if (!ret)
  4048. wasm_runtime_access_exce_check_guard_page();
  4049. #endif
  4050. return ret;
  4051. }
  4052. #if WASM_ENABLE_BULK_MEMORY != 0
  4053. bool
  4054. llvm_jit_memory_init(WASMModuleInstance *module_inst, uint32 seg_index,
  4055. uint32 offset, uint32 len, size_t dst)
  4056. {
  4057. WASMMemoryInstance *memory_inst;
  4058. WASMModule *module;
  4059. uint8 *data;
  4060. uint8 *maddr;
  4061. uint64 seg_len;
  4062. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4063. memory_inst = wasm_get_default_memory(module_inst);
  4064. if (bh_bitmap_get_bit(module_inst->e->common.data_dropped, seg_index)) {
  4065. seg_len = 0;
  4066. data = NULL;
  4067. }
  4068. else {
  4069. module = module_inst->module;
  4070. seg_len = module->data_segments[seg_index]->data_length;
  4071. data = module->data_segments[seg_index]->data;
  4072. }
  4073. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  4074. (uint64)dst, (uint64)len))
  4075. return false;
  4076. if ((uint64)offset + (uint64)len > seg_len) {
  4077. wasm_set_exception(module_inst, "out of bounds memory access");
  4078. return false;
  4079. }
  4080. maddr = wasm_runtime_addr_app_to_native(
  4081. (WASMModuleInstanceCommon *)module_inst, (uint64)dst);
  4082. SHARED_MEMORY_LOCK(memory_inst);
  4083. bh_memcpy_s(maddr, CLAMP_U64_TO_U32(memory_inst->memory_data_size - dst),
  4084. data + offset, len);
  4085. SHARED_MEMORY_UNLOCK(memory_inst);
  4086. return true;
  4087. }
  4088. bool
  4089. llvm_jit_data_drop(WASMModuleInstance *module_inst, uint32 seg_index)
  4090. {
  4091. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4092. bh_bitmap_set_bit(module_inst->e->common.data_dropped, seg_index);
  4093. /* Currently we can't free the dropped data segment
  4094. as they are stored in wasm bytecode */
  4095. return true;
  4096. }
  4097. #endif /* end of WASM_ENABLE_BULK_MEMORY != 0 */
  4098. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  4099. void
  4100. llvm_jit_drop_table_seg(WASMModuleInstance *module_inst, uint32 tbl_seg_idx)
  4101. {
  4102. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4103. bh_bitmap_set_bit(module_inst->e->common.elem_dropped, tbl_seg_idx);
  4104. }
  4105. void
  4106. llvm_jit_table_init(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4107. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  4108. uint32 dst_offset)
  4109. {
  4110. WASMTableInstance *tbl_inst;
  4111. WASMTableSeg *tbl_seg;
  4112. table_elem_type_t *table_elems;
  4113. InitializerExpression *tbl_seg_init_values = NULL, *init_values;
  4114. uint32 i, tbl_seg_len = 0;
  4115. #if WASM_ENABLE_GC != 0
  4116. void *func_obj;
  4117. #endif
  4118. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4119. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4120. tbl_seg = module_inst->module->table_segments + tbl_seg_idx;
  4121. bh_assert(tbl_inst);
  4122. bh_assert(tbl_seg);
  4123. if (!bh_bitmap_get_bit(module_inst->e->common.elem_dropped, tbl_seg_idx)) {
  4124. /* table segment isn't dropped */
  4125. tbl_seg_init_values = tbl_seg->init_values;
  4126. tbl_seg_len = tbl_seg->value_count;
  4127. }
  4128. if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len)
  4129. || offset_len_out_of_bounds(dst_offset, length, tbl_inst->cur_size)) {
  4130. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4131. return;
  4132. }
  4133. if (!length) {
  4134. return;
  4135. }
  4136. table_elems = tbl_inst->elems + dst_offset;
  4137. init_values = tbl_seg_init_values + src_offset;
  4138. for (i = 0; i < length; i++) {
  4139. #if WASM_ENABLE_GC != 0
  4140. /* UINT32_MAX indicates that it is a null ref */
  4141. if (init_values[i].u.ref_index != UINT32_MAX) {
  4142. if (!(func_obj = wasm_create_func_obj(module_inst,
  4143. init_values[i].u.ref_index,
  4144. true, NULL, 0))) {
  4145. wasm_set_exception(module_inst, "null function reference");
  4146. return;
  4147. }
  4148. table_elems[i] = func_obj;
  4149. }
  4150. else {
  4151. table_elems[i] = NULL_REF;
  4152. }
  4153. #else
  4154. table_elems[i] = init_values[i].u.ref_index;
  4155. #endif
  4156. }
  4157. }
  4158. void
  4159. llvm_jit_table_copy(WASMModuleInstance *module_inst, uint32 src_tbl_idx,
  4160. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  4161. uint32 dst_offset)
  4162. {
  4163. WASMTableInstance *src_tbl_inst;
  4164. WASMTableInstance *dst_tbl_inst;
  4165. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4166. src_tbl_inst = wasm_get_table_inst(module_inst, src_tbl_idx);
  4167. dst_tbl_inst = wasm_get_table_inst(module_inst, dst_tbl_idx);
  4168. bh_assert(src_tbl_inst);
  4169. bh_assert(dst_tbl_inst);
  4170. if (offset_len_out_of_bounds(dst_offset, length, dst_tbl_inst->cur_size)
  4171. || offset_len_out_of_bounds(src_offset, length,
  4172. src_tbl_inst->cur_size)) {
  4173. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4174. return;
  4175. }
  4176. /* if src_offset >= dst_offset, copy from front to back */
  4177. /* if src_offset < dst_offset, copy from back to front */
  4178. /* merge all together */
  4179. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(WASMTableInstance, elems)
  4180. + sizeof(table_elem_type_t) * dst_offset,
  4181. (uint32)sizeof(table_elem_type_t)
  4182. * (dst_tbl_inst->cur_size - dst_offset),
  4183. (uint8 *)src_tbl_inst + offsetof(WASMTableInstance, elems)
  4184. + sizeof(table_elem_type_t) * src_offset,
  4185. (uint32)sizeof(table_elem_type_t) * length);
  4186. }
  4187. void
  4188. llvm_jit_table_fill(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4189. uint32 length, uintptr_t val, uint32 data_offset)
  4190. {
  4191. WASMTableInstance *tbl_inst;
  4192. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4193. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4194. bh_assert(tbl_inst);
  4195. if (offset_len_out_of_bounds(data_offset, length, tbl_inst->cur_size)) {
  4196. jit_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  4197. return;
  4198. }
  4199. for (; length != 0; data_offset++, length--) {
  4200. tbl_inst->elems[data_offset] = (table_elem_type_t)val;
  4201. }
  4202. }
  4203. uint32
  4204. llvm_jit_table_grow(WASMModuleInstance *module_inst, uint32 tbl_idx,
  4205. uint32 inc_size, uintptr_t init_val)
  4206. {
  4207. WASMTableInstance *tbl_inst;
  4208. uint32 i, orig_size, total_size;
  4209. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4210. tbl_inst = wasm_get_table_inst(module_inst, tbl_idx);
  4211. if (!tbl_inst) {
  4212. return (uint32)-1;
  4213. }
  4214. orig_size = tbl_inst->cur_size;
  4215. if (!inc_size) {
  4216. return orig_size;
  4217. }
  4218. if (tbl_inst->cur_size > UINT32_MAX - inc_size) { /* integer overflow */
  4219. #if WASM_ENABLE_SPEC_TEST == 0
  4220. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  4221. ") failed because of integer overflow",
  4222. tbl_inst->cur_size, inc_size);
  4223. #endif
  4224. return (uint32)-1;
  4225. }
  4226. total_size = tbl_inst->cur_size + inc_size;
  4227. if (total_size > tbl_inst->max_size) {
  4228. #if WASM_ENABLE_SPEC_TEST == 0
  4229. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  4230. ") failed because of over max size",
  4231. tbl_inst->cur_size, inc_size);
  4232. #endif
  4233. return (uint32)-1;
  4234. }
  4235. /* fill in */
  4236. for (i = 0; i < inc_size; ++i) {
  4237. tbl_inst->elems[tbl_inst->cur_size + i] = (table_elem_type_t)init_val;
  4238. }
  4239. tbl_inst->cur_size = total_size;
  4240. return orig_size;
  4241. }
  4242. #endif /* end of WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  4243. #if WASM_ENABLE_GC != 0
  4244. void *
  4245. llvm_jit_create_func_obj(WASMModuleInstance *module_inst, uint32 func_idx,
  4246. bool throw_exce, char *error_buf,
  4247. uint32 error_buf_size)
  4248. {
  4249. bh_assert(module_inst->module_type == Wasm_Module_Bytecode);
  4250. return wasm_create_func_obj(module_inst, func_idx, throw_exce, error_buf,
  4251. error_buf_size);
  4252. }
  4253. bool
  4254. llvm_jit_obj_is_instance_of(WASMModuleInstance *module_inst,
  4255. WASMObjectRef gc_obj, uint32 type_index)
  4256. {
  4257. WASMModule *module = module_inst->module;
  4258. WASMType **types = module->types;
  4259. uint32 type_count = module->type_count;
  4260. return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count);
  4261. }
  4262. bool
  4263. llvm_jit_func_type_is_super_of(WASMModuleInstance *module_inst,
  4264. uint32 type_idx1, uint32 type_idx2)
  4265. {
  4266. WASMModule *module = module_inst->module;
  4267. WASMType **types = module->types;
  4268. if (type_idx1 == type_idx2)
  4269. return true;
  4270. bh_assert(types[type_idx1]->type_flag == WASM_TYPE_FUNC);
  4271. bh_assert(types[type_idx2]->type_flag == WASM_TYPE_FUNC);
  4272. return wasm_func_type_is_super_of((WASMFuncType *)types[type_idx1],
  4273. (WASMFuncType *)types[type_idx2]);
  4274. }
  4275. WASMRttTypeRef
  4276. llvm_jit_rtt_type_new(WASMModuleInstance *module_inst, uint32 type_index)
  4277. {
  4278. WASMModule *module = module_inst->module;
  4279. WASMType *defined_type = module->types[type_index];
  4280. WASMRttType **rtt_types = module->rtt_types;
  4281. uint32 rtt_type_count = module->type_count;
  4282. korp_mutex *rtt_type_lock = &module->rtt_type_lock;
  4283. return wasm_rtt_type_new(defined_type, type_index, rtt_types,
  4284. rtt_type_count, rtt_type_lock);
  4285. }
  4286. bool
  4287. llvm_array_init_with_data(WASMModuleInstance *module_inst, uint32 seg_index,
  4288. uint32 data_seg_offset, WASMArrayObjectRef array_obj,
  4289. uint32 elem_size, uint32 array_len)
  4290. {
  4291. WASMModule *wasm_module = module_inst->module;
  4292. WASMDataSeg *data_seg;
  4293. uint8 *array_elem_base;
  4294. uint64 total_size;
  4295. data_seg = wasm_module->data_segments[seg_index];
  4296. total_size = (int64)elem_size * array_len;
  4297. if (data_seg_offset >= data_seg->data_length
  4298. || total_size > data_seg->data_length - data_seg_offset) {
  4299. wasm_set_exception(module_inst, "out of bounds memory access");
  4300. return false;
  4301. }
  4302. array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj);
  4303. bh_memcpy_s(array_elem_base, (uint32)total_size,
  4304. data_seg->data + data_seg_offset, (uint32)total_size);
  4305. return true;
  4306. }
  4307. #endif /* end of WASM_ENABLE_GC != 0 */
  4308. #endif /* end of WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0 */
  4309. #if WASM_ENABLE_LIBC_WASI != 0 && WASM_ENABLE_MULTI_MODULE != 0
  4310. void
  4311. wasm_propagate_wasi_args(WASMModule *module)
  4312. {
  4313. if (!module->import_count)
  4314. return;
  4315. bh_assert(&module->import_module_list_head);
  4316. WASMRegisteredModule *node =
  4317. bh_list_first_elem(&module->import_module_list_head);
  4318. while (node) {
  4319. WASIArguments *wasi_args_impt_mod =
  4320. &((WASMModule *)(node->module))->wasi_args;
  4321. bh_assert(wasi_args_impt_mod);
  4322. bh_memcpy_s(wasi_args_impt_mod, sizeof(WASIArguments),
  4323. &module->wasi_args, sizeof(WASIArguments));
  4324. node = bh_list_elem_next(node);
  4325. }
  4326. }
  4327. #endif
  4328. bool
  4329. wasm_check_utf8_str(const uint8 *str, uint32 len)
  4330. {
  4331. /* The valid ranges are taken from page 125, below link
  4332. https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf */
  4333. const uint8 *p = str, *p_end = str + len;
  4334. uint8 chr;
  4335. while (p < p_end) {
  4336. chr = *p;
  4337. if (chr == 0) {
  4338. LOG_WARNING(
  4339. "LIMITATION: a string which contains '\\00' is unsupported");
  4340. return false;
  4341. }
  4342. else if (chr < 0x80) {
  4343. p++;
  4344. }
  4345. else if (chr >= 0xC2 && chr <= 0xDF && p + 1 < p_end) {
  4346. if (p[1] < 0x80 || p[1] > 0xBF) {
  4347. return false;
  4348. }
  4349. p += 2;
  4350. }
  4351. else if (chr >= 0xE0 && chr <= 0xEF && p + 2 < p_end) {
  4352. if (chr == 0xE0) {
  4353. if (p[1] < 0xA0 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) {
  4354. return false;
  4355. }
  4356. }
  4357. else if (chr == 0xED) {
  4358. if (p[1] < 0x80 || p[1] > 0x9F || p[2] < 0x80 || p[2] > 0xBF) {
  4359. return false;
  4360. }
  4361. }
  4362. else { /* chr >= 0xE1 && chr <= 0xEF */
  4363. if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF) {
  4364. return false;
  4365. }
  4366. }
  4367. p += 3;
  4368. }
  4369. else if (chr >= 0xF0 && chr <= 0xF4 && p + 3 < p_end) {
  4370. if (chr == 0xF0) {
  4371. if (p[1] < 0x90 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF
  4372. || p[3] < 0x80 || p[3] > 0xBF) {
  4373. return false;
  4374. }
  4375. }
  4376. else if (chr <= 0xF3) { /* and also chr >= 0xF1 */
  4377. if (p[1] < 0x80 || p[1] > 0xBF || p[2] < 0x80 || p[2] > 0xBF
  4378. || p[3] < 0x80 || p[3] > 0xBF) {
  4379. return false;
  4380. }
  4381. }
  4382. else { /* chr == 0xF4 */
  4383. if (p[1] < 0x80 || p[1] > 0x8F || p[2] < 0x80 || p[2] > 0xBF
  4384. || p[3] < 0x80 || p[3] > 0xBF) {
  4385. return false;
  4386. }
  4387. }
  4388. p += 4;
  4389. }
  4390. else {
  4391. return false;
  4392. }
  4393. }
  4394. return (p == p_end);
  4395. }
  4396. char *
  4397. wasm_const_str_list_insert(const uint8 *str, uint32 len, WASMModule *module,
  4398. bool is_load_from_file_buf, char *error_buf,
  4399. uint32 error_buf_size)
  4400. {
  4401. StringNode *node, *node_next;
  4402. if (!wasm_check_utf8_str(str, len)) {
  4403. set_error_buf(error_buf, error_buf_size, "invalid UTF-8 encoding");
  4404. return NULL;
  4405. }
  4406. if (len == 0) {
  4407. return "";
  4408. }
  4409. else if (is_load_from_file_buf) {
  4410. /* As the file buffer can be referred to after loading, we use
  4411. the previous byte of leb encoded size to adjust the string:
  4412. move string 1 byte backward and then append '\0' */
  4413. char *c_str = (char *)str - 1;
  4414. bh_memmove_s(c_str, len + 1, c_str + 1, len);
  4415. c_str[len] = '\0';
  4416. return c_str;
  4417. }
  4418. /* Search const str list */
  4419. node = module->const_str_list;
  4420. while (node) {
  4421. node_next = node->next;
  4422. if (strlen(node->str) == len && !memcmp(node->str, str, len))
  4423. break;
  4424. node = node_next;
  4425. }
  4426. if (node) {
  4427. return node->str;
  4428. }
  4429. if (!(node = runtime_malloc(sizeof(StringNode) + len + 1, error_buf,
  4430. error_buf_size))) {
  4431. return NULL;
  4432. }
  4433. node->str = ((char *)node) + sizeof(StringNode);
  4434. bh_memcpy_s(node->str, len + 1, str, len);
  4435. node->str[len] = '\0';
  4436. if (!module->const_str_list) {
  4437. /* set as head */
  4438. module->const_str_list = node;
  4439. node->next = NULL;
  4440. }
  4441. else {
  4442. /* insert it */
  4443. node->next = module->const_str_list;
  4444. module->const_str_list = node;
  4445. }
  4446. return node->str;
  4447. }
  4448. bool
  4449. wasm_set_module_name(WASMModule *module, const char *name, char *error_buf,
  4450. uint32_t error_buf_size)
  4451. {
  4452. if (!name)
  4453. return false;
  4454. module->name =
  4455. wasm_const_str_list_insert((const uint8 *)name, (uint32)strlen(name),
  4456. module, false, error_buf, error_buf_size);
  4457. return module->name != NULL;
  4458. }
  4459. const char *
  4460. wasm_get_module_name(WASMModule *module)
  4461. {
  4462. return module->name;
  4463. }