aot_runtime.c 186 KB

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