aot_runtime.c 188 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521
  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. if (!exec_env_tls) {
  2028. if (!os_thread_signal_inited()) {
  2029. aot_set_exception(module_inst, "thread signal env not inited");
  2030. return false;
  2031. }
  2032. /* Set thread handle and stack boundary if they haven't been set */
  2033. wasm_exec_env_set_thread_info(exec_env);
  2034. wasm_runtime_set_exec_env_tls(exec_env);
  2035. }
  2036. else {
  2037. if (exec_env_tls != exec_env) {
  2038. aot_set_exception(module_inst, "invalid exec env");
  2039. return false;
  2040. }
  2041. }
  2042. /* Check native stack overflow firstly to ensure we have enough
  2043. native stack to run the following codes before actually calling
  2044. the aot function in invokeNative function. */
  2045. if (!wasm_runtime_detect_native_stack_overflow(exec_env)) {
  2046. return false;
  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. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2893. void *prev_frame = get_top_frame(exec_env);
  2894. if (!is_frame_per_function(exec_env)
  2895. && !aot_alloc_frame(exec_env, func_idx)) {
  2896. if (argv1 != argv1_buf)
  2897. wasm_runtime_free(argv1);
  2898. return false;
  2899. }
  2900. #endif
  2901. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  2902. attachment, argv1, argc, argv);
  2903. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2904. /* Free all frames allocated, note that some frames
  2905. may be allocated in AOT code and haven't been
  2906. freed if exception occurred */
  2907. while (get_top_frame(exec_env) != prev_frame)
  2908. aot_free_frame(exec_env);
  2909. #endif
  2910. if (!ret) {
  2911. if (argv1 != argv1_buf)
  2912. wasm_runtime_free(argv1);
  2913. goto fail;
  2914. }
  2915. /* Get extra result values */
  2916. switch (func_type->types[func_type->param_count]) {
  2917. case VALUE_TYPE_I32:
  2918. case VALUE_TYPE_F32:
  2919. #if WASM_ENABLE_REF_TYPES != 0
  2920. case VALUE_TYPE_FUNCREF:
  2921. case VALUE_TYPE_EXTERNREF:
  2922. #endif
  2923. argv_ret++;
  2924. break;
  2925. case VALUE_TYPE_I64:
  2926. case VALUE_TYPE_F64:
  2927. argv_ret += 2;
  2928. break;
  2929. #if WASM_ENABLE_SIMD != 0
  2930. case VALUE_TYPE_V128:
  2931. argv_ret += 4;
  2932. break;
  2933. #endif
  2934. default:
  2935. bh_assert(0);
  2936. break;
  2937. }
  2938. ext_rets =
  2939. argv1 + argc + sizeof(void *) / sizeof(uint32) * ext_ret_count;
  2940. bh_memcpy_s(argv_ret, sizeof(uint32) * cell_num, ext_rets,
  2941. sizeof(uint32) * cell_num);
  2942. if (argv1 != argv1_buf)
  2943. wasm_runtime_free(argv1);
  2944. return true;
  2945. }
  2946. else {
  2947. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2948. void *prev_frame = get_top_frame(exec_env);
  2949. /* Only allocate frame for frame-per-call mode; in the
  2950. frame-per-function mode the frame is allocated at the
  2951. beginning of the function. */
  2952. if (!is_frame_per_function(exec_env)
  2953. && !aot_alloc_frame(exec_env, func_idx)) {
  2954. return false;
  2955. }
  2956. #endif
  2957. ret = invoke_native_internal(exec_env, func_ptr, func_type, signature,
  2958. attachment, argv, argc, argv);
  2959. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  2960. /* Free all frames allocated, note that some frames
  2961. may be allocated in AOT code and haven't been
  2962. freed if exception occurred */
  2963. while (get_top_frame(exec_env) != prev_frame)
  2964. aot_free_frame(exec_env);
  2965. #endif
  2966. if (!ret)
  2967. goto fail;
  2968. return true;
  2969. }
  2970. fail:
  2971. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2972. wasm_runtime_access_exce_check_guard_page();
  2973. #endif
  2974. return false;
  2975. }
  2976. bool
  2977. aot_check_app_addr_and_convert(AOTModuleInstance *module_inst, bool is_str,
  2978. uint64 app_buf_addr, uint64 app_buf_size,
  2979. void **p_native_addr)
  2980. {
  2981. bool ret;
  2982. ret = wasm_check_app_addr_and_convert(module_inst, is_str, app_buf_addr,
  2983. app_buf_size, p_native_addr);
  2984. #ifdef OS_ENABLE_HW_BOUND_CHECK
  2985. if (!ret)
  2986. wasm_runtime_access_exce_check_guard_page();
  2987. #endif
  2988. return ret;
  2989. }
  2990. void *
  2991. aot_memmove(void *dest, const void *src, size_t n)
  2992. {
  2993. return memmove(dest, src, n);
  2994. }
  2995. void *
  2996. aot_memset(void *s, int c, size_t n)
  2997. {
  2998. return memset(s, c, n);
  2999. }
  3000. double
  3001. aot_sqrt(double x)
  3002. {
  3003. return sqrt(x);
  3004. }
  3005. float
  3006. aot_sqrtf(float x)
  3007. {
  3008. return sqrtf(x);
  3009. }
  3010. #if WASM_ENABLE_BULK_MEMORY != 0
  3011. bool
  3012. aot_memory_init(AOTModuleInstance *module_inst, uint32 seg_index, uint32 offset,
  3013. uint32 len, size_t dst)
  3014. {
  3015. AOTMemoryInstance *memory_inst = aot_get_default_memory(module_inst);
  3016. AOTModule *aot_module;
  3017. uint8 *data;
  3018. uint8 *maddr;
  3019. uint64 seg_len;
  3020. if (bh_bitmap_get_bit(
  3021. ((AOTModuleInstanceExtra *)module_inst->e)->common.data_dropped,
  3022. seg_index)) {
  3023. seg_len = 0;
  3024. data = NULL;
  3025. }
  3026. else {
  3027. aot_module = (AOTModule *)module_inst->module;
  3028. seg_len = aot_module->mem_init_data_list[seg_index]->byte_count;
  3029. data = aot_module->mem_init_data_list[seg_index]->bytes;
  3030. }
  3031. if (!wasm_runtime_validate_app_addr((WASMModuleInstanceCommon *)module_inst,
  3032. (uint64)dst, (uint64)len))
  3033. return false;
  3034. if ((uint64)offset + (uint64)len > seg_len) {
  3035. aot_set_exception(module_inst, "out of bounds memory access");
  3036. return false;
  3037. }
  3038. maddr = wasm_runtime_addr_app_to_native(
  3039. (WASMModuleInstanceCommon *)module_inst, (uint64)dst);
  3040. SHARED_MEMORY_LOCK(memory_inst);
  3041. bh_memcpy_s(maddr, CLAMP_U64_TO_U32(memory_inst->memory_data_size - dst),
  3042. data + offset, len);
  3043. SHARED_MEMORY_UNLOCK(memory_inst);
  3044. return true;
  3045. }
  3046. bool
  3047. aot_data_drop(AOTModuleInstance *module_inst, uint32 seg_index)
  3048. {
  3049. bh_bitmap_set_bit(
  3050. ((AOTModuleInstanceExtra *)module_inst->e)->common.data_dropped,
  3051. seg_index);
  3052. /* Currently we can't free the dropped data segment
  3053. as the mem_init_data_count is a continuous array */
  3054. return true;
  3055. }
  3056. #endif /* WASM_ENABLE_BULK_MEMORY */
  3057. #if WASM_ENABLE_THREAD_MGR != 0
  3058. bool
  3059. aot_set_aux_stack(WASMExecEnv *exec_env, uint64 start_offset, uint32 size)
  3060. {
  3061. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3062. AOTModule *module = (AOTModule *)module_inst->module;
  3063. uint32 stack_top_idx = module->aux_stack_top_global_index;
  3064. uint64 data_end = module->aux_data_end;
  3065. uint64 stack_bottom = module->aux_stack_bottom;
  3066. bool is_stack_before_data = stack_bottom < data_end ? true : false;
  3067. /* Check the aux stack space, currently we don't allocate space in heap */
  3068. if ((is_stack_before_data && (size > start_offset))
  3069. || ((!is_stack_before_data) && (start_offset - data_end < size)))
  3070. return false;
  3071. if (stack_top_idx != (uint32)-1) {
  3072. /* The aux stack top is a wasm global,
  3073. set the initial value for the global */
  3074. uint32 global_offset = module->globals[stack_top_idx].data_offset;
  3075. uint8 *global_addr = module_inst->global_data + global_offset;
  3076. /* TODO: Memory64 the type i32/i64 depends on memory idx type*/
  3077. *(int32 *)global_addr = (uint32)start_offset;
  3078. /* The aux stack boundary is a constant value,
  3079. set the value to exec_env */
  3080. exec_env->aux_stack_boundary = (uintptr_t)start_offset - size;
  3081. exec_env->aux_stack_bottom = (uintptr_t)start_offset;
  3082. return true;
  3083. }
  3084. return false;
  3085. }
  3086. bool
  3087. aot_get_aux_stack(WASMExecEnv *exec_env, uint64 *start_offset, uint32 *size)
  3088. {
  3089. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3090. AOTModule *module = (AOTModule *)module_inst->module;
  3091. /* The aux stack information is resolved in loader
  3092. and store in module */
  3093. uint64 stack_bottom = module->aux_stack_bottom;
  3094. uint32 total_aux_stack_size = module->aux_stack_size;
  3095. if (stack_bottom != 0 && total_aux_stack_size != 0) {
  3096. if (start_offset)
  3097. *start_offset = stack_bottom;
  3098. if (size)
  3099. *size = total_aux_stack_size;
  3100. return true;
  3101. }
  3102. return false;
  3103. }
  3104. #endif
  3105. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  3106. static void
  3107. const_string_node_size_cb(void *key, void *value, void *p_const_string_size)
  3108. {
  3109. uint32 const_string_size = 0;
  3110. const_string_size += bh_hash_map_get_elem_struct_size();
  3111. const_string_size += strlen((const char *)value) + 1;
  3112. *(uint32 *)p_const_string_size += const_string_size;
  3113. }
  3114. void
  3115. aot_get_module_mem_consumption(const AOTModule *module,
  3116. WASMModuleMemConsumption *mem_conspn)
  3117. {
  3118. uint32 i, size;
  3119. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3120. mem_conspn->module_struct_size = sizeof(AOTModule);
  3121. mem_conspn->types_size = sizeof(AOTFuncType *) * module->type_count;
  3122. for (i = 0; i < module->type_count; i++) {
  3123. AOTFuncType *type = (AOTFuncType *)module->types[i];
  3124. size = offsetof(AOTFuncType, types)
  3125. + sizeof(uint8) * (type->param_count + type->result_count);
  3126. mem_conspn->types_size += size;
  3127. }
  3128. mem_conspn->imports_size =
  3129. sizeof(AOTImportMemory) * module->import_memory_count
  3130. + sizeof(AOTImportTable) * module->import_table_count
  3131. + sizeof(AOTImportGlobal) * module->import_global_count
  3132. + sizeof(AOTImportFunc) * module->import_func_count;
  3133. /* func_ptrs and func_type_indexes */
  3134. mem_conspn->functions_size =
  3135. (sizeof(void *) + sizeof(uint32)) * module->func_count;
  3136. mem_conspn->tables_size = sizeof(AOTTable) * module->table_count;
  3137. mem_conspn->memories_size = sizeof(AOTMemory) * module->memory_count;
  3138. mem_conspn->globals_size = sizeof(AOTGlobal) * module->global_count;
  3139. mem_conspn->exports_size = sizeof(AOTExport) * module->export_count;
  3140. mem_conspn->table_segs_size =
  3141. sizeof(AOTTableInitData *) * module->table_init_data_count;
  3142. for (i = 0; i < module->table_init_data_count; i++) {
  3143. AOTTableInitData *init_data = module->table_init_data_list[i];
  3144. size = offsetof(AOTTableInitData, init_values)
  3145. + sizeof(InitializerExpression) * init_data->value_count;
  3146. mem_conspn->table_segs_size += size;
  3147. }
  3148. mem_conspn->data_segs_size =
  3149. sizeof(AOTMemInitData *) * module->mem_init_data_count;
  3150. for (i = 0; i < module->mem_init_data_count; i++) {
  3151. mem_conspn->data_segs_size += sizeof(AOTMemInitData);
  3152. }
  3153. if (module->const_str_set) {
  3154. uint32 const_string_size = 0;
  3155. mem_conspn->const_strs_size =
  3156. bh_hash_map_get_struct_size(module->const_str_set);
  3157. bh_hash_map_traverse(module->const_str_set, const_string_node_size_cb,
  3158. (void *)&const_string_size);
  3159. mem_conspn->const_strs_size += const_string_size;
  3160. }
  3161. /* code size + literal size + object data section size */
  3162. mem_conspn->aot_code_size =
  3163. module->code_size + module->literal_size
  3164. + sizeof(AOTObjectDataSection) * module->data_section_count;
  3165. for (i = 0; i < module->data_section_count; i++) {
  3166. AOTObjectDataSection *obj_data = module->data_sections + i;
  3167. mem_conspn->aot_code_size += sizeof(uint8) * obj_data->size;
  3168. }
  3169. mem_conspn->total_size += mem_conspn->module_struct_size;
  3170. mem_conspn->total_size += mem_conspn->types_size;
  3171. mem_conspn->total_size += mem_conspn->imports_size;
  3172. mem_conspn->total_size += mem_conspn->functions_size;
  3173. mem_conspn->total_size += mem_conspn->tables_size;
  3174. mem_conspn->total_size += mem_conspn->memories_size;
  3175. mem_conspn->total_size += mem_conspn->globals_size;
  3176. mem_conspn->total_size += mem_conspn->exports_size;
  3177. mem_conspn->total_size += mem_conspn->table_segs_size;
  3178. mem_conspn->total_size += mem_conspn->data_segs_size;
  3179. mem_conspn->total_size += mem_conspn->const_strs_size;
  3180. mem_conspn->total_size += mem_conspn->aot_code_size;
  3181. }
  3182. void
  3183. aot_get_module_inst_mem_consumption(const AOTModuleInstance *module_inst,
  3184. WASMModuleInstMemConsumption *mem_conspn)
  3185. {
  3186. AOTTableInstance *tbl_inst;
  3187. uint32 i;
  3188. memset(mem_conspn, 0, sizeof(*mem_conspn));
  3189. mem_conspn->module_inst_struct_size = sizeof(AOTModuleInstance);
  3190. mem_conspn->memories_size =
  3191. sizeof(void *) * module_inst->memory_count
  3192. + sizeof(AOTMemoryInstance) * module_inst->memory_count;
  3193. for (i = 0; i < module_inst->memory_count; i++) {
  3194. AOTMemoryInstance *mem_inst = module_inst->memories[i];
  3195. mem_conspn->memories_size +=
  3196. mem_inst->num_bytes_per_page * mem_inst->cur_page_count;
  3197. mem_conspn->app_heap_size =
  3198. mem_inst->heap_data_end - mem_inst->heap_data;
  3199. /* size of app heap structure */
  3200. mem_conspn->memories_size += mem_allocator_get_heap_struct_size();
  3201. }
  3202. mem_conspn->tables_size +=
  3203. sizeof(AOTTableInstance *) * module_inst->table_count;
  3204. for (i = 0; i < module_inst->table_count; i++) {
  3205. tbl_inst = module_inst->tables[i];
  3206. mem_conspn->tables_size += offsetof(AOTTableInstance, elems);
  3207. mem_conspn->tables_size += sizeof(uint32) * tbl_inst->max_size;
  3208. }
  3209. /* func_ptrs and func_type_indexes */
  3210. mem_conspn->functions_size =
  3211. (sizeof(void *) + sizeof(uint32))
  3212. * (((AOTModule *)module_inst->module)->import_func_count
  3213. + ((AOTModule *)module_inst->module)->func_count);
  3214. mem_conspn->globals_size = module_inst->global_data_size;
  3215. mem_conspn->exports_size =
  3216. sizeof(AOTFunctionInstance) * (uint64)module_inst->export_func_count;
  3217. mem_conspn->total_size += mem_conspn->module_inst_struct_size;
  3218. mem_conspn->total_size += mem_conspn->memories_size;
  3219. mem_conspn->total_size += mem_conspn->functions_size;
  3220. mem_conspn->total_size += mem_conspn->tables_size;
  3221. mem_conspn->total_size += mem_conspn->globals_size;
  3222. mem_conspn->total_size += mem_conspn->exports_size;
  3223. }
  3224. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  3225. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  3226. #if WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0
  3227. void
  3228. aot_drop_table_seg(AOTModuleInstance *module_inst, uint32 tbl_seg_idx)
  3229. {
  3230. bh_bitmap_set_bit(
  3231. ((AOTModuleInstanceExtra *)module_inst->e)->common.elem_dropped,
  3232. tbl_seg_idx);
  3233. }
  3234. void
  3235. aot_table_init(AOTModuleInstance *module_inst, uint32 tbl_idx,
  3236. uint32 tbl_seg_idx, uint32 length, uint32 src_offset,
  3237. uint32 dst_offset)
  3238. {
  3239. AOTTableInstance *tbl_inst;
  3240. AOTTableInitData *tbl_seg;
  3241. const AOTModule *module = (AOTModule *)module_inst->module;
  3242. table_elem_type_t *table_elems;
  3243. InitializerExpression *tbl_seg_init_values = NULL, *init_values;
  3244. uint32 i, tbl_seg_len = 0;
  3245. #if WASM_ENABLE_GC != 0
  3246. void *func_obj;
  3247. #endif
  3248. tbl_inst = module_inst->tables[tbl_idx];
  3249. bh_assert(tbl_inst);
  3250. tbl_seg = module->table_init_data_list[tbl_seg_idx];
  3251. bh_assert(tbl_seg);
  3252. if (!bh_bitmap_get_bit(
  3253. ((AOTModuleInstanceExtra *)module_inst->e)->common.elem_dropped,
  3254. tbl_seg_idx)) {
  3255. /* table segment isn't dropped */
  3256. tbl_seg_init_values = tbl_seg->init_values;
  3257. tbl_seg_len = tbl_seg->value_count;
  3258. }
  3259. if (offset_len_out_of_bounds(src_offset, length, tbl_seg_len)
  3260. || offset_len_out_of_bounds(dst_offset, length, tbl_inst->cur_size)) {
  3261. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3262. return;
  3263. }
  3264. if (!length) {
  3265. return;
  3266. }
  3267. table_elems = tbl_inst->elems + dst_offset;
  3268. init_values = tbl_seg_init_values + src_offset;
  3269. for (i = 0; i < length; i++) {
  3270. #if WASM_ENABLE_GC != 0
  3271. /* UINT32_MAX indicates that it is a null ref */
  3272. if (init_values[i].u.ref_index != UINT32_MAX) {
  3273. if (!(func_obj = aot_create_func_obj(module_inst,
  3274. init_values[i].u.ref_index,
  3275. true, NULL, 0))) {
  3276. aot_set_exception_with_id(module_inst, EXCE_NULL_FUNC_OBJ);
  3277. return;
  3278. }
  3279. table_elems[i] = func_obj;
  3280. }
  3281. else {
  3282. table_elems[i] = NULL_REF;
  3283. }
  3284. #else
  3285. table_elems[i] = init_values[i].u.ref_index;
  3286. #endif
  3287. }
  3288. }
  3289. void
  3290. aot_table_copy(AOTModuleInstance *module_inst, uint32 src_tbl_idx,
  3291. uint32 dst_tbl_idx, uint32 length, uint32 src_offset,
  3292. uint32 dst_offset)
  3293. {
  3294. AOTTableInstance *src_tbl_inst, *dst_tbl_inst;
  3295. src_tbl_inst = module_inst->tables[src_tbl_idx];
  3296. bh_assert(src_tbl_inst);
  3297. dst_tbl_inst = module_inst->tables[dst_tbl_idx];
  3298. bh_assert(dst_tbl_inst);
  3299. if (offset_len_out_of_bounds(dst_offset, length, dst_tbl_inst->cur_size)
  3300. || offset_len_out_of_bounds(src_offset, length,
  3301. src_tbl_inst->cur_size)) {
  3302. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3303. return;
  3304. }
  3305. /* if src_offset >= dst_offset, copy from front to back */
  3306. /* if src_offset < dst_offset, copy from back to front */
  3307. /* merge all together */
  3308. bh_memmove_s((uint8 *)dst_tbl_inst + offsetof(AOTTableInstance, elems)
  3309. + dst_offset * sizeof(table_elem_type_t),
  3310. (dst_tbl_inst->cur_size - dst_offset)
  3311. * sizeof(table_elem_type_t),
  3312. (uint8 *)src_tbl_inst + offsetof(AOTTableInstance, elems)
  3313. + src_offset * sizeof(table_elem_type_t),
  3314. length * sizeof(table_elem_type_t));
  3315. }
  3316. void
  3317. aot_table_fill(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 length,
  3318. table_elem_type_t val, uint32 data_offset)
  3319. {
  3320. AOTTableInstance *tbl_inst;
  3321. tbl_inst = module_inst->tables[tbl_idx];
  3322. bh_assert(tbl_inst);
  3323. if (offset_len_out_of_bounds(data_offset, length, tbl_inst->cur_size)) {
  3324. aot_set_exception_with_id(module_inst, EXCE_OUT_OF_BOUNDS_TABLE_ACCESS);
  3325. return;
  3326. }
  3327. for (; length != 0; data_offset++, length--) {
  3328. tbl_inst->elems[data_offset] = val;
  3329. }
  3330. }
  3331. uint32
  3332. aot_table_grow(AOTModuleInstance *module_inst, uint32 tbl_idx, uint32 inc_size,
  3333. table_elem_type_t init_val)
  3334. {
  3335. AOTTableInstance *tbl_inst;
  3336. uint32 i, orig_size, total_size;
  3337. tbl_inst = module_inst->tables[tbl_idx];
  3338. if (!tbl_inst) {
  3339. return (uint32)-1;
  3340. }
  3341. orig_size = tbl_inst->cur_size;
  3342. if (!inc_size) {
  3343. return orig_size;
  3344. }
  3345. if (tbl_inst->cur_size > UINT32_MAX - inc_size) {
  3346. #if WASM_ENABLE_SPEC_TEST == 0
  3347. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  3348. ") failed because of integer overflow",
  3349. tbl_inst->cur_size, inc_size);
  3350. #endif
  3351. return (uint32)-1;
  3352. }
  3353. total_size = tbl_inst->cur_size + inc_size;
  3354. if (total_size > tbl_inst->max_size) {
  3355. #if WASM_ENABLE_SPEC_TEST == 0
  3356. LOG_WARNING("table grow (%" PRIu32 "-> %" PRIu32
  3357. ") failed because of over max size",
  3358. tbl_inst->cur_size, inc_size);
  3359. #endif
  3360. return (uint32)-1;
  3361. }
  3362. /* fill in */
  3363. for (i = 0; i < inc_size; ++i) {
  3364. tbl_inst->elems[tbl_inst->cur_size + i] = init_val;
  3365. }
  3366. tbl_inst->cur_size = total_size;
  3367. return orig_size;
  3368. }
  3369. #endif /* WASM_ENABLE_REF_TYPES != 0 || WASM_ENABLE_GC != 0 */
  3370. #if WASM_ENABLE_AOT_STACK_FRAME != 0
  3371. #if WASM_ENABLE_DUMP_CALL_STACK != 0 || WASM_ENABLE_PERF_PROFILING != 0
  3372. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  3373. static const char *
  3374. lookup_func_name(const char **func_names, uint32 *func_indexes,
  3375. uint32 func_index_count, uint32 func_index)
  3376. {
  3377. int64 low = 0, mid;
  3378. int64 high = func_index_count - 1;
  3379. if (!func_names || !func_indexes || func_index_count == 0)
  3380. return NULL;
  3381. while (low <= high) {
  3382. mid = (low + high) / 2;
  3383. if (func_index == func_indexes[mid]) {
  3384. return func_names[mid];
  3385. }
  3386. else if (func_index < func_indexes[mid])
  3387. high = mid - 1;
  3388. else
  3389. low = mid + 1;
  3390. }
  3391. return NULL;
  3392. }
  3393. #endif /* WASM_ENABLE_CUSTOM_NAME_SECTION != 0 */
  3394. static const char *
  3395. get_func_name_from_index(const AOTModuleInstance *module_inst,
  3396. uint32 func_index)
  3397. {
  3398. const char *func_name = NULL;
  3399. AOTModule *module = (AOTModule *)module_inst->module;
  3400. #if WASM_ENABLE_CUSTOM_NAME_SECTION != 0
  3401. if ((func_name =
  3402. lookup_func_name(module->aux_func_names, module->aux_func_indexes,
  3403. module->aux_func_name_count, func_index))) {
  3404. return func_name;
  3405. }
  3406. #endif
  3407. if (func_index < module->import_func_count) {
  3408. func_name = module->import_funcs[func_index].func_name;
  3409. }
  3410. else {
  3411. uint32 i;
  3412. for (i = 0; i < module->export_count; i++) {
  3413. AOTExport export = module->exports[i];
  3414. if (export.index == func_index && export.kind == EXPORT_KIND_FUNC) {
  3415. func_name = export.name;
  3416. break;
  3417. }
  3418. }
  3419. }
  3420. return func_name;
  3421. }
  3422. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 || \
  3423. WASM_ENABLE_PERF_PROFILING != 0 */
  3424. #if WASM_ENABLE_GC == 0
  3425. static bool
  3426. aot_alloc_standard_frame(WASMExecEnv *exec_env, uint32 func_index)
  3427. {
  3428. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3429. #if WASM_ENABLE_PERF_PROFILING != 0
  3430. AOTFuncPerfProfInfo *func_perf_prof =
  3431. module_inst->func_perf_profilings + func_index;
  3432. #endif
  3433. AOTFrame *cur_frame, *frame;
  3434. uint32 size = (uint32)offsetof(AOTFrame, lp);
  3435. cur_frame = (AOTFrame *)exec_env->cur_frame;
  3436. if (!cur_frame)
  3437. frame = (AOTFrame *)exec_env->wasm_stack.bottom;
  3438. else
  3439. frame = (AOTFrame *)((uint8 *)cur_frame + size);
  3440. if ((uint8 *)frame + size > exec_env->wasm_stack.top_boundary) {
  3441. aot_set_exception(module_inst, "wasm operand stack overflow");
  3442. return false;
  3443. }
  3444. frame->func_index = func_index;
  3445. /* No need to initialize ip, it will be committed in jitted code
  3446. when needed */
  3447. /* frame->ip = NULL; */
  3448. frame->prev_frame = (AOTFrame *)exec_env->cur_frame;
  3449. #if WASM_ENABLE_PERF_PROFILING != 0
  3450. frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3451. frame->func_perf_prof_info = func_perf_prof;
  3452. #endif
  3453. #if WASM_ENABLE_MEMORY_PROFILING != 0
  3454. {
  3455. uint32 wasm_stack_used =
  3456. (uint8 *)frame + size - exec_env->wasm_stack.bottom;
  3457. if (wasm_stack_used > exec_env->max_wasm_stack_used)
  3458. exec_env->max_wasm_stack_used = wasm_stack_used;
  3459. }
  3460. #endif
  3461. exec_env->cur_frame = (struct WASMInterpFrame *)frame;
  3462. return true;
  3463. }
  3464. #else /* else of WASM_ENABLE_GC == 0 */
  3465. static bool
  3466. aot_alloc_standard_frame(WASMExecEnv *exec_env, uint32 func_index)
  3467. {
  3468. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3469. AOTModule *module = (AOTModule *)module_inst->module;
  3470. #if WASM_ENABLE_PERF_PROFILING != 0
  3471. AOTFuncPerfProfInfo *func_perf_prof =
  3472. module_inst->func_perf_profilings + func_index;
  3473. #endif
  3474. AOTFrame *frame;
  3475. uint32 max_local_cell_num, max_stack_cell_num, all_cell_num;
  3476. uint32 aot_func_idx, frame_size;
  3477. if (func_index >= module->import_func_count) {
  3478. aot_func_idx = func_index - module->import_func_count;
  3479. max_local_cell_num = module->max_local_cell_nums[aot_func_idx];
  3480. max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx];
  3481. }
  3482. else {
  3483. AOTFuncType *func_type = module->import_funcs[func_index].func_type;
  3484. max_local_cell_num =
  3485. func_type->param_cell_num > 2 ? func_type->param_cell_num : 2;
  3486. max_stack_cell_num = 0;
  3487. }
  3488. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3489. #if WASM_ENABLE_GC == 0
  3490. frame_size = (uint32)offsetof(AOTFrame, lp) + all_cell_num * 4;
  3491. #else
  3492. frame_size =
  3493. (uint32)offsetof(AOTFrame, lp) + align_uint(all_cell_num * 5, 4);
  3494. #endif
  3495. frame = wasm_exec_env_alloc_wasm_frame(exec_env, frame_size);
  3496. if (!frame) {
  3497. aot_set_exception(module_inst, "wasm operand stack overflow");
  3498. return false;
  3499. }
  3500. #if WASM_ENABLE_PERF_PROFILING != 0
  3501. frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3502. frame->func_perf_prof_info = func_perf_prof;
  3503. #endif
  3504. #if WASM_ENABLE_GC != 0
  3505. frame->sp = frame->lp + max_local_cell_num;
  3506. frame->frame_ref = (uint8 *)(frame->sp + max_stack_cell_num);
  3507. #endif
  3508. frame->prev_frame = (AOTFrame *)exec_env->cur_frame;
  3509. exec_env->cur_frame = (struct WASMInterpFrame *)frame;
  3510. frame->func_index = func_index;
  3511. return true;
  3512. }
  3513. #endif /* end of WASM_ENABLE_GC == 0 */
  3514. static bool
  3515. aot_alloc_tiny_frame(WASMExecEnv *exec_env, uint32 func_index)
  3516. {
  3517. AOTTinyFrame *new_frame = (AOTTinyFrame *)exec_env->wasm_stack.top;
  3518. if ((uint8 *)new_frame > exec_env->wasm_stack.top_boundary) {
  3519. aot_set_exception((WASMModuleInstance *)exec_env->module_inst,
  3520. "wasm operand stack overflow");
  3521. return false;
  3522. }
  3523. new_frame->func_index = func_index;
  3524. exec_env->wasm_stack.top += sizeof(AOTTinyFrame);
  3525. return true;
  3526. }
  3527. bool
  3528. aot_alloc_frame(WASMExecEnv *exec_env, uint32 func_index)
  3529. {
  3530. AOTModule *module =
  3531. (AOTModule *)((AOTModuleInstance *)exec_env->module_inst)->module;
  3532. if (is_frame_per_function(exec_env)
  3533. && func_index >= module->import_func_count) {
  3534. /* in frame per function mode the frame is allocated at
  3535. the beginning of each frame, so we only need to allocate
  3536. the frame for imported functions */
  3537. return true;
  3538. }
  3539. if (is_tiny_frame(exec_env)) {
  3540. return aot_alloc_tiny_frame(exec_env, func_index);
  3541. }
  3542. else {
  3543. return aot_alloc_standard_frame(exec_env, func_index);
  3544. }
  3545. }
  3546. static inline void
  3547. aot_free_standard_frame(WASMExecEnv *exec_env)
  3548. {
  3549. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  3550. AOTFrame *prev_frame = (AOTFrame *)cur_frame->prev_frame;
  3551. #if WASM_ENABLE_PERF_PROFILING != 0
  3552. uint64 time_elapsed =
  3553. (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started;
  3554. cur_frame->func_perf_prof_info->total_exec_time += time_elapsed;
  3555. cur_frame->func_perf_prof_info->total_exec_cnt++;
  3556. /* parent function */
  3557. if (prev_frame)
  3558. prev_frame->func_perf_prof_info->children_exec_time += time_elapsed;
  3559. #endif
  3560. #if WASM_ENABLE_GC != 0
  3561. wasm_exec_env_free_wasm_frame(exec_env, cur_frame);
  3562. #endif
  3563. exec_env->cur_frame = (struct WASMInterpFrame *)prev_frame;
  3564. }
  3565. static inline void
  3566. aot_free_tiny_frame(WASMExecEnv *exec_env)
  3567. {
  3568. exec_env->wasm_stack.top =
  3569. get_prev_frame(exec_env, exec_env->wasm_stack.top);
  3570. }
  3571. void
  3572. aot_free_frame(WASMExecEnv *exec_env)
  3573. {
  3574. if (is_tiny_frame(exec_env)) {
  3575. aot_free_tiny_frame(exec_env);
  3576. }
  3577. else {
  3578. aot_free_standard_frame(exec_env);
  3579. }
  3580. }
  3581. void
  3582. aot_frame_update_profile_info(WASMExecEnv *exec_env, bool alloc_frame)
  3583. {
  3584. #if WASM_ENABLE_PERF_PROFILING != 0
  3585. AOTFrame *cur_frame = (AOTFrame *)exec_env->cur_frame;
  3586. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3587. AOTFuncPerfProfInfo *func_perf_prof =
  3588. module_inst->func_perf_profilings + cur_frame->func_index;
  3589. if (alloc_frame) {
  3590. cur_frame->time_started = (uintptr_t)os_time_thread_cputime_us();
  3591. cur_frame->func_perf_prof_info = func_perf_prof;
  3592. }
  3593. else {
  3594. AOTFrame *prev_frame = cur_frame->prev_frame;
  3595. uint64 time_elapsed =
  3596. (uintptr_t)os_time_thread_cputime_us() - cur_frame->time_started;
  3597. cur_frame->func_perf_prof_info->total_exec_time += time_elapsed;
  3598. cur_frame->func_perf_prof_info->total_exec_cnt++;
  3599. /* parent function */
  3600. if (prev_frame)
  3601. prev_frame->func_perf_prof_info->children_exec_time += time_elapsed;
  3602. }
  3603. #endif
  3604. #if WASM_ENABLE_MEMORY_PROFILING != 0
  3605. if (alloc_frame) {
  3606. #if WASM_ENABLE_GC == 0
  3607. uint32 wasm_stack_used = (uint8 *)exec_env->cur_frame
  3608. + (uint32)offsetof(AOTFrame, lp)
  3609. - exec_env->wasm_stack.bottom;
  3610. #else
  3611. uint32 wasm_stack_used =
  3612. exec_env->wasm_stack.top - exec_env->wasm_stack.bottom;
  3613. #endif
  3614. if (wasm_stack_used > exec_env->max_wasm_stack_used)
  3615. exec_env->max_wasm_stack_used = wasm_stack_used;
  3616. }
  3617. #endif
  3618. }
  3619. #endif /* end of WASM_ENABLE_AOT_STACK_FRAME != 0 */
  3620. #if WAMR_ENABLE_COPY_CALLSTACK != 0
  3621. uint32
  3622. aot_copy_callstack_tiny_frame(WASMExecEnv *exec_env, wasm_frame_t *buffer,
  3623. const uint32 length, const uint32 skip_n,
  3624. char *error_buf, uint32 error_buf_size)
  3625. {
  3626. /*
  3627. * Note for devs: please refrain from such modifications inside of
  3628. * aot_copy_callstack_tiny_frame
  3629. * - any allocations/freeing memory
  3630. * - dereferencing any pointers other than: exec_env, exec_env->module_inst,
  3631. * exec_env->module_inst->module, pointers between stack's bottom and
  3632. * top_boundary For more details check wasm_copy_callstack in
  3633. * wasm_export.h
  3634. */
  3635. uint8 *top_boundary = exec_env->wasm_stack.top_boundary;
  3636. uint8 *top = exec_env->wasm_stack.top;
  3637. uint8 *bottom = exec_env->wasm_stack.bottom;
  3638. uint32 count = 0;
  3639. bool is_top_index_in_range =
  3640. top_boundary >= top && top >= (bottom + sizeof(AOTTinyFrame));
  3641. if (!is_top_index_in_range) {
  3642. char *err_msg =
  3643. "Top of the stack pointer is outside of the stack boundaries";
  3644. strncpy(error_buf, err_msg, error_buf_size);
  3645. return 0;
  3646. }
  3647. bool is_top_aligned_with_bottom =
  3648. (unsigned long)(top - bottom) % sizeof(AOTTinyFrame) == 0;
  3649. if (!is_top_aligned_with_bottom) {
  3650. char *err_msg = "Top of the stack is not aligned with the bottom";
  3651. strncpy(error_buf, err_msg, error_buf_size);
  3652. return 0;
  3653. }
  3654. AOTTinyFrame *frame = (AOTTinyFrame *)(top - sizeof(AOTTinyFrame));
  3655. WASMCApiFrame record_frame;
  3656. while (frame && (uint8_t *)frame >= bottom && count < (skip_n + length)) {
  3657. if (count < skip_n) {
  3658. ++count;
  3659. frame -= 1;
  3660. continue;
  3661. }
  3662. record_frame.instance = exec_env->module_inst;
  3663. record_frame.module_offset = 0;
  3664. record_frame.func_index = frame->func_index;
  3665. record_frame.func_offset = frame->ip_offset;
  3666. buffer[count - skip_n] = record_frame;
  3667. frame -= 1;
  3668. ++count;
  3669. }
  3670. return count >= skip_n ? count - skip_n : 0;
  3671. }
  3672. uint32
  3673. aot_copy_callstack_standard_frame(WASMExecEnv *exec_env, wasm_frame_t *buffer,
  3674. const uint32 length, const uint32 skip_n,
  3675. char *error_buf, uint32_t error_buf_size)
  3676. {
  3677. /*
  3678. * Note for devs: please refrain from such modifications inside of
  3679. * aot_iterate_callstack_standard_frame
  3680. * - any allocations/freeing memory
  3681. * - dereferencing any pointers other than: exec_env, exec_env->module_inst,
  3682. * exec_env->module_inst->module, pointers between stack's bottom and
  3683. * top_boundary For more details check wasm_iterate_callstack in
  3684. * wasm_export.h
  3685. */
  3686. uint32 count = 0;
  3687. #if WASM_ENABLE_GC == 0
  3688. WASMModuleInstance *module_inst =
  3689. (WASMModuleInstance *)wasm_exec_env_get_module_inst(exec_env);
  3690. AOTFrame *cur_frame = (AOTFrame *)wasm_exec_env_get_cur_frame(exec_env);
  3691. uint8 *top_boundary = exec_env->wasm_stack.top_boundary;
  3692. uint8 *bottom = exec_env->wasm_stack.bottom;
  3693. uint32 frame_size = (uint32)offsetof(AOTFrame, lp);
  3694. WASMCApiFrame record_frame;
  3695. while (cur_frame && (uint8_t *)cur_frame >= bottom
  3696. && (uint8_t *)cur_frame + frame_size <= top_boundary
  3697. && count < (skip_n + length)) {
  3698. if (count < skip_n) {
  3699. ++count;
  3700. cur_frame = cur_frame->prev_frame;
  3701. continue;
  3702. }
  3703. record_frame.instance = module_inst;
  3704. record_frame.module_offset = 0;
  3705. record_frame.func_index = (uint32)cur_frame->func_index;
  3706. record_frame.func_offset = (uint32)cur_frame->ip_offset;
  3707. buffer[count - skip_n] = record_frame;
  3708. cur_frame = cur_frame->prev_frame;
  3709. ++count;
  3710. }
  3711. #else
  3712. /*
  3713. * TODO: add support for standard frames when GC is enabled
  3714. * now it poses a risk due to variable size of the frame
  3715. */
  3716. #endif
  3717. return count >= skip_n ? count - skip_n : 0;
  3718. }
  3719. uint32
  3720. aot_copy_callstack(WASMExecEnv *exec_env, wasm_frame_t *buffer,
  3721. const uint32 length, const uint32 skip_n, char *error_buf,
  3722. uint32_t error_buf_size)
  3723. {
  3724. /*
  3725. * Note for devs: please refrain from such modifications inside of
  3726. * aot_iterate_callstack
  3727. * - any allocations/freeing memory
  3728. * - dereferencing any pointers other than: exec_env, exec_env->module_inst,
  3729. * exec_env->module_inst->module, pointers between stack's bottom and
  3730. * top_boundary For more details check wasm_iterate_callstack in
  3731. * wasm_export.h
  3732. */
  3733. if (!is_tiny_frame(exec_env)) {
  3734. return aot_copy_callstack_standard_frame(
  3735. exec_env, buffer, length, skip_n, error_buf, error_buf_size);
  3736. }
  3737. else {
  3738. return aot_copy_callstack_tiny_frame(exec_env, buffer, length, skip_n,
  3739. error_buf, error_buf_size);
  3740. }
  3741. }
  3742. #endif // WAMR_ENABLE_COPY_CALLSTACK
  3743. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  3744. bool
  3745. aot_create_call_stack(struct WASMExecEnv *exec_env)
  3746. {
  3747. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3748. AOTModule *module = (AOTModule *)module_inst->module;
  3749. uint32 n = 0;
  3750. void *top_frame = get_top_frame(exec_env);
  3751. while (top_frame) {
  3752. top_frame = get_prev_frame(exec_env, top_frame);
  3753. n++;
  3754. }
  3755. /* release previous stack frames and create new ones */
  3756. destroy_c_api_frames(module_inst->frames);
  3757. if (!bh_vector_init(module_inst->frames, n, sizeof(WASMCApiFrame), false)) {
  3758. return false;
  3759. }
  3760. top_frame = get_top_frame(exec_env);
  3761. while (n-- > 0) {
  3762. uint32 func_index, ip_offset;
  3763. uint32 *lp = NULL;
  3764. #if WASM_ENABLE_GC != 0
  3765. uint32 *sp = NULL;
  3766. uint8 *frame_ref = NULL;
  3767. #endif
  3768. if (is_tiny_frame(exec_env)) {
  3769. AOTTinyFrame *frame = (AOTTinyFrame *)top_frame;
  3770. func_index = (uint32)frame->func_index;
  3771. ip_offset = (uint32)frame->ip_offset;
  3772. }
  3773. else {
  3774. AOTFrame *frame = (AOTFrame *)top_frame;
  3775. func_index = (uint32)frame->func_index;
  3776. ip_offset = (uint32)frame->ip_offset;
  3777. lp = frame->lp;
  3778. #if WASM_ENABLE_GC != 0
  3779. sp = frame->sp;
  3780. frame_ref = frame->frame_ref;
  3781. #endif
  3782. }
  3783. WASMCApiFrame frame = { 0 };
  3784. uint32 max_local_cell_num = 0, max_stack_cell_num = 0;
  3785. uint32 all_cell_num, lp_size;
  3786. frame.instance = module_inst;
  3787. frame.module_offset = 0;
  3788. frame.func_index = func_index;
  3789. frame.func_offset = ip_offset;
  3790. frame.func_name_wp = get_func_name_from_index(module_inst, func_index);
  3791. if (!is_frame_func_idx_disabled(exec_env)) {
  3792. if (func_index >= module->import_func_count) {
  3793. uint32 aot_func_idx = func_index - module->import_func_count;
  3794. max_local_cell_num = module->max_local_cell_nums[aot_func_idx];
  3795. max_stack_cell_num = module->max_stack_cell_nums[aot_func_idx];
  3796. }
  3797. else {
  3798. AOTFuncType *func_type =
  3799. module->import_funcs[func_index].func_type;
  3800. max_local_cell_num = func_type->param_cell_num > 2
  3801. ? func_type->param_cell_num
  3802. : 2;
  3803. max_stack_cell_num = 0;
  3804. }
  3805. }
  3806. all_cell_num = max_local_cell_num + max_stack_cell_num;
  3807. #if WASM_ENABLE_GC == 0
  3808. lp_size = all_cell_num * 4;
  3809. #else
  3810. lp_size = align_uint(all_cell_num * 5, 4);
  3811. #endif
  3812. if (lp_size > 0 && !is_tiny_frame(exec_env)) {
  3813. if (!(frame.lp = wasm_runtime_malloc(lp_size))) {
  3814. destroy_c_api_frames(module_inst->frames);
  3815. return false;
  3816. }
  3817. bh_memcpy_s(frame.lp, lp_size, lp, lp_size);
  3818. #if WASM_ENABLE_GC != 0
  3819. uint32 local_ref_flags_cell_num =
  3820. module->func_local_ref_flags[frame.func_index]
  3821. .local_ref_flag_cell_num;
  3822. uint8 *local_ref_flags =
  3823. module->func_local_ref_flags[frame.func_index].local_ref_flags;
  3824. frame.sp = frame.lp + (sp - lp);
  3825. frame.frame_ref = (uint8 *)frame.lp + (frame_ref - (uint8 *)lp);
  3826. /* copy local ref flags from AOT module */
  3827. bh_memcpy_s(frame.frame_ref, local_ref_flags_cell_num,
  3828. local_ref_flags, lp_size);
  3829. #endif
  3830. }
  3831. if (!bh_vector_append(module_inst->frames, &frame)) {
  3832. if (frame.lp)
  3833. wasm_runtime_free(frame.lp);
  3834. destroy_c_api_frames(module_inst->frames);
  3835. return false;
  3836. }
  3837. top_frame = get_prev_frame(exec_env, top_frame);
  3838. }
  3839. return true;
  3840. }
  3841. #define PRINT_OR_DUMP() \
  3842. do { \
  3843. total_len += \
  3844. wasm_runtime_dump_line_buf_impl(line_buf, print, &buf, &len); \
  3845. if ((!print) && buf && (len == 0)) { \
  3846. exception_unlock(module_inst); \
  3847. return total_len; \
  3848. } \
  3849. } while (0)
  3850. uint32
  3851. aot_dump_call_stack(WASMExecEnv *exec_env, bool print, char *buf, uint32 len)
  3852. {
  3853. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  3854. uint32 n = 0, total_len = 0, total_frames;
  3855. /* reserve 256 bytes for line buffer, any line longer than 256 bytes
  3856. * will be truncated */
  3857. char line_buf[256];
  3858. if (!module_inst->frames) {
  3859. return 0;
  3860. }
  3861. total_frames = (uint32)bh_vector_size(module_inst->frames);
  3862. if (total_frames == 0) {
  3863. return 0;
  3864. }
  3865. exception_lock(module_inst);
  3866. snprintf(line_buf, sizeof(line_buf), "\n");
  3867. PRINT_OR_DUMP();
  3868. while (n < total_frames) {
  3869. WASMCApiFrame frame = { 0 };
  3870. uint32 line_length, i;
  3871. if (!bh_vector_get(module_inst->frames, n, &frame)) {
  3872. exception_unlock(module_inst);
  3873. return 0;
  3874. }
  3875. /* function name not exported, print number instead */
  3876. if (frame.func_name_wp == NULL) {
  3877. line_length = snprintf(line_buf, sizeof(line_buf),
  3878. "#%02" PRIu32 ": 0x%04x - $f%" PRIu32 "\n",
  3879. n, frame.func_offset, frame.func_index);
  3880. }
  3881. else {
  3882. line_length = snprintf(line_buf, sizeof(line_buf),
  3883. "#%02" PRIu32 ": 0x%04x - %s\n", n,
  3884. frame.func_offset, frame.func_name_wp);
  3885. }
  3886. if (line_length >= sizeof(line_buf)) {
  3887. uint32 line_buffer_len = sizeof(line_buf);
  3888. /* If line too long, ensure the last character is '\n' */
  3889. for (i = line_buffer_len - 5; i < line_buffer_len - 2; i++) {
  3890. line_buf[i] = '.';
  3891. }
  3892. line_buf[line_buffer_len - 2] = '\n';
  3893. }
  3894. PRINT_OR_DUMP();
  3895. n++;
  3896. }
  3897. snprintf(line_buf, sizeof(line_buf), "\n");
  3898. PRINT_OR_DUMP();
  3899. exception_unlock(module_inst);
  3900. return total_len + 1;
  3901. }
  3902. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK != 0 */
  3903. #if WASM_ENABLE_PERF_PROFILING != 0
  3904. void
  3905. aot_dump_perf_profiling(const AOTModuleInstance *module_inst)
  3906. {
  3907. AOTFuncPerfProfInfo *perf_prof =
  3908. (AOTFuncPerfProfInfo *)module_inst->func_perf_profilings;
  3909. AOTModule *module = (AOTModule *)module_inst->module;
  3910. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3911. const char *func_name;
  3912. os_printf("Performance profiler data:\n");
  3913. for (i = 0; i < total_func_count; i++, perf_prof++) {
  3914. if (perf_prof->total_exec_cnt == 0)
  3915. continue;
  3916. func_name = get_func_name_from_index(module_inst, i);
  3917. if (func_name)
  3918. os_printf(
  3919. " func %s, execution time: %.3f ms, execution count: %" PRIu32
  3920. " times, children execution time: %.3f ms\n",
  3921. func_name, perf_prof->total_exec_time / 1000.0f,
  3922. perf_prof->total_exec_cnt,
  3923. perf_prof->children_exec_time / 1000.0f);
  3924. else
  3925. os_printf(" func %" PRIu32
  3926. ", execution time: %.3f ms, execution count: %" PRIu32
  3927. " times, children execution time: %.3f ms\n",
  3928. i, perf_prof->total_exec_time / 1000.0f,
  3929. perf_prof->total_exec_cnt,
  3930. perf_prof->children_exec_time / 1000.0f);
  3931. }
  3932. }
  3933. double
  3934. aot_summarize_wasm_execute_time(const AOTModuleInstance *inst)
  3935. {
  3936. double ret = 0;
  3937. AOTModule *module = (AOTModule *)inst->module;
  3938. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3939. for (i = 0; i < total_func_count; i++) {
  3940. AOTFuncPerfProfInfo *perf_prof =
  3941. (AOTFuncPerfProfInfo *)inst->func_perf_profilings + i;
  3942. ret += (perf_prof->total_exec_time - perf_prof->children_exec_time)
  3943. / 1000.0f;
  3944. }
  3945. return ret;
  3946. }
  3947. double
  3948. aot_get_wasm_func_exec_time(const AOTModuleInstance *inst,
  3949. const char *func_name)
  3950. {
  3951. AOTModule *module = (AOTModule *)inst->module;
  3952. uint32 total_func_count = module->import_func_count + module->func_count, i;
  3953. for (i = 0; i < total_func_count; i++) {
  3954. const char *name_in_wasm = get_func_name_from_index(inst, i);
  3955. if (name_in_wasm && strcmp(func_name, name_in_wasm) == 0) {
  3956. AOTFuncPerfProfInfo *perf_prof =
  3957. (AOTFuncPerfProfInfo *)inst->func_perf_profilings + i;
  3958. return (perf_prof->total_exec_time - perf_prof->children_exec_time)
  3959. / 1000.0f;
  3960. }
  3961. }
  3962. return -1.0;
  3963. }
  3964. #endif /* end of WASM_ENABLE_PERF_PROFILING != 0 */
  3965. #if WASM_ENABLE_STATIC_PGO != 0
  3966. /* indirect call target */
  3967. #define IPVK_IndirectCallTarget 0
  3968. /* memory intrinsic functions size */
  3969. #define IPVK_MemOPSize 1
  3970. #define IPVK_First IPVK_IndirectCallTarget
  3971. #define IPVK_Last IPVK_MemOPSize
  3972. #define INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE 24
  3973. #define INSTR_PROF_MAX_NUM_VAL_PER_SITE 255
  3974. static int hasNonDefaultValsPerSite = 0;
  3975. static uint32 VPMaxNumValsPerSite = INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE;
  3976. static bool
  3977. cmpxchg_ptr(void **ptr, void *old_val, void *new_val)
  3978. {
  3979. #if defined(os_atomic_cmpxchg)
  3980. return os_atomic_cmpxchg(ptr, &old_val, new_val);
  3981. #else
  3982. /* TODO: add lock when thread-manager is enabled */
  3983. void *read = *ptr;
  3984. if (read == old_val) {
  3985. *ptr = new_val;
  3986. return true;
  3987. }
  3988. return false;
  3989. #endif
  3990. }
  3991. static int
  3992. allocateValueProfileCounters(LLVMProfileData *Data)
  3993. {
  3994. ValueProfNode **Mem;
  3995. uint64 NumVSites = 0, total_size;
  3996. uint32 VKI;
  3997. /* When dynamic allocation is enabled, allow tracking the max number of
  3998. values allowed. */
  3999. if (!hasNonDefaultValsPerSite)
  4000. VPMaxNumValsPerSite = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
  4001. for (VKI = IPVK_First; VKI <= IPVK_Last; ++VKI)
  4002. NumVSites += Data->num_value_sites[VKI];
  4003. /* If NumVSites = 0, calloc is allowed to return a non-null pointer. */
  4004. bh_assert(NumVSites > 0 && "NumVSites can't be zero");
  4005. total_size = (uint64)sizeof(ValueProfNode *) * NumVSites;
  4006. if (total_size > UINT32_MAX
  4007. || !(Mem = (ValueProfNode **)wasm_runtime_malloc((uint32)total_size))) {
  4008. return 0;
  4009. }
  4010. memset(Mem, 0, (uint32)total_size);
  4011. if (!cmpxchg_ptr((void **)&Data->values, NULL, Mem)) {
  4012. wasm_runtime_free(Mem);
  4013. return 0;
  4014. }
  4015. return 1;
  4016. }
  4017. static ValueProfNode *
  4018. allocateOneNode(void)
  4019. {
  4020. ValueProfNode *Node;
  4021. Node = wasm_runtime_malloc((uint32)sizeof(ValueProfNode));
  4022. if (Node)
  4023. memset(Node, 0, sizeof(ValueProfNode));
  4024. return Node;
  4025. }
  4026. static void
  4027. instrumentTargetValueImpl(uint64 TargetValue, void *Data, uint32 CounterIndex,
  4028. uint64 CountValue)
  4029. {
  4030. ValueProfNode **ValueCounters;
  4031. ValueProfNode *PrevVNode = NULL, *MinCountVNode = NULL, *CurVNode;
  4032. LLVMProfileData *PData = (LLVMProfileData *)Data;
  4033. uint64 MinCount = UINT64_MAX;
  4034. uint8 VDataCount = 0;
  4035. bool success = false;
  4036. if (!PData)
  4037. return;
  4038. if (!CountValue)
  4039. return;
  4040. if (!PData->values) {
  4041. if (!allocateValueProfileCounters(PData))
  4042. return;
  4043. }
  4044. ValueCounters = (ValueProfNode **)PData->values;
  4045. CurVNode = ValueCounters[CounterIndex];
  4046. while (CurVNode) {
  4047. if (TargetValue == CurVNode->value) {
  4048. CurVNode->count += CountValue;
  4049. return;
  4050. }
  4051. if (CurVNode->count < MinCount) {
  4052. MinCount = CurVNode->count;
  4053. MinCountVNode = CurVNode;
  4054. }
  4055. PrevVNode = CurVNode;
  4056. CurVNode = CurVNode->next;
  4057. ++VDataCount;
  4058. }
  4059. if (VDataCount >= VPMaxNumValsPerSite) {
  4060. if (MinCountVNode->count <= CountValue) {
  4061. CurVNode = MinCountVNode;
  4062. CurVNode->value = TargetValue;
  4063. CurVNode->count = CountValue;
  4064. }
  4065. else
  4066. MinCountVNode->count -= CountValue;
  4067. return;
  4068. }
  4069. CurVNode = allocateOneNode();
  4070. if (!CurVNode)
  4071. return;
  4072. CurVNode->value = TargetValue;
  4073. CurVNode->count += CountValue;
  4074. if (!ValueCounters[CounterIndex]) {
  4075. success =
  4076. cmpxchg_ptr((void **)&ValueCounters[CounterIndex], NULL, CurVNode);
  4077. }
  4078. else if (PrevVNode && !PrevVNode->next) {
  4079. success = cmpxchg_ptr((void **)&PrevVNode->next, 0, CurVNode);
  4080. }
  4081. if (!success) {
  4082. wasm_runtime_free(CurVNode);
  4083. }
  4084. }
  4085. void
  4086. llvm_profile_instrument_target(uint64 target_value, void *data,
  4087. uint32 counter_idx)
  4088. {
  4089. instrumentTargetValueImpl(target_value, data, counter_idx, 1);
  4090. }
  4091. static inline uint32
  4092. popcount64(uint64 u)
  4093. {
  4094. uint32 ret = 0;
  4095. while (u) {
  4096. u = (u & (u - 1));
  4097. ret++;
  4098. }
  4099. return ret;
  4100. }
  4101. static inline uint32
  4102. clz64(uint64 type)
  4103. {
  4104. uint32 num = 0;
  4105. if (type == 0)
  4106. return 64;
  4107. while (!(type & 0x8000000000000000LL)) {
  4108. num++;
  4109. type <<= 1;
  4110. }
  4111. return num;
  4112. }
  4113. /* Map an (observed) memop size value to the representative value of its range.
  4114. For example, 5 -> 5, 22 -> 17, 99 -> 65, 256 -> 256, 1001 -> 513. */
  4115. static uint64
  4116. InstrProfGetRangeRepValue(uint64 Value)
  4117. {
  4118. if (Value <= 8)
  4119. /* The first ranges are individually tracked. Use the value as is. */
  4120. return Value;
  4121. else if (Value >= 513)
  4122. /* The last range is mapped to its lowest value. */
  4123. return 513;
  4124. else if (popcount64(Value) == 1)
  4125. /* If it's a power of two, use it as is. */
  4126. return Value;
  4127. else
  4128. /* Otherwise, take to the previous power of two + 1. */
  4129. return (((uint64)1) << (64 - clz64(Value) - 1)) + 1;
  4130. }
  4131. void
  4132. llvm_profile_instrument_memop(uint64 target_value, void *data,
  4133. uint32 counter_idx)
  4134. {
  4135. uint64 rep_value = InstrProfGetRangeRepValue(target_value);
  4136. instrumentTargetValueImpl(rep_value, data, counter_idx, 1);
  4137. }
  4138. static uint32
  4139. get_pgo_prof_data_size(AOTModuleInstance *module_inst, uint32 *p_num_prof_data,
  4140. uint32 *p_num_prof_counters, uint32 *p_padding_size,
  4141. uint32 *p_prof_counters_size, uint32 *p_prof_names_size,
  4142. uint32 *p_value_counters_size, uint8 **p_prof_names)
  4143. {
  4144. AOTModule *module = (AOTModule *)module_inst->module;
  4145. LLVMProfileData *prof_data;
  4146. uint8 *prof_names = NULL;
  4147. uint32 num_prof_data = 0, num_prof_counters = 0, padding_size, i;
  4148. uint32 prof_counters_size = 0, prof_names_size = 0;
  4149. uint32 total_size, total_size_wo_value_counters;
  4150. for (i = 0; i < module->data_section_count; i++) {
  4151. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  4152. bh_assert(module->data_sections[i].size == sizeof(LLVMProfileData));
  4153. num_prof_data++;
  4154. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  4155. num_prof_counters += prof_data->num_counters;
  4156. }
  4157. else if (!strncmp(module->data_sections[i].name, "__llvm_prf_cnts",
  4158. 15)) {
  4159. prof_counters_size += module->data_sections[i].size;
  4160. }
  4161. else if (!strncmp(module->data_sections[i].name, "__llvm_prf_names",
  4162. 16)) {
  4163. prof_names_size = module->data_sections[i].size;
  4164. prof_names = module->data_sections[i].data;
  4165. }
  4166. }
  4167. if (prof_counters_size != num_prof_counters * sizeof(uint64))
  4168. return 0;
  4169. total_size = sizeof(LLVMProfileRawHeader)
  4170. + num_prof_data * sizeof(LLVMProfileData_64)
  4171. + prof_counters_size + prof_names_size;
  4172. padding_size = sizeof(uint64) - (prof_names_size % sizeof(uint64));
  4173. if (padding_size != sizeof(uint64))
  4174. total_size += padding_size;
  4175. /* Total size excluding value counters */
  4176. total_size_wo_value_counters = total_size;
  4177. for (i = 0; i < module->data_section_count; i++) {
  4178. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  4179. uint32 j, k, num_value_sites, num_value_nodes;
  4180. ValueProfNode **values, *value_node;
  4181. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  4182. values = prof_data->values;
  4183. if (prof_data->num_value_sites[0] > 0
  4184. || prof_data->num_value_sites[1] > 0) {
  4185. /* TotalSize (uint32) and NumValueKinds (uint32) */
  4186. total_size += 8;
  4187. for (j = 0; j < 2; j++) {
  4188. if ((num_value_sites = prof_data->num_value_sites[j]) > 0) {
  4189. /* ValueKind (uint32) and NumValueSites (uint32) */
  4190. total_size += 8;
  4191. /* (Value + Counter) group counts of each value site,
  4192. each count is one byte */
  4193. total_size += align_uint(num_value_sites, 8);
  4194. if (values) {
  4195. for (k = 0; k < num_value_sites; k++) {
  4196. num_value_nodes = 0;
  4197. value_node = *values;
  4198. while (value_node) {
  4199. num_value_nodes++;
  4200. value_node = value_node->next;
  4201. }
  4202. if (num_value_nodes) {
  4203. /* (Value + Counter) groups */
  4204. total_size += num_value_nodes * 8 * 2;
  4205. }
  4206. values++;
  4207. }
  4208. }
  4209. }
  4210. }
  4211. }
  4212. }
  4213. }
  4214. if (p_num_prof_data)
  4215. *p_num_prof_data = num_prof_data;
  4216. if (p_num_prof_counters)
  4217. *p_num_prof_counters = num_prof_counters;
  4218. if (p_padding_size)
  4219. *p_padding_size = padding_size;
  4220. if (p_prof_counters_size)
  4221. *p_prof_counters_size = prof_counters_size;
  4222. if (p_prof_names_size)
  4223. *p_prof_names_size = prof_names_size;
  4224. if (p_value_counters_size)
  4225. *p_value_counters_size = total_size - total_size_wo_value_counters;
  4226. if (p_prof_names)
  4227. *p_prof_names = prof_names;
  4228. return total_size;
  4229. }
  4230. uint32
  4231. aot_get_pgo_prof_data_size(AOTModuleInstance *module_inst)
  4232. {
  4233. return get_pgo_prof_data_size(module_inst, NULL, NULL, NULL, NULL, NULL,
  4234. NULL, NULL);
  4235. }
  4236. static union {
  4237. int a;
  4238. char b;
  4239. } __ue = { .a = 1 };
  4240. #define is_little_endian() (__ue.b == 1)
  4241. uint32
  4242. aot_dump_pgo_prof_data_to_buf(AOTModuleInstance *module_inst, char *buf,
  4243. uint32 len)
  4244. {
  4245. AOTModule *module = (AOTModule *)module_inst->module;
  4246. LLVMProfileRawHeader prof_header = { 0 };
  4247. LLVMProfileData *prof_data;
  4248. uint8 *prof_names = NULL;
  4249. uint32 num_prof_data = 0, num_prof_counters = 0, padding_size, i;
  4250. uint32 prof_counters_size = 0, prof_names_size = 0;
  4251. uint32 value_counters_size = 0, value_counters_size_backup = 0;
  4252. uint32 total_size, size;
  4253. int64 counters_delta, offset_counters;
  4254. total_size = get_pgo_prof_data_size(module_inst, &num_prof_data,
  4255. &num_prof_counters, &padding_size,
  4256. &prof_counters_size, &prof_names_size,
  4257. &value_counters_size, &prof_names);
  4258. if (len < total_size)
  4259. return 0;
  4260. value_counters_size_backup = value_counters_size;
  4261. value_counters_size = 0;
  4262. prof_header.counters_delta = counters_delta =
  4263. sizeof(LLVMProfileData_64) * num_prof_data;
  4264. offset_counters = 0;
  4265. for (i = 0; i < module->data_section_count; i++) {
  4266. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  4267. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  4268. prof_data->offset_counters = counters_delta + offset_counters;
  4269. offset_counters += prof_data->num_counters * sizeof(uint64);
  4270. counters_delta -= sizeof(LLVMProfileData_64);
  4271. }
  4272. }
  4273. prof_header.magic = 0xFF6C70726F667281LL;
  4274. /* Version 9 */
  4275. prof_header.version = 0x0000000000000009LL;
  4276. /* with VARIANT_MASK_IR_PROF (IR Instrumentation) */
  4277. prof_header.version |= 0x1ULL << 56;
  4278. /* with VARIANT_MASK_MEMPROF (Memory Profile) */
  4279. prof_header.version |= 0x1ULL << 62;
  4280. prof_header.num_prof_data = num_prof_data;
  4281. prof_header.num_prof_counters = num_prof_counters;
  4282. prof_header.names_size = prof_names_size;
  4283. prof_header.value_kind_last = 1;
  4284. /* __llvm_prf_bits won't be used in PGO, set dummy value here */
  4285. prof_header.num_prof_bitmaps = 0;
  4286. prof_header.bitmap_delta = 0;
  4287. if (!is_little_endian()) {
  4288. aot_exchange_uint64((uint8 *)&prof_header.magic);
  4289. aot_exchange_uint64((uint8 *)&prof_header.version);
  4290. aot_exchange_uint64((uint8 *)&prof_header.num_prof_data);
  4291. aot_exchange_uint64((uint8 *)&prof_header.num_prof_counters);
  4292. aot_exchange_uint64((uint8 *)&prof_header.num_prof_bitmaps);
  4293. aot_exchange_uint64((uint8 *)&prof_header.names_size);
  4294. aot_exchange_uint64((uint8 *)&prof_header.counters_delta);
  4295. aot_exchange_uint64((uint8 *)&prof_header.bitmap_delta);
  4296. aot_exchange_uint64((uint8 *)&prof_header.value_kind_last);
  4297. }
  4298. size = sizeof(LLVMProfileRawHeader);
  4299. bh_memcpy_s(buf, size, &prof_header, size);
  4300. buf += size;
  4301. for (i = 0; i < module->data_section_count; i++) {
  4302. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  4303. LLVMProfileData_64 *prof_data_64 = (LLVMProfileData_64 *)buf;
  4304. /* Convert LLVMProfileData to LLVMProfileData_64, the pointer width
  4305. in the output file is always 8 bytes */
  4306. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  4307. prof_data_64->func_md5 = prof_data->func_md5;
  4308. prof_data_64->func_hash = prof_data->func_hash;
  4309. prof_data_64->offset_counters = prof_data->offset_counters;
  4310. prof_data_64->offset_bitmaps = prof_data->offset_bitmaps;
  4311. prof_data_64->func_ptr = prof_data->func_ptr;
  4312. prof_data_64->values = (uint64)(uintptr_t)prof_data->values;
  4313. prof_data_64->num_counters = prof_data->num_counters;
  4314. /* __llvm_prf_bits won't be used in PGO, set dummy value here */
  4315. prof_data_64->num_bitmaps = 0;
  4316. prof_data_64->num_value_sites[0] = prof_data->num_value_sites[0];
  4317. prof_data_64->num_value_sites[1] = prof_data->num_value_sites[1];
  4318. if (!is_little_endian()) {
  4319. aot_exchange_uint64((uint8 *)&prof_data_64->func_hash);
  4320. aot_exchange_uint64((uint8 *)&prof_data_64->offset_counters);
  4321. aot_exchange_uint64((uint8 *)&prof_data_64->offset_bitmaps);
  4322. aot_exchange_uint64((uint8 *)&prof_data_64->func_ptr);
  4323. aot_exchange_uint64((uint8 *)&prof_data_64->values);
  4324. aot_exchange_uint32((uint8 *)&prof_data_64->num_counters);
  4325. aot_exchange_uint32((uint8 *)&prof_data_64->num_bitmaps);
  4326. aot_exchange_uint16((uint8 *)&prof_data_64->num_value_sites[0]);
  4327. aot_exchange_uint16((uint8 *)&prof_data_64->num_value_sites[1]);
  4328. }
  4329. buf += sizeof(LLVMProfileData_64);
  4330. }
  4331. }
  4332. for (i = 0; i < module->data_section_count; i++) {
  4333. if (!strncmp(module->data_sections[i].name, "__llvm_prf_cnts", 15)) {
  4334. size = module->data_sections[i].size;
  4335. bh_memcpy_s(buf, size, module->data_sections[i].data, size);
  4336. buf += size;
  4337. }
  4338. }
  4339. if (prof_names && prof_names_size > 0) {
  4340. size = prof_names_size;
  4341. bh_memcpy_s(buf, size, prof_names, size);
  4342. buf += size;
  4343. padding_size = sizeof(uint64) - (prof_names_size % sizeof(uint64));
  4344. if (padding_size != sizeof(uint64)) {
  4345. char padding_buf[8] = { 0 };
  4346. bh_memcpy_s(buf, padding_size, padding_buf, padding_size);
  4347. buf += padding_size;
  4348. }
  4349. }
  4350. for (i = 0; i < module->data_section_count; i++) {
  4351. if (!strncmp(module->data_sections[i].name, "__llvm_prf_data", 15)) {
  4352. uint32 j, k, num_value_sites, num_value_nodes;
  4353. ValueProfNode **values, **values_tmp, *value_node;
  4354. prof_data = (LLVMProfileData *)module->data_sections[i].data;
  4355. values = values_tmp = prof_data->values;
  4356. if (prof_data->num_value_sites[0] > 0
  4357. || prof_data->num_value_sites[1] > 0) {
  4358. uint32 *buf_total_size = (uint32 *)buf;
  4359. buf += 4; /* emit TotalSize later */
  4360. *(uint32 *)buf = (prof_data->num_value_sites[0] > 0
  4361. && prof_data->num_value_sites[1] > 0)
  4362. ? 2
  4363. : 1;
  4364. if (!is_little_endian())
  4365. aot_exchange_uint32((uint8 *)buf);
  4366. buf += 4;
  4367. for (j = 0; j < 2; j++) {
  4368. if ((num_value_sites = prof_data->num_value_sites[j]) > 0) {
  4369. /* ValueKind */
  4370. *(uint32 *)buf = j;
  4371. if (!is_little_endian())
  4372. aot_exchange_uint32((uint8 *)buf);
  4373. buf += 4;
  4374. /* NumValueSites */
  4375. *(uint32 *)buf = num_value_sites;
  4376. if (!is_little_endian())
  4377. aot_exchange_uint32((uint8 *)buf);
  4378. buf += 4;
  4379. for (k = 0; k < num_value_sites; k++) {
  4380. num_value_nodes = 0;
  4381. if (values_tmp) {
  4382. value_node = *values_tmp;
  4383. while (value_node) {
  4384. num_value_nodes++;
  4385. value_node = value_node->next;
  4386. }
  4387. values_tmp++;
  4388. }
  4389. bh_assert(num_value_nodes < 255);
  4390. *(uint8 *)buf++ = (uint8)num_value_nodes;
  4391. }
  4392. if (num_value_sites % 8) {
  4393. buf += 8 - (num_value_sites % 8);
  4394. }
  4395. for (k = 0; k < num_value_sites; k++) {
  4396. if (values) {
  4397. value_node = *values;
  4398. while (value_node) {
  4399. *(uint64 *)buf = value_node->value;
  4400. if (!is_little_endian())
  4401. aot_exchange_uint64((uint8 *)buf);
  4402. buf += 8;
  4403. *(uint64 *)buf = value_node->count;
  4404. if (!is_little_endian())
  4405. aot_exchange_uint64((uint8 *)buf);
  4406. buf += 8;
  4407. value_node = value_node->next;
  4408. }
  4409. values++;
  4410. }
  4411. }
  4412. }
  4413. }
  4414. /* TotalSize */
  4415. *(uint32 *)buf_total_size =
  4416. (uint8 *)buf - (uint8 *)buf_total_size;
  4417. if (!is_little_endian())
  4418. aot_exchange_uint64((uint8 *)buf_total_size);
  4419. value_counters_size += (uint8 *)buf - (uint8 *)buf_total_size;
  4420. }
  4421. }
  4422. }
  4423. bh_assert(value_counters_size == value_counters_size_backup);
  4424. (void)value_counters_size_backup;
  4425. return total_size;
  4426. }
  4427. #endif /* end of WASM_ENABLE_STATIC_PGO != 0 */
  4428. #if WASM_ENABLE_GC != 0
  4429. void *
  4430. aot_create_func_obj(AOTModuleInstance *module_inst, uint32 func_idx,
  4431. bool throw_exce, char *error_buf, uint32 error_buf_size)
  4432. {
  4433. AOTModule *module = (AOTModule *)module_inst->module;
  4434. WASMRttTypeRef rtt_type;
  4435. WASMFuncObjectRef func_obj;
  4436. AOTFuncType *func_type;
  4437. uint32 type_idx;
  4438. if (throw_exce) {
  4439. error_buf = module_inst->cur_exception;
  4440. error_buf_size = sizeof(module_inst->cur_exception);
  4441. }
  4442. if (func_idx >= module->import_func_count + module->func_count) {
  4443. set_error_buf_v(error_buf, error_buf_size, "unknown function %d",
  4444. func_idx);
  4445. return NULL;
  4446. }
  4447. type_idx = module_inst->func_type_indexes[func_idx];
  4448. func_type = (AOTFuncType *)module->types[type_idx];
  4449. if (!(rtt_type = wasm_rtt_type_new((AOTType *)func_type, type_idx,
  4450. module->rtt_types, module->type_count,
  4451. &module->rtt_type_lock))) {
  4452. set_error_buf(error_buf, error_buf_size, "create rtt object failed");
  4453. return NULL;
  4454. }
  4455. if (!(func_obj = wasm_func_obj_new_internal(
  4456. ((AOTModuleInstanceExtra *)module_inst->e)->common.gc_heap_handle,
  4457. rtt_type, func_idx))) {
  4458. set_error_buf(error_buf, error_buf_size, "create func object failed");
  4459. return NULL;
  4460. }
  4461. return func_obj;
  4462. }
  4463. bool
  4464. aot_obj_is_instance_of(AOTModuleInstance *module_inst, WASMObjectRef gc_obj,
  4465. uint32 type_index)
  4466. {
  4467. AOTModule *aot_module = (AOTModule *)module_inst->module;
  4468. AOTType **types = aot_module->types;
  4469. uint32 type_count = aot_module->type_count;
  4470. return wasm_obj_is_instance_of(gc_obj, type_index, types, type_count);
  4471. }
  4472. bool
  4473. aot_func_type_is_super_of(AOTModuleInstance *module_inst, uint32 type_idx1,
  4474. uint32 type_idx2)
  4475. {
  4476. AOTModule *aot_module = (AOTModule *)module_inst->module;
  4477. AOTType **types = aot_module->types;
  4478. if (type_idx1 == type_idx2)
  4479. return true;
  4480. bh_assert(types[type_idx1]->type_flag == WASM_TYPE_FUNC);
  4481. bh_assert(types[type_idx2]->type_flag == WASM_TYPE_FUNC);
  4482. return wasm_func_type_is_super_of((WASMFuncType *)types[type_idx1],
  4483. (WASMFuncType *)types[type_idx2]);
  4484. }
  4485. WASMRttTypeRef
  4486. aot_rtt_type_new(AOTModuleInstance *module_inst, uint32 type_index)
  4487. {
  4488. AOTModule *aot_module = (AOTModule *)module_inst->module;
  4489. AOTType *defined_type = aot_module->types[type_index];
  4490. WASMRttType **rtt_types = aot_module->rtt_types;
  4491. uint32 rtt_type_count = aot_module->type_count;
  4492. korp_mutex *rtt_type_lock = &aot_module->rtt_type_lock;
  4493. return wasm_rtt_type_new(defined_type, type_index, rtt_types,
  4494. rtt_type_count, rtt_type_lock);
  4495. }
  4496. bool
  4497. aot_array_init_with_data(AOTModuleInstance *module_inst, uint32 seg_index,
  4498. uint32 data_seg_offset, WASMArrayObjectRef array_obj,
  4499. uint32 elem_size, uint32 array_len)
  4500. {
  4501. AOTModule *aot_module;
  4502. uint8 *data = NULL;
  4503. uint8 *array_elem_base;
  4504. uint64 seg_len = 0;
  4505. uint64 total_size = (int64)elem_size * array_len;
  4506. aot_module = (AOTModule *)module_inst->module;
  4507. seg_len = aot_module->mem_init_data_list[seg_index]->byte_count;
  4508. data = aot_module->mem_init_data_list[seg_index]->bytes;
  4509. if (data_seg_offset >= seg_len || total_size > seg_len - data_seg_offset) {
  4510. aot_set_exception(module_inst, "out of bounds memory access");
  4511. return false;
  4512. }
  4513. array_elem_base = (uint8 *)wasm_array_obj_first_elem_addr(array_obj);
  4514. bh_memcpy_s(array_elem_base, (uint32)total_size, data + data_seg_offset,
  4515. (uint32)total_size);
  4516. return true;
  4517. }
  4518. static bool
  4519. aot_global_traverse_gc_rootset(AOTModuleInstance *module_inst, void *heap)
  4520. {
  4521. AOTModule *module = (AOTModule *)module_inst->module;
  4522. uint8 *global_data = module_inst->global_data;
  4523. AOTImportGlobal *import_global = module->import_globals;
  4524. AOTGlobal *global = module->globals;
  4525. WASMObjectRef gc_obj;
  4526. uint32 i;
  4527. for (i = 0; i < module->import_global_count; i++, import_global++) {
  4528. if (wasm_is_type_reftype(import_global->type.val_type)) {
  4529. gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data);
  4530. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4531. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  4532. return false;
  4533. }
  4534. }
  4535. global_data += import_global->size;
  4536. }
  4537. for (i = 0; i < module->global_count; i++, global++) {
  4538. if (wasm_is_type_reftype(global->type.val_type)) {
  4539. gc_obj = GET_REF_FROM_ADDR((uint32 *)global_data);
  4540. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4541. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  4542. return false;
  4543. }
  4544. }
  4545. global_data += global->size;
  4546. }
  4547. return true;
  4548. }
  4549. static bool
  4550. aot_table_traverse_gc_rootset(WASMModuleInstance *module_inst, void *heap)
  4551. {
  4552. AOTTableInstance **tables = (AOTTableInstance **)module_inst->tables;
  4553. AOTTableInstance *table;
  4554. uint32 table_count = module_inst->table_count, i, j;
  4555. WASMObjectRef gc_obj, *table_elems;
  4556. for (i = 0; i < table_count; i++) {
  4557. table = tables[i];
  4558. table_elems = (WASMObjectRef *)table->elems;
  4559. for (j = 0; j < table->cur_size; j++) {
  4560. gc_obj = table_elems[j];
  4561. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4562. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  4563. return false;
  4564. }
  4565. }
  4566. }
  4567. return true;
  4568. }
  4569. static bool
  4570. local_object_refs_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  4571. {
  4572. WASMLocalObjectRef *r;
  4573. WASMObjectRef gc_obj;
  4574. for (r = exec_env->cur_local_object_ref; r; r = r->prev) {
  4575. gc_obj = r->val;
  4576. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4577. if (0 != mem_allocator_add_root((mem_allocator_t)heap, gc_obj))
  4578. return false;
  4579. }
  4580. }
  4581. return true;
  4582. }
  4583. static bool
  4584. aot_frame_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  4585. {
  4586. AOTFrame *frame;
  4587. AOTModule *module;
  4588. LocalRefFlag frame_local_flags;
  4589. WASMObjectRef gc_obj;
  4590. uint32 i, local_ref_flag_cell_num;
  4591. module = (AOTModule *)wasm_exec_env_get_module(exec_env);
  4592. frame = (AOTFrame *)wasm_exec_env_get_cur_frame(exec_env);
  4593. for (; frame; frame = frame->prev_frame) {
  4594. /* local ref flags */
  4595. frame_local_flags = module->func_local_ref_flags[frame->func_index];
  4596. local_ref_flag_cell_num = frame_local_flags.local_ref_flag_cell_num;
  4597. for (i = 0; i < local_ref_flag_cell_num; i++) {
  4598. if (frame_local_flags.local_ref_flags[i]) {
  4599. gc_obj = GET_REF_FROM_ADDR(frame->lp + i);
  4600. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4601. if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) {
  4602. return false;
  4603. }
  4604. }
  4605. #if UINTPTR_MAX == UINT64_MAX
  4606. bh_assert(frame_local_flags.local_ref_flags[i + 1]);
  4607. i++;
  4608. #endif
  4609. }
  4610. }
  4611. /* stack ref flags */
  4612. uint8 *frame_ref = frame->frame_ref;
  4613. for (i = local_ref_flag_cell_num; i < (uint32)(frame->sp - frame->lp);
  4614. i++) {
  4615. if (frame_ref[i]) {
  4616. gc_obj = GET_REF_FROM_ADDR(frame->lp + i);
  4617. if (wasm_obj_is_created_from_heap(gc_obj)) {
  4618. if (mem_allocator_add_root((mem_allocator_t)heap, gc_obj)) {
  4619. return false;
  4620. }
  4621. }
  4622. #if UINTPTR_MAX == UINT64_MAX
  4623. bh_assert(frame_ref[i + 1]);
  4624. i++;
  4625. #endif
  4626. }
  4627. }
  4628. }
  4629. return true;
  4630. }
  4631. bool
  4632. aot_traverse_gc_rootset(WASMExecEnv *exec_env, void *heap)
  4633. {
  4634. AOTModuleInstance *module_inst = (AOTModuleInstance *)exec_env->module_inst;
  4635. bool ret;
  4636. ret = aot_global_traverse_gc_rootset(module_inst, heap);
  4637. if (!ret)
  4638. return ret;
  4639. ret = aot_table_traverse_gc_rootset(module_inst, heap);
  4640. if (!ret)
  4641. return ret;
  4642. ret = local_object_refs_traverse_gc_rootset(exec_env, heap);
  4643. if (!ret)
  4644. return ret;
  4645. ret = aot_frame_traverse_gc_rootset(exec_env, heap);
  4646. if (!ret)
  4647. return ret;
  4648. return true;
  4649. }
  4650. #endif /* end of WASM_ENABLE_GC != 0 */
  4651. char *
  4652. aot_const_str_set_insert(const uint8 *str, int32 len, AOTModule *module,
  4653. #if (WASM_ENABLE_WORD_ALIGN_READ != 0)
  4654. bool is_vram_word_align,
  4655. #endif
  4656. char *error_buf, uint32 error_buf_size)
  4657. {
  4658. HashMap *set = module->const_str_set;
  4659. char *c_str, *value;
  4660. /* Create const string set if it isn't created */
  4661. if (!set
  4662. && !(set = module->const_str_set = bh_hash_map_create(
  4663. 32, false, (HashFunc)wasm_string_hash,
  4664. (KeyEqualFunc)wasm_string_equal, NULL, wasm_runtime_free))) {
  4665. set_error_buf(error_buf, error_buf_size,
  4666. "create const string set failed");
  4667. return NULL;
  4668. }
  4669. /* Lookup const string set, use the string if found */
  4670. if (!(c_str = runtime_malloc((uint32)len, error_buf, error_buf_size))) {
  4671. return NULL;
  4672. }
  4673. #if (WASM_ENABLE_WORD_ALIGN_READ != 0)
  4674. if (is_vram_word_align) {
  4675. bh_memcpy_wa(c_str, (uint32)len, str, (uint32)len);
  4676. }
  4677. else
  4678. #endif
  4679. {
  4680. bh_memcpy_s(c_str, len, str, (uint32)len);
  4681. }
  4682. if ((value = bh_hash_map_find(set, c_str))) {
  4683. wasm_runtime_free(c_str);
  4684. return value;
  4685. }
  4686. if (!bh_hash_map_insert(set, c_str, c_str)) {
  4687. set_error_buf(error_buf, error_buf_size,
  4688. "insert string to hash map failed");
  4689. wasm_runtime_free(c_str);
  4690. return NULL;
  4691. }
  4692. return c_str;
  4693. }
  4694. #if WASM_ENABLE_DYNAMIC_AOT_DEBUG != 0
  4695. AOTModule *g_dynamic_aot_module = NULL;
  4696. void __attribute__((noinline)) __enable_dynamic_aot_debug(void)
  4697. {
  4698. /* empty implementation. */
  4699. }
  4700. void (*__enable_dynamic_aot_debug_ptr)(void)
  4701. __attribute__((visibility("default"))) = __enable_dynamic_aot_debug;
  4702. #endif
  4703. bool
  4704. aot_set_module_name(AOTModule *module, const char *name, char *error_buf,
  4705. uint32_t error_buf_size)
  4706. {
  4707. if (!name)
  4708. return false;
  4709. module->name = aot_const_str_set_insert((const uint8 *)name,
  4710. (uint32)(strlen(name) + 1), module,
  4711. #if (WASM_ENABLE_WORD_ALIGN_READ != 0)
  4712. false,
  4713. #endif
  4714. error_buf, error_buf_size);
  4715. #if WASM_ENABLE_DYNAMIC_AOT_DEBUG != 0
  4716. /* export g_dynamic_aot_module for dynamic aot debug */
  4717. g_dynamic_aot_module = module;
  4718. /* trigger breakpoint __enable_dynamic_aot_debug */
  4719. (*__enable_dynamic_aot_debug_ptr)();
  4720. #endif
  4721. return module->name != NULL;
  4722. }
  4723. const char *
  4724. aot_get_module_name(AOTModule *module)
  4725. {
  4726. return module->name;
  4727. }
  4728. bool
  4729. aot_resolve_symbols(AOTModule *module)
  4730. {
  4731. bool ret = true;
  4732. uint32 idx;
  4733. for (idx = 0; idx < module->import_func_count; ++idx) {
  4734. AOTImportFunc *aot_import_func = &module->import_funcs[idx];
  4735. if (!aot_import_func->func_ptr_linked) {
  4736. if (!aot_resolve_import_func(module, aot_import_func)) {
  4737. LOG_WARNING("Failed to link function (%s, %s)",
  4738. aot_import_func->module_name,
  4739. aot_import_func->func_name);
  4740. ret = false;
  4741. }
  4742. }
  4743. }
  4744. return ret;
  4745. }
  4746. #if WASM_ENABLE_MULTI_MODULE != 0
  4747. static void *
  4748. aot_resolve_function(const AOTModule *module, const char *function_name,
  4749. const AOTFuncType *expected_function_type, char *error_buf,
  4750. uint32 error_buf_size);
  4751. static void *
  4752. aot_resolve_function_ex(const char *module_name, const char *function_name,
  4753. const AOTFuncType *expected_function_type,
  4754. char *error_buf, uint32 error_buf_size)
  4755. {
  4756. WASMModuleCommon *module_reg;
  4757. module_reg = wasm_runtime_find_module_registered(module_name);
  4758. if (!module_reg || module_reg->module_type != Wasm_Module_AoT) {
  4759. LOG_DEBUG("can not find a module named %s for function %s", module_name,
  4760. function_name);
  4761. set_error_buf(error_buf, error_buf_size, "unknown import");
  4762. return NULL;
  4763. }
  4764. return aot_resolve_function((AOTModule *)module_reg, function_name,
  4765. expected_function_type, error_buf,
  4766. error_buf_size);
  4767. }
  4768. static void *
  4769. aot_resolve_function(const AOTModule *module, const char *function_name,
  4770. const AOTFuncType *expected_function_type, char *error_buf,
  4771. uint32 error_buf_size)
  4772. {
  4773. void *function = NULL;
  4774. AOTExport *export = NULL;
  4775. AOTFuncType *target_function_type = NULL;
  4776. export = loader_find_export((WASMModuleCommon *)module, module->name,
  4777. function_name, EXPORT_KIND_FUNC, error_buf,
  4778. error_buf_size);
  4779. if (!export) {
  4780. return NULL;
  4781. }
  4782. /* resolve function type and function */
  4783. if (export->index < module->import_func_count) {
  4784. target_function_type = module->import_funcs[export->index].func_type;
  4785. function = module->import_funcs[export->index].func_ptr_linked;
  4786. }
  4787. else {
  4788. target_function_type =
  4789. (AOTFuncType *)module
  4790. ->types[module->func_type_indexes[export->index
  4791. - module->import_func_count]];
  4792. function =
  4793. (module->func_ptrs[export->index - module->import_func_count]);
  4794. }
  4795. /* check function type */
  4796. if (!wasm_type_equal((WASMType *)expected_function_type,
  4797. (WASMType *)target_function_type, module->types,
  4798. module->type_count)) {
  4799. LOG_DEBUG("%s.%s failed the type check", module->name, function_name);
  4800. set_error_buf(error_buf, error_buf_size, "incompatible import type");
  4801. return NULL;
  4802. }
  4803. return function;
  4804. }
  4805. #endif /* end of WASM_ENABLE_MULTI_MODULE */
  4806. bool
  4807. aot_resolve_import_func(AOTModule *module, AOTImportFunc *import_func)
  4808. {
  4809. #if WASM_ENABLE_MULTI_MODULE != 0
  4810. char error_buf[128];
  4811. AOTModule *sub_module = NULL;
  4812. #endif
  4813. import_func->func_ptr_linked = wasm_native_resolve_symbol(
  4814. import_func->module_name, import_func->func_name,
  4815. import_func->func_type, &import_func->signature,
  4816. &import_func->attachment, &import_func->call_conv_raw);
  4817. #if WASM_ENABLE_MULTI_MODULE != 0
  4818. if (!import_func->func_ptr_linked) {
  4819. if (!wasm_runtime_is_built_in_module(import_func->module_name)) {
  4820. sub_module = (AOTModule *)wasm_runtime_load_depended_module(
  4821. (WASMModuleCommon *)module, import_func->module_name, error_buf,
  4822. sizeof(error_buf));
  4823. if (!sub_module) {
  4824. LOG_WARNING("Failed to load sub module: %s", error_buf);
  4825. }
  4826. if (!sub_module)
  4827. import_func->func_ptr_linked = aot_resolve_function_ex(
  4828. import_func->module_name, import_func->func_name,
  4829. import_func->func_type, error_buf, sizeof(error_buf));
  4830. else
  4831. import_func->func_ptr_linked = aot_resolve_function(
  4832. sub_module, import_func->func_name, import_func->func_type,
  4833. error_buf, sizeof(error_buf));
  4834. if (!import_func->func_ptr_linked) {
  4835. LOG_WARNING("Failed to link function: %s", error_buf);
  4836. }
  4837. }
  4838. }
  4839. #endif
  4840. return import_func->func_ptr_linked != NULL;
  4841. }