aot_runtime.c 189 KB

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