wasm_runtime.c 169 KB

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