wasm_runtime_common.c 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_platform.h"
  6. #include "bh_common.h"
  7. #include "bh_assert.h"
  8. #include "bh_log.h"
  9. #include "wasm_native.h"
  10. #include "wasm_runtime_common.h"
  11. #include "wasm_memory.h"
  12. #if WASM_ENABLE_INTERP != 0
  13. #include "../interpreter/wasm_runtime.h"
  14. #endif
  15. #if WASM_ENABLE_AOT != 0
  16. #include "../aot/aot_runtime.h"
  17. #if WASM_ENABLE_DEBUG_AOT != 0
  18. #include "../aot/debug/jit_debug.h"
  19. #endif
  20. #endif
  21. #if WASM_ENABLE_THREAD_MGR != 0
  22. #include "../libraries/thread-mgr/thread_manager.h"
  23. #if WASM_ENABLE_DEBUG_INTERP != 0
  24. #include "../libraries/debug-engine/debug_engine.h"
  25. #endif
  26. #endif
  27. #if WASM_ENABLE_SHARED_MEMORY != 0
  28. #include "wasm_shared_memory.h"
  29. #endif
  30. #if WASM_ENABLE_FAST_JIT != 0
  31. #include "../fast-jit/jit_compiler.h"
  32. #endif
  33. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  34. #include "../compilation/aot_llvm.h"
  35. #endif
  36. #include "../common/wasm_c_api_internal.h"
  37. #include "../../version.h"
  38. /**
  39. * For runtime build, BH_MALLOC/BH_FREE should be defined as
  40. * wasm_runtime_malloc/wasm_runtime_free.
  41. */
  42. #define CHECK(a) CHECK1(a)
  43. #define CHECK1(a) SHOULD_BE_##a
  44. #define SHOULD_BE_wasm_runtime_malloc 1
  45. #if !CHECK(BH_MALLOC)
  46. #error unexpected BH_MALLOC
  47. #endif
  48. #undef SHOULD_BE_wasm_runtime_malloc
  49. #define SHOULD_BE_wasm_runtime_free 1
  50. #if !CHECK(BH_FREE)
  51. #error unexpected BH_FREE
  52. #endif
  53. #undef SHOULD_BE_wasm_runtime_free
  54. #undef CHECK
  55. #undef CHECK1
  56. #if WASM_ENABLE_MULTI_MODULE != 0
  57. /**
  58. * A safety insurance to prevent
  59. * circular depencies which leads stack overflow
  60. * try to break early
  61. */
  62. typedef struct LoadingModule {
  63. bh_list_link l;
  64. /* point to a string pool */
  65. const char *module_name;
  66. } LoadingModule;
  67. static bh_list loading_module_list_head;
  68. static bh_list *const loading_module_list = &loading_module_list_head;
  69. static korp_mutex loading_module_list_lock;
  70. /**
  71. * A list to store all exported functions/globals/memories/tables
  72. * of every fully loaded module
  73. */
  74. static bh_list registered_module_list_head;
  75. static bh_list *const registered_module_list = &registered_module_list_head;
  76. static korp_mutex registered_module_list_lock;
  77. static void
  78. wasm_runtime_destroy_registered_module_list();
  79. #endif /* WASM_ENABLE_MULTI_MODULE */
  80. #define E_TYPE_XIP 4
  81. #if WASM_ENABLE_REF_TYPES != 0
  82. /* Initialize externref hashmap */
  83. static bool
  84. wasm_externref_map_init();
  85. /* Destroy externref hashmap */
  86. static void
  87. wasm_externref_map_destroy();
  88. #endif /* WASM_ENABLE_REF_TYPES */
  89. static void
  90. set_error_buf(char *error_buf, uint32 error_buf_size, const char *string)
  91. {
  92. if (error_buf != NULL)
  93. snprintf(error_buf, error_buf_size, "%s", string);
  94. }
  95. static void *
  96. runtime_malloc(uint64 size, WASMModuleInstanceCommon *module_inst,
  97. char *error_buf, uint32 error_buf_size)
  98. {
  99. void *mem;
  100. if (size >= UINT32_MAX || !(mem = wasm_runtime_malloc((uint32)size))) {
  101. if (module_inst != NULL) {
  102. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  103. }
  104. else if (error_buf != NULL) {
  105. set_error_buf(error_buf, error_buf_size, "allocate memory failed");
  106. }
  107. return NULL;
  108. }
  109. memset(mem, 0, (uint32)size);
  110. return mem;
  111. }
  112. #if WASM_ENABLE_FAST_JIT != 0
  113. static JitCompOptions jit_options = { 0 };
  114. #endif
  115. #if WASM_ENABLE_JIT != 0
  116. static LLVMJITOptions llvm_jit_options = { 3, 3, 0 };
  117. #endif
  118. static RunningMode runtime_running_mode = Mode_Default;
  119. #ifdef OS_ENABLE_HW_BOUND_CHECK
  120. /* The exec_env of thread local storage, set before calling function
  121. and used in signal handler, as we cannot get it from the argument
  122. of signal handler */
  123. static os_thread_local_attribute WASMExecEnv *exec_env_tls = NULL;
  124. #ifndef BH_PLATFORM_WINDOWS
  125. static void
  126. runtime_signal_handler(void *sig_addr)
  127. {
  128. WASMModuleInstance *module_inst;
  129. WASMMemoryInstance *memory_inst;
  130. WASMJmpBuf *jmpbuf_node;
  131. uint8 *mapped_mem_start_addr = NULL;
  132. uint8 *mapped_mem_end_addr = NULL;
  133. uint32 page_size = os_getpagesize();
  134. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  135. uint8 *stack_min_addr;
  136. uint32 guard_page_count = STACK_OVERFLOW_CHECK_GUARD_PAGE_COUNT;
  137. #endif
  138. /* Check whether current thread is running wasm function */
  139. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  140. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  141. /* Get mapped mem info of current instance */
  142. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  143. /* Get the default memory instance */
  144. memory_inst = wasm_get_default_memory(module_inst);
  145. if (memory_inst) {
  146. mapped_mem_start_addr = memory_inst->memory_data;
  147. mapped_mem_end_addr = memory_inst->memory_data + 8 * (uint64)BH_GB;
  148. }
  149. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  150. /* Get stack info of current thread */
  151. stack_min_addr = os_thread_get_stack_boundary();
  152. #endif
  153. if (memory_inst
  154. && (mapped_mem_start_addr <= (uint8 *)sig_addr
  155. && (uint8 *)sig_addr < mapped_mem_end_addr)) {
  156. /* The address which causes segmentation fault is inside
  157. the memory instance's guard regions */
  158. wasm_set_exception(module_inst, "out of bounds memory access");
  159. os_longjmp(jmpbuf_node->jmpbuf, 1);
  160. }
  161. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  162. else if (stack_min_addr - page_size <= (uint8 *)sig_addr
  163. && (uint8 *)sig_addr
  164. < stack_min_addr + page_size * guard_page_count) {
  165. /* The address which causes segmentation fault is inside
  166. native thread's guard page */
  167. wasm_set_exception(module_inst, "native stack overflow");
  168. os_longjmp(jmpbuf_node->jmpbuf, 1);
  169. }
  170. #endif
  171. else if (exec_env_tls->exce_check_guard_page <= (uint8 *)sig_addr
  172. && (uint8 *)sig_addr
  173. < exec_env_tls->exce_check_guard_page + page_size) {
  174. bh_assert(wasm_copy_exception(module_inst, NULL));
  175. os_longjmp(jmpbuf_node->jmpbuf, 1);
  176. }
  177. }
  178. }
  179. #else
  180. static LONG
  181. runtime_exception_handler(EXCEPTION_POINTERS *exce_info)
  182. {
  183. PEXCEPTION_RECORD ExceptionRecord = exce_info->ExceptionRecord;
  184. uint8 *sig_addr = (uint8 *)ExceptionRecord->ExceptionInformation[1];
  185. WASMModuleInstance *module_inst;
  186. WASMMemoryInstance *memory_inst;
  187. WASMJmpBuf *jmpbuf_node;
  188. uint8 *mapped_mem_start_addr = NULL;
  189. uint8 *mapped_mem_end_addr = NULL;
  190. uint32 page_size = os_getpagesize();
  191. if (exec_env_tls && exec_env_tls->handle == os_self_thread()
  192. && (jmpbuf_node = exec_env_tls->jmpbuf_stack_top)) {
  193. module_inst = (WASMModuleInstance *)exec_env_tls->module_inst;
  194. if (ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
  195. /* Get the default memory instance */
  196. memory_inst = wasm_get_default_memory(module_inst);
  197. if (memory_inst) {
  198. mapped_mem_start_addr = memory_inst->memory_data;
  199. mapped_mem_end_addr =
  200. memory_inst->memory_data + 8 * (uint64)BH_GB;
  201. }
  202. if (memory_inst && mapped_mem_start_addr <= (uint8 *)sig_addr
  203. && (uint8 *)sig_addr < mapped_mem_end_addr) {
  204. /* The address which causes segmentation fault is inside
  205. the memory instance's guard regions.
  206. Set exception and let the wasm func continue to run, when
  207. the wasm func returns, the caller will check whether the
  208. exception is thrown and return to runtime. */
  209. wasm_set_exception(module_inst, "out of bounds memory access");
  210. if (module_inst->module_type == Wasm_Module_Bytecode) {
  211. /* Continue to search next exception handler for
  212. interpreter mode as it can be caught by
  213. `__try { .. } __except { .. }` sentences in
  214. wasm_runtime.c */
  215. return EXCEPTION_CONTINUE_SEARCH;
  216. }
  217. else {
  218. /* Skip current instruction and continue to run for
  219. AOT mode. TODO: implement unwind support for AOT
  220. code in Windows platform */
  221. exce_info->ContextRecord->Rip++;
  222. return EXCEPTION_CONTINUE_EXECUTION;
  223. }
  224. }
  225. else if (exec_env_tls->exce_check_guard_page <= (uint8 *)sig_addr
  226. && (uint8 *)sig_addr
  227. < exec_env_tls->exce_check_guard_page + page_size) {
  228. bh_assert(wasm_copy_exception(module_inst, NULL));
  229. if (module_inst->module_type == Wasm_Module_Bytecode) {
  230. return EXCEPTION_CONTINUE_SEARCH;
  231. }
  232. else {
  233. exce_info->ContextRecord->Rip++;
  234. return EXCEPTION_CONTINUE_EXECUTION;
  235. }
  236. }
  237. }
  238. #if WASM_DISABLE_STACK_HW_BOUND_CHECK == 0
  239. else if (ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
  240. /* Set stack overflow exception and let the wasm func continue
  241. to run, when the wasm func returns, the caller will check
  242. whether the exception is thrown and return to runtime, and
  243. the damaged stack will be recovered by _resetstkoflw(). */
  244. wasm_set_exception(module_inst, "native stack overflow");
  245. if (module_inst->module_type == Wasm_Module_Bytecode) {
  246. return EXCEPTION_CONTINUE_SEARCH;
  247. }
  248. else {
  249. return EXCEPTION_CONTINUE_EXECUTION;
  250. }
  251. }
  252. #endif
  253. }
  254. os_printf("Unhandled exception thrown: exception code: 0x%lx, "
  255. "exception address: %p, exception information: %p\n",
  256. ExceptionRecord->ExceptionCode, ExceptionRecord->ExceptionAddress,
  257. sig_addr);
  258. return EXCEPTION_CONTINUE_SEARCH;
  259. }
  260. #endif /* end of BH_PLATFORM_WINDOWS */
  261. static bool
  262. runtime_signal_init()
  263. {
  264. #ifndef BH_PLATFORM_WINDOWS
  265. return os_thread_signal_init(runtime_signal_handler) == 0 ? true : false;
  266. #else
  267. if (os_thread_signal_init() != 0)
  268. return false;
  269. if (!AddVectoredExceptionHandler(1, runtime_exception_handler)) {
  270. os_thread_signal_destroy();
  271. return false;
  272. }
  273. #endif
  274. return true;
  275. }
  276. static void
  277. runtime_signal_destroy()
  278. {
  279. #ifdef BH_PLATFORM_WINDOWS
  280. RemoveVectoredExceptionHandler(runtime_exception_handler);
  281. #endif
  282. os_thread_signal_destroy();
  283. }
  284. void
  285. wasm_runtime_set_exec_env_tls(WASMExecEnv *exec_env)
  286. {
  287. exec_env_tls = exec_env;
  288. }
  289. WASMExecEnv *
  290. wasm_runtime_get_exec_env_tls()
  291. {
  292. return exec_env_tls;
  293. }
  294. #endif /* end of OS_ENABLE_HW_BOUND_CHECK */
  295. static bool
  296. wasm_runtime_env_init()
  297. {
  298. if (bh_platform_init() != 0)
  299. return false;
  300. if (wasm_native_init() == false) {
  301. goto fail1;
  302. }
  303. #if WASM_ENABLE_MULTI_MODULE
  304. if (BHT_OK != os_mutex_init(&registered_module_list_lock)) {
  305. goto fail2;
  306. }
  307. if (BHT_OK != os_mutex_init(&loading_module_list_lock)) {
  308. goto fail3;
  309. }
  310. #endif
  311. #if WASM_ENABLE_SHARED_MEMORY
  312. if (!wasm_shared_memory_init()) {
  313. goto fail4;
  314. }
  315. #endif
  316. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  317. if (!thread_manager_init()) {
  318. goto fail5;
  319. }
  320. #endif
  321. #ifdef OS_ENABLE_HW_BOUND_CHECK
  322. if (!runtime_signal_init()) {
  323. goto fail6;
  324. }
  325. #endif
  326. #if WASM_ENABLE_AOT != 0
  327. #if WASM_ENABLE_DEBUG_AOT != 0
  328. if (!jit_debug_engine_init()) {
  329. goto fail7;
  330. }
  331. #endif
  332. #endif
  333. #if WASM_ENABLE_REF_TYPES != 0
  334. if (!wasm_externref_map_init()) {
  335. goto fail8;
  336. }
  337. #endif
  338. #if WASM_ENABLE_FAST_JIT != 0
  339. if (!jit_compiler_init(&jit_options)) {
  340. goto fail9;
  341. }
  342. #endif
  343. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  344. if (!aot_compiler_init()) {
  345. goto fail10;
  346. }
  347. #endif
  348. return true;
  349. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  350. fail10:
  351. #if WASM_ENABLE_FAST_JIT != 0
  352. jit_compiler_destroy();
  353. #endif
  354. #endif
  355. #if WASM_ENABLE_FAST_JIT != 0
  356. fail9:
  357. #if WASM_ENABLE_REF_TYPES != 0
  358. wasm_externref_map_destroy();
  359. #endif
  360. #endif
  361. #if WASM_ENABLE_REF_TYPES != 0
  362. fail8:
  363. #endif
  364. #if WASM_ENABLE_AOT != 0
  365. #if WASM_ENABLE_DEBUG_AOT != 0
  366. jit_debug_engine_destroy();
  367. fail7:
  368. #endif
  369. #endif
  370. #ifdef OS_ENABLE_HW_BOUND_CHECK
  371. runtime_signal_destroy();
  372. fail6:
  373. #endif
  374. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  375. thread_manager_destroy();
  376. fail5:
  377. #endif
  378. #if WASM_ENABLE_SHARED_MEMORY
  379. wasm_shared_memory_destroy();
  380. fail4:
  381. #endif
  382. #if WASM_ENABLE_MULTI_MODULE
  383. os_mutex_destroy(&loading_module_list_lock);
  384. fail3:
  385. os_mutex_destroy(&registered_module_list_lock);
  386. fail2:
  387. #endif
  388. wasm_native_destroy();
  389. fail1:
  390. bh_platform_destroy();
  391. return false;
  392. }
  393. static bool
  394. wasm_runtime_exec_env_check(WASMExecEnv *exec_env)
  395. {
  396. return exec_env && exec_env->module_inst && exec_env->wasm_stack_size > 0
  397. && exec_env->wasm_stack.s.top_boundary
  398. == exec_env->wasm_stack.s.bottom + exec_env->wasm_stack_size
  399. && exec_env->wasm_stack.s.top <= exec_env->wasm_stack.s.top_boundary;
  400. }
  401. bool
  402. wasm_runtime_init()
  403. {
  404. if (!wasm_runtime_memory_init(Alloc_With_System_Allocator, NULL))
  405. return false;
  406. if (!wasm_runtime_env_init()) {
  407. wasm_runtime_memory_destroy();
  408. return false;
  409. }
  410. return true;
  411. }
  412. void
  413. wasm_runtime_destroy()
  414. {
  415. #if WASM_ENABLE_REF_TYPES != 0
  416. wasm_externref_map_destroy();
  417. #endif
  418. #if WASM_ENABLE_AOT != 0
  419. #if WASM_ENABLE_DEBUG_AOT != 0
  420. jit_debug_engine_destroy();
  421. #endif
  422. #endif
  423. #ifdef OS_ENABLE_HW_BOUND_CHECK
  424. runtime_signal_destroy();
  425. #endif
  426. /* runtime env destroy */
  427. #if WASM_ENABLE_MULTI_MODULE
  428. wasm_runtime_destroy_loading_module_list();
  429. os_mutex_destroy(&loading_module_list_lock);
  430. wasm_runtime_destroy_registered_module_list();
  431. os_mutex_destroy(&registered_module_list_lock);
  432. #endif
  433. #if WASM_ENABLE_JIT != 0 || WASM_ENABLE_WAMR_COMPILER != 0
  434. /* Destroy LLVM-JIT compiler after destroying the modules
  435. * loaded by multi-module feature, since these modules may
  436. * create backend threads to compile the wasm functions,
  437. * which may access the LLVM resources. We wait until they
  438. * finish the compilation to avoid accessing the destroyed
  439. * resources in the compilation threads.
  440. */
  441. aot_compiler_destroy();
  442. #endif
  443. #if WASM_ENABLE_FAST_JIT != 0
  444. /* Destroy Fast-JIT compiler after destroying the modules
  445. * loaded by multi-module feature, since the Fast JIT's
  446. * code cache allocator may be used by these modules.
  447. */
  448. jit_compiler_destroy();
  449. #endif
  450. #if WASM_ENABLE_SHARED_MEMORY
  451. wasm_shared_memory_destroy();
  452. #endif
  453. #if (WASM_ENABLE_WAMR_COMPILER == 0) && (WASM_ENABLE_THREAD_MGR != 0)
  454. #if WASM_ENABLE_DEBUG_INTERP != 0
  455. wasm_debug_engine_destroy();
  456. #endif
  457. thread_manager_destroy();
  458. #endif
  459. wasm_native_destroy();
  460. bh_platform_destroy();
  461. wasm_runtime_memory_destroy();
  462. }
  463. RunningMode
  464. wasm_runtime_get_default_running_mode(void)
  465. {
  466. return runtime_running_mode;
  467. }
  468. #if WASM_ENABLE_JIT != 0
  469. LLVMJITOptions
  470. wasm_runtime_get_llvm_jit_options(void)
  471. {
  472. return llvm_jit_options;
  473. }
  474. #endif
  475. bool
  476. wasm_runtime_full_init(RuntimeInitArgs *init_args)
  477. {
  478. if (!wasm_runtime_memory_init(init_args->mem_alloc_type,
  479. &init_args->mem_alloc_option))
  480. return false;
  481. if (!wasm_runtime_set_default_running_mode(init_args->running_mode)) {
  482. wasm_runtime_memory_destroy();
  483. return false;
  484. }
  485. #if WASM_ENABLE_FAST_JIT != 0
  486. jit_options.code_cache_size = init_args->fast_jit_code_cache_size;
  487. #endif
  488. #if WASM_ENABLE_JIT != 0
  489. llvm_jit_options.size_level = init_args->llvm_jit_size_level;
  490. llvm_jit_options.opt_level = init_args->llvm_jit_opt_level;
  491. llvm_jit_options.segue_flags = init_args->segue_flags;
  492. #endif
  493. if (!wasm_runtime_env_init()) {
  494. wasm_runtime_memory_destroy();
  495. return false;
  496. }
  497. #if WASM_ENABLE_DEBUG_INTERP != 0
  498. if (strlen(init_args->ip_addr))
  499. if (!wasm_debug_engine_init(init_args->ip_addr,
  500. init_args->instance_port)) {
  501. wasm_runtime_destroy();
  502. return false;
  503. }
  504. #endif
  505. if (init_args->n_native_symbols > 0
  506. && !wasm_runtime_register_natives(init_args->native_module_name,
  507. init_args->native_symbols,
  508. init_args->n_native_symbols)) {
  509. wasm_runtime_destroy();
  510. return false;
  511. }
  512. #if WASM_ENABLE_THREAD_MGR != 0
  513. wasm_cluster_set_max_thread_num(init_args->max_thread_num);
  514. #endif
  515. return true;
  516. }
  517. bool
  518. wasm_runtime_is_running_mode_supported(RunningMode running_mode)
  519. {
  520. if (running_mode == Mode_Default) {
  521. return true;
  522. }
  523. else if (running_mode == Mode_Interp) {
  524. #if WASM_ENABLE_INTERP != 0
  525. return true;
  526. #endif
  527. }
  528. else if (running_mode == Mode_Fast_JIT) {
  529. #if WASM_ENABLE_FAST_JIT != 0
  530. return true;
  531. #endif
  532. }
  533. else if (running_mode == Mode_LLVM_JIT) {
  534. #if WASM_ENABLE_JIT != 0
  535. return true;
  536. #endif
  537. }
  538. else if (running_mode == Mode_Multi_Tier_JIT) {
  539. #if WASM_ENABLE_FAST_JIT != 0 && WASM_ENABLE_JIT != 0 \
  540. && WASM_ENABLE_LAZY_JIT != 0
  541. return true;
  542. #endif
  543. }
  544. return false;
  545. }
  546. bool
  547. wasm_runtime_set_default_running_mode(RunningMode running_mode)
  548. {
  549. if (wasm_runtime_is_running_mode_supported(running_mode)) {
  550. runtime_running_mode = running_mode;
  551. return true;
  552. }
  553. return false;
  554. }
  555. PackageType
  556. get_package_type(const uint8 *buf, uint32 size)
  557. {
  558. #if (WASM_ENABLE_WORD_ALIGN_READ != 0)
  559. uint32 buf32 = *(uint32 *)buf;
  560. buf = (const uint8 *)&buf32;
  561. #endif
  562. if (buf && size >= 4) {
  563. if (buf[0] == '\0' && buf[1] == 'a' && buf[2] == 's' && buf[3] == 'm')
  564. return Wasm_Module_Bytecode;
  565. if (buf[0] == '\0' && buf[1] == 'a' && buf[2] == 'o' && buf[3] == 't')
  566. return Wasm_Module_AoT;
  567. }
  568. return Package_Type_Unknown;
  569. }
  570. #if WASM_ENABLE_AOT != 0
  571. static uint8 *
  572. align_ptr(const uint8 *p, uint32 b)
  573. {
  574. uintptr_t v = (uintptr_t)p;
  575. uintptr_t m = b - 1;
  576. return (uint8 *)((v + m) & ~m);
  577. }
  578. #define CHECK_BUF(buf, buf_end, length) \
  579. do { \
  580. if ((uintptr_t)buf + length < (uintptr_t)buf \
  581. || (uintptr_t)buf + length > (uintptr_t)buf_end) \
  582. return false; \
  583. } while (0)
  584. #define read_uint16(p, p_end, res) \
  585. do { \
  586. p = (uint8 *)align_ptr(p, sizeof(uint16)); \
  587. CHECK_BUF(p, p_end, sizeof(uint16)); \
  588. res = *(uint16 *)p; \
  589. p += sizeof(uint16); \
  590. } while (0)
  591. #define read_uint32(p, p_end, res) \
  592. do { \
  593. p = (uint8 *)align_ptr(p, sizeof(uint32)); \
  594. CHECK_BUF(p, p_end, sizeof(uint32)); \
  595. res = *(uint32 *)p; \
  596. p += sizeof(uint32); \
  597. } while (0)
  598. bool
  599. wasm_runtime_is_xip_file(const uint8 *buf, uint32 size)
  600. {
  601. const uint8 *p = buf, *p_end = buf + size;
  602. uint32 section_type, section_size;
  603. uint16 e_type;
  604. if (get_package_type(buf, size) != Wasm_Module_AoT)
  605. return false;
  606. CHECK_BUF(p, p_end, 8);
  607. p += 8;
  608. while (p < p_end) {
  609. read_uint32(p, p_end, section_type);
  610. read_uint32(p, p_end, section_size);
  611. CHECK_BUF(p, p_end, section_size);
  612. if (section_type == AOT_SECTION_TYPE_TARGET_INFO) {
  613. p += 4;
  614. read_uint16(p, p_end, e_type);
  615. return (e_type == E_TYPE_XIP) ? true : false;
  616. }
  617. else if (section_type >= AOT_SECTION_TYPE_SIGANATURE) {
  618. return false;
  619. }
  620. p += section_size;
  621. }
  622. return false;
  623. }
  624. #endif /* end of WASM_ENABLE_AOT */
  625. #if (WASM_ENABLE_THREAD_MGR != 0) && (WASM_ENABLE_DEBUG_INTERP != 0)
  626. uint32
  627. wasm_runtime_start_debug_instance_with_port(WASMExecEnv *exec_env, int32_t port)
  628. {
  629. WASMModuleInstanceCommon *module_inst =
  630. wasm_runtime_get_module_inst(exec_env);
  631. WASMCluster *cluster = wasm_exec_env_get_cluster(exec_env);
  632. bh_assert(module_inst);
  633. bh_assert(cluster);
  634. if (module_inst->module_type != Wasm_Module_Bytecode) {
  635. LOG_WARNING("Attempt to create a debug instance for an AOT module");
  636. return 0;
  637. }
  638. if (cluster->debug_inst) {
  639. LOG_WARNING("Cluster already bind to a debug instance");
  640. return cluster->debug_inst->control_thread->port;
  641. }
  642. if (wasm_debug_instance_create(cluster, port)) {
  643. return cluster->debug_inst->control_thread->port;
  644. }
  645. return 0;
  646. }
  647. uint32
  648. wasm_runtime_start_debug_instance(WASMExecEnv *exec_env)
  649. {
  650. return wasm_runtime_start_debug_instance_with_port(exec_env, -1);
  651. }
  652. #endif
  653. #if WASM_ENABLE_MULTI_MODULE != 0
  654. static module_reader reader;
  655. static module_destroyer destroyer;
  656. void
  657. wasm_runtime_set_module_reader(const module_reader reader_cb,
  658. const module_destroyer destroyer_cb)
  659. {
  660. reader = reader_cb;
  661. destroyer = destroyer_cb;
  662. }
  663. module_reader
  664. wasm_runtime_get_module_reader()
  665. {
  666. return reader;
  667. }
  668. module_destroyer
  669. wasm_runtime_get_module_destroyer()
  670. {
  671. return destroyer;
  672. }
  673. static WASMRegisteredModule *
  674. wasm_runtime_find_module_registered_by_reference(WASMModuleCommon *module)
  675. {
  676. WASMRegisteredModule *reg_module = NULL;
  677. os_mutex_lock(&registered_module_list_lock);
  678. reg_module = bh_list_first_elem(registered_module_list);
  679. while (reg_module && module != reg_module->module) {
  680. reg_module = bh_list_elem_next(reg_module);
  681. }
  682. os_mutex_unlock(&registered_module_list_lock);
  683. return reg_module;
  684. }
  685. bool
  686. wasm_runtime_register_module_internal(const char *module_name,
  687. WASMModuleCommon *module,
  688. uint8 *orig_file_buf,
  689. uint32 orig_file_buf_size,
  690. char *error_buf, uint32 error_buf_size)
  691. {
  692. WASMRegisteredModule *node = NULL;
  693. node = wasm_runtime_find_module_registered_by_reference(module);
  694. if (node) { /* module has been registered */
  695. if (node->module_name) { /* module has name */
  696. if (!module_name || strcmp(node->module_name, module_name)) {
  697. /* module has different name */
  698. LOG_DEBUG("module(%p) has been registered with name %s", module,
  699. node->module_name);
  700. set_error_buf(error_buf, error_buf_size,
  701. "Register module failed: "
  702. "failed to rename the module");
  703. return false;
  704. }
  705. else {
  706. /* module has the same name */
  707. LOG_DEBUG(
  708. "module(%p) has been registered with the same name %s",
  709. module, node->module_name);
  710. return true;
  711. }
  712. }
  713. else {
  714. /* module has empyt name, reset it */
  715. node->module_name = module_name;
  716. return true;
  717. }
  718. }
  719. /* module hasn't been registered */
  720. node = runtime_malloc(sizeof(WASMRegisteredModule), NULL, NULL, 0);
  721. if (!node) {
  722. LOG_DEBUG("malloc WASMRegisteredModule failed. SZ=%d",
  723. sizeof(WASMRegisteredModule));
  724. return false;
  725. }
  726. /* share the string and the module */
  727. node->module_name = module_name;
  728. node->module = module;
  729. node->orig_file_buf = orig_file_buf;
  730. node->orig_file_buf_size = orig_file_buf_size;
  731. os_mutex_lock(&registered_module_list_lock);
  732. bh_list_status ret = bh_list_insert(registered_module_list, node);
  733. bh_assert(BH_LIST_SUCCESS == ret);
  734. (void)ret;
  735. os_mutex_unlock(&registered_module_list_lock);
  736. return true;
  737. }
  738. bool
  739. wasm_runtime_register_module(const char *module_name, WASMModuleCommon *module,
  740. char *error_buf, uint32 error_buf_size)
  741. {
  742. if (!error_buf || !error_buf_size) {
  743. LOG_ERROR("error buffer is required");
  744. return false;
  745. }
  746. if (!module_name || !module) {
  747. LOG_DEBUG("module_name and module are required");
  748. set_error_buf(error_buf, error_buf_size,
  749. "Register module failed: "
  750. "module_name and module are required");
  751. return false;
  752. }
  753. if (wasm_runtime_is_built_in_module(module_name)) {
  754. LOG_DEBUG("%s is a built-in module name", module_name);
  755. set_error_buf(error_buf, error_buf_size,
  756. "Register module failed: "
  757. "can not register as a built-in module");
  758. return false;
  759. }
  760. return wasm_runtime_register_module_internal(module_name, module, NULL, 0,
  761. error_buf, error_buf_size);
  762. }
  763. void
  764. wasm_runtime_unregister_module(const WASMModuleCommon *module)
  765. {
  766. WASMRegisteredModule *registered_module = NULL;
  767. os_mutex_lock(&registered_module_list_lock);
  768. registered_module = bh_list_first_elem(registered_module_list);
  769. while (registered_module && module != registered_module->module) {
  770. registered_module = bh_list_elem_next(registered_module);
  771. }
  772. /* it does not matter if it is not exist. after all, it is gone */
  773. if (registered_module) {
  774. bh_list_remove(registered_module_list, registered_module);
  775. wasm_runtime_free(registered_module);
  776. }
  777. os_mutex_unlock(&registered_module_list_lock);
  778. }
  779. WASMModuleCommon *
  780. wasm_runtime_find_module_registered(const char *module_name)
  781. {
  782. WASMRegisteredModule *module = NULL, *module_next;
  783. os_mutex_lock(&registered_module_list_lock);
  784. module = bh_list_first_elem(registered_module_list);
  785. while (module) {
  786. module_next = bh_list_elem_next(module);
  787. if (module->module_name && !strcmp(module_name, module->module_name)) {
  788. break;
  789. }
  790. module = module_next;
  791. }
  792. os_mutex_unlock(&registered_module_list_lock);
  793. return module ? module->module : NULL;
  794. }
  795. /*
  796. * simply destroy all
  797. */
  798. static void
  799. wasm_runtime_destroy_registered_module_list()
  800. {
  801. WASMRegisteredModule *reg_module = NULL;
  802. os_mutex_lock(&registered_module_list_lock);
  803. reg_module = bh_list_first_elem(registered_module_list);
  804. while (reg_module) {
  805. WASMRegisteredModule *next_reg_module = bh_list_elem_next(reg_module);
  806. bh_list_remove(registered_module_list, reg_module);
  807. /* now, it is time to release every module in the runtime */
  808. if (reg_module->module->module_type == Wasm_Module_Bytecode) {
  809. #if WASM_ENABLE_INTERP != 0
  810. wasm_unload((WASMModule *)reg_module->module);
  811. #endif
  812. }
  813. else {
  814. #if WASM_ENABLE_AOT != 0
  815. aot_unload((AOTModule *)reg_module->module);
  816. #endif
  817. }
  818. /* destroy the file buffer */
  819. if (destroyer && reg_module->orig_file_buf) {
  820. destroyer(reg_module->orig_file_buf,
  821. reg_module->orig_file_buf_size);
  822. reg_module->orig_file_buf = NULL;
  823. reg_module->orig_file_buf_size = 0;
  824. }
  825. wasm_runtime_free(reg_module);
  826. reg_module = next_reg_module;
  827. }
  828. os_mutex_unlock(&registered_module_list_lock);
  829. }
  830. bool
  831. wasm_runtime_add_loading_module(const char *module_name, char *error_buf,
  832. uint32 error_buf_size)
  833. {
  834. LOG_DEBUG("add %s into a loading list", module_name);
  835. LoadingModule *loadingModule =
  836. runtime_malloc(sizeof(LoadingModule), NULL, error_buf, error_buf_size);
  837. if (!loadingModule) {
  838. return false;
  839. }
  840. /* share the incoming string */
  841. loadingModule->module_name = module_name;
  842. os_mutex_lock(&loading_module_list_lock);
  843. bh_list_status ret = bh_list_insert(loading_module_list, loadingModule);
  844. bh_assert(BH_LIST_SUCCESS == ret);
  845. (void)ret;
  846. os_mutex_unlock(&loading_module_list_lock);
  847. return true;
  848. }
  849. void
  850. wasm_runtime_delete_loading_module(const char *module_name)
  851. {
  852. LOG_DEBUG("delete %s from a loading list", module_name);
  853. LoadingModule *module = NULL;
  854. os_mutex_lock(&loading_module_list_lock);
  855. module = bh_list_first_elem(loading_module_list);
  856. while (module && strcmp(module->module_name, module_name)) {
  857. module = bh_list_elem_next(module);
  858. }
  859. /* it does not matter if it is not exist. after all, it is gone */
  860. if (module) {
  861. bh_list_remove(loading_module_list, module);
  862. wasm_runtime_free(module);
  863. }
  864. os_mutex_unlock(&loading_module_list_lock);
  865. }
  866. bool
  867. wasm_runtime_is_loading_module(const char *module_name)
  868. {
  869. LOG_DEBUG("find %s in a loading list", module_name);
  870. LoadingModule *module = NULL;
  871. os_mutex_lock(&loading_module_list_lock);
  872. module = bh_list_first_elem(loading_module_list);
  873. while (module && strcmp(module_name, module->module_name)) {
  874. module = bh_list_elem_next(module);
  875. }
  876. os_mutex_unlock(&loading_module_list_lock);
  877. return module != NULL;
  878. }
  879. void
  880. wasm_runtime_destroy_loading_module_list()
  881. {
  882. LoadingModule *module = NULL;
  883. os_mutex_lock(&loading_module_list_lock);
  884. module = bh_list_first_elem(loading_module_list);
  885. while (module) {
  886. LoadingModule *next_module = bh_list_elem_next(module);
  887. bh_list_remove(loading_module_list, module);
  888. /*
  889. * will not free the module_name since it is
  890. * shared one of the const string pool
  891. */
  892. wasm_runtime_free(module);
  893. module = next_module;
  894. }
  895. os_mutex_unlock(&loading_module_list_lock);
  896. }
  897. #endif /* WASM_ENABLE_MULTI_MODULE */
  898. bool
  899. wasm_runtime_is_built_in_module(const char *module_name)
  900. {
  901. return (!strcmp("env", module_name) || !strcmp("wasi_unstable", module_name)
  902. || !strcmp("wasi_snapshot_preview1", module_name)
  903. #if WASM_ENABLE_SPEC_TEST != 0
  904. || !strcmp("spectest", module_name)
  905. #endif
  906. || !strcmp("", module_name));
  907. }
  908. #if WASM_ENABLE_THREAD_MGR != 0
  909. bool
  910. wasm_exec_env_set_aux_stack(WASMExecEnv *exec_env, uint32 start_offset,
  911. uint32 size)
  912. {
  913. WASMModuleInstanceCommon *module_inst =
  914. wasm_exec_env_get_module_inst(exec_env);
  915. #if WASM_ENABLE_INTERP != 0
  916. if (module_inst->module_type == Wasm_Module_Bytecode) {
  917. return wasm_set_aux_stack(exec_env, start_offset, size);
  918. }
  919. #endif
  920. #if WASM_ENABLE_AOT != 0
  921. if (module_inst->module_type == Wasm_Module_AoT) {
  922. return aot_set_aux_stack(exec_env, start_offset, size);
  923. }
  924. #endif
  925. return false;
  926. }
  927. bool
  928. wasm_exec_env_get_aux_stack(WASMExecEnv *exec_env, uint32 *start_offset,
  929. uint32 *size)
  930. {
  931. WASMModuleInstanceCommon *module_inst =
  932. wasm_exec_env_get_module_inst(exec_env);
  933. #if WASM_ENABLE_INTERP != 0
  934. if (module_inst->module_type == Wasm_Module_Bytecode) {
  935. return wasm_get_aux_stack(exec_env, start_offset, size);
  936. }
  937. #endif
  938. #if WASM_ENABLE_AOT != 0
  939. if (module_inst->module_type == Wasm_Module_AoT) {
  940. return aot_get_aux_stack(exec_env, start_offset, size);
  941. }
  942. #endif
  943. return false;
  944. }
  945. void
  946. wasm_runtime_set_max_thread_num(uint32 num)
  947. {
  948. wasm_cluster_set_max_thread_num(num);
  949. }
  950. #endif /* end of WASM_ENABLE_THREAD_MGR */
  951. static WASMModuleCommon *
  952. register_module_with_null_name(WASMModuleCommon *module_common, char *error_buf,
  953. uint32 error_buf_size)
  954. {
  955. #if WASM_ENABLE_MULTI_MODULE != 0
  956. if (module_common) {
  957. if (!wasm_runtime_register_module_internal(NULL, module_common, NULL, 0,
  958. error_buf, error_buf_size)) {
  959. wasm_runtime_unload(module_common);
  960. return NULL;
  961. }
  962. return module_common;
  963. }
  964. else
  965. return NULL;
  966. #else
  967. return module_common;
  968. #endif
  969. }
  970. WASMModuleCommon *
  971. wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf,
  972. uint32 error_buf_size)
  973. {
  974. WASMModuleCommon *module_common = NULL;
  975. if (get_package_type(buf, size) == Wasm_Module_Bytecode) {
  976. #if WASM_ENABLE_INTERP != 0
  977. module_common =
  978. (WASMModuleCommon *)wasm_load(buf, size, error_buf, error_buf_size);
  979. return register_module_with_null_name(module_common, error_buf,
  980. error_buf_size);
  981. #endif
  982. }
  983. else if (get_package_type(buf, size) == Wasm_Module_AoT) {
  984. #if WASM_ENABLE_AOT != 0
  985. module_common = (WASMModuleCommon *)aot_load_from_aot_file(
  986. buf, size, error_buf, error_buf_size);
  987. return register_module_with_null_name(module_common, error_buf,
  988. error_buf_size);
  989. #endif
  990. }
  991. if (size < 4)
  992. set_error_buf(error_buf, error_buf_size,
  993. "WASM module load failed: unexpected end");
  994. else
  995. set_error_buf(error_buf, error_buf_size,
  996. "WASM module load failed: magic header not detected");
  997. return NULL;
  998. }
  999. WASMModuleCommon *
  1000. wasm_runtime_load_from_sections(WASMSection *section_list, bool is_aot,
  1001. char *error_buf, uint32 error_buf_size)
  1002. {
  1003. WASMModuleCommon *module_common;
  1004. if (!is_aot) {
  1005. #if WASM_ENABLE_INTERP != 0
  1006. module_common = (WASMModuleCommon *)wasm_load_from_sections(
  1007. section_list, error_buf, error_buf_size);
  1008. return register_module_with_null_name(module_common, error_buf,
  1009. error_buf_size);
  1010. #endif
  1011. }
  1012. else {
  1013. #if WASM_ENABLE_AOT != 0
  1014. module_common = (WASMModuleCommon *)aot_load_from_sections(
  1015. section_list, error_buf, error_buf_size);
  1016. return register_module_with_null_name(module_common, error_buf,
  1017. error_buf_size);
  1018. #endif
  1019. }
  1020. #if WASM_ENABLE_INTERP == 0 || WASM_ENABLE_AOT == 0
  1021. set_error_buf(error_buf, error_buf_size,
  1022. "WASM module load failed: invalid section list type");
  1023. return NULL;
  1024. #endif
  1025. }
  1026. void
  1027. wasm_runtime_unload(WASMModuleCommon *module)
  1028. {
  1029. #if WASM_ENABLE_MULTI_MODULE != 0
  1030. /**
  1031. * since we will unload and free all module when runtime_destroy()
  1032. * we don't want users to unwillingly disrupt it
  1033. */
  1034. return;
  1035. #endif
  1036. #if WASM_ENABLE_INTERP != 0
  1037. if (module->module_type == Wasm_Module_Bytecode) {
  1038. wasm_unload((WASMModule *)module);
  1039. return;
  1040. }
  1041. #endif
  1042. #if WASM_ENABLE_AOT != 0
  1043. if (module->module_type == Wasm_Module_AoT) {
  1044. aot_unload((AOTModule *)module);
  1045. return;
  1046. }
  1047. #endif
  1048. }
  1049. WASMModuleInstanceCommon *
  1050. wasm_runtime_instantiate_internal(WASMModuleCommon *module, bool is_sub_inst,
  1051. WASMExecEnv *exec_env_main, uint32 stack_size,
  1052. uint32 heap_size, char *error_buf,
  1053. uint32 error_buf_size)
  1054. {
  1055. #if WASM_ENABLE_INTERP != 0
  1056. if (module->module_type == Wasm_Module_Bytecode)
  1057. return (WASMModuleInstanceCommon *)wasm_instantiate(
  1058. (WASMModule *)module, is_sub_inst, exec_env_main, stack_size,
  1059. heap_size, error_buf, error_buf_size);
  1060. #endif
  1061. #if WASM_ENABLE_AOT != 0
  1062. if (module->module_type == Wasm_Module_AoT)
  1063. return (WASMModuleInstanceCommon *)aot_instantiate(
  1064. (AOTModule *)module, is_sub_inst, exec_env_main, stack_size,
  1065. heap_size, error_buf, error_buf_size);
  1066. #endif
  1067. set_error_buf(error_buf, error_buf_size,
  1068. "Instantiate module failed, invalid module type");
  1069. return NULL;
  1070. }
  1071. WASMModuleInstanceCommon *
  1072. wasm_runtime_instantiate(WASMModuleCommon *module, uint32 stack_size,
  1073. uint32 heap_size, char *error_buf,
  1074. uint32 error_buf_size)
  1075. {
  1076. return wasm_runtime_instantiate_internal(
  1077. module, false, NULL, stack_size, heap_size, error_buf, error_buf_size);
  1078. }
  1079. void
  1080. wasm_runtime_deinstantiate_internal(WASMModuleInstanceCommon *module_inst,
  1081. bool is_sub_inst)
  1082. {
  1083. #if WASM_ENABLE_INTERP != 0
  1084. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1085. wasm_deinstantiate((WASMModuleInstance *)module_inst, is_sub_inst);
  1086. return;
  1087. }
  1088. #endif
  1089. #if WASM_ENABLE_AOT != 0
  1090. if (module_inst->module_type == Wasm_Module_AoT) {
  1091. aot_deinstantiate((AOTModuleInstance *)module_inst, is_sub_inst);
  1092. return;
  1093. }
  1094. #endif
  1095. }
  1096. bool
  1097. wasm_runtime_set_running_mode(wasm_module_inst_t module_inst,
  1098. RunningMode running_mode)
  1099. {
  1100. #if WASM_ENABLE_AOT != 0
  1101. if (module_inst->module_type == Wasm_Module_AoT)
  1102. return true;
  1103. #endif
  1104. #if WASM_ENABLE_INTERP != 0
  1105. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1106. WASMModuleInstance *module_inst_interp =
  1107. (WASMModuleInstance *)module_inst;
  1108. return wasm_set_running_mode(module_inst_interp, running_mode);
  1109. }
  1110. #endif
  1111. return false;
  1112. }
  1113. RunningMode
  1114. wasm_runtime_get_running_mode(wasm_module_inst_t module_inst)
  1115. {
  1116. #if WASM_ENABLE_INTERP != 0
  1117. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1118. WASMModuleInstance *module_inst_interp =
  1119. (WASMModuleInstance *)module_inst;
  1120. return module_inst_interp->e->running_mode;
  1121. }
  1122. #endif
  1123. return Mode_Default;
  1124. }
  1125. void
  1126. wasm_runtime_deinstantiate(WASMModuleInstanceCommon *module_inst)
  1127. {
  1128. wasm_runtime_deinstantiate_internal(module_inst, false);
  1129. }
  1130. WASMModuleCommon *
  1131. wasm_runtime_get_module(WASMModuleInstanceCommon *module_inst)
  1132. {
  1133. return (WASMModuleCommon *)((WASMModuleInstance *)module_inst)->module;
  1134. }
  1135. WASMExecEnv *
  1136. wasm_runtime_create_exec_env(WASMModuleInstanceCommon *module_inst,
  1137. uint32 stack_size)
  1138. {
  1139. return wasm_exec_env_create(module_inst, stack_size);
  1140. }
  1141. void
  1142. wasm_runtime_destroy_exec_env(WASMExecEnv *exec_env)
  1143. {
  1144. wasm_exec_env_destroy(exec_env);
  1145. }
  1146. bool
  1147. wasm_runtime_init_thread_env(void)
  1148. {
  1149. #ifdef BH_PLATFORM_WINDOWS
  1150. if (os_thread_env_init() != 0)
  1151. return false;
  1152. #endif
  1153. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1154. if (!runtime_signal_init()) {
  1155. #ifdef BH_PLATFORM_WINDOWS
  1156. os_thread_env_destroy();
  1157. #endif
  1158. return false;
  1159. }
  1160. #endif
  1161. return true;
  1162. }
  1163. void
  1164. wasm_runtime_destroy_thread_env(void)
  1165. {
  1166. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1167. runtime_signal_destroy();
  1168. #endif
  1169. #ifdef BH_PLATFORM_WINDOWS
  1170. os_thread_env_destroy();
  1171. #endif
  1172. }
  1173. bool
  1174. wasm_runtime_thread_env_inited(void)
  1175. {
  1176. #ifdef BH_PLATFORM_WINDOWS
  1177. if (!os_thread_env_inited())
  1178. return false;
  1179. #endif
  1180. #if WASM_ENABLE_AOT != 0
  1181. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1182. if (!os_thread_signal_inited())
  1183. return false;
  1184. #endif
  1185. #endif
  1186. return true;
  1187. }
  1188. #if (WASM_ENABLE_MEMORY_PROFILING != 0) || (WASM_ENABLE_MEMORY_TRACING != 0)
  1189. void
  1190. wasm_runtime_dump_module_mem_consumption(const WASMModuleCommon *module)
  1191. {
  1192. WASMModuleMemConsumption mem_conspn = { 0 };
  1193. #if WASM_ENABLE_INTERP != 0
  1194. if (module->module_type == Wasm_Module_Bytecode) {
  1195. wasm_get_module_mem_consumption((WASMModule *)module, &mem_conspn);
  1196. }
  1197. #endif
  1198. #if WASM_ENABLE_AOT != 0
  1199. if (module->module_type == Wasm_Module_AoT) {
  1200. aot_get_module_mem_consumption((AOTModule *)module, &mem_conspn);
  1201. }
  1202. #endif
  1203. os_printf("WASM module memory consumption, total size: %u\n",
  1204. mem_conspn.total_size);
  1205. os_printf(" module struct size: %u\n", mem_conspn.module_struct_size);
  1206. os_printf(" types size: %u\n", mem_conspn.types_size);
  1207. os_printf(" imports size: %u\n", mem_conspn.imports_size);
  1208. os_printf(" funcs size: %u\n", mem_conspn.functions_size);
  1209. os_printf(" tables size: %u\n", mem_conspn.tables_size);
  1210. os_printf(" memories size: %u\n", mem_conspn.memories_size);
  1211. os_printf(" globals size: %u\n", mem_conspn.globals_size);
  1212. os_printf(" exports size: %u\n", mem_conspn.exports_size);
  1213. os_printf(" table segs size: %u\n", mem_conspn.table_segs_size);
  1214. os_printf(" data segs size: %u\n", mem_conspn.data_segs_size);
  1215. os_printf(" const strings size: %u\n", mem_conspn.const_strs_size);
  1216. #if WASM_ENABLE_AOT != 0
  1217. os_printf(" aot code size: %u\n", mem_conspn.aot_code_size);
  1218. #endif
  1219. }
  1220. void
  1221. wasm_runtime_dump_module_inst_mem_consumption(
  1222. const WASMModuleInstanceCommon *module_inst)
  1223. {
  1224. WASMModuleInstMemConsumption mem_conspn = { 0 };
  1225. #if WASM_ENABLE_INTERP != 0
  1226. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1227. wasm_get_module_inst_mem_consumption((WASMModuleInstance *)module_inst,
  1228. &mem_conspn);
  1229. }
  1230. #endif
  1231. #if WASM_ENABLE_AOT != 0
  1232. if (module_inst->module_type == Wasm_Module_AoT) {
  1233. aot_get_module_inst_mem_consumption((AOTModuleInstance *)module_inst,
  1234. &mem_conspn);
  1235. }
  1236. #endif
  1237. os_printf("WASM module inst memory consumption, total size: %u\n",
  1238. mem_conspn.total_size);
  1239. os_printf(" module inst struct size: %u\n",
  1240. mem_conspn.module_inst_struct_size);
  1241. os_printf(" memories size: %u\n", mem_conspn.memories_size);
  1242. os_printf(" app heap size: %u\n", mem_conspn.app_heap_size);
  1243. os_printf(" tables size: %u\n", mem_conspn.tables_size);
  1244. os_printf(" functions size: %u\n", mem_conspn.functions_size);
  1245. os_printf(" globals size: %u\n", mem_conspn.globals_size);
  1246. os_printf(" exports size: %u\n", mem_conspn.exports_size);
  1247. }
  1248. void
  1249. wasm_runtime_dump_exec_env_mem_consumption(const WASMExecEnv *exec_env)
  1250. {
  1251. uint32 total_size =
  1252. offsetof(WASMExecEnv, wasm_stack.s.bottom) + exec_env->wasm_stack_size;
  1253. os_printf("Exec env memory consumption, total size: %u\n", total_size);
  1254. os_printf(" exec env struct size: %u\n",
  1255. offsetof(WASMExecEnv, wasm_stack.s.bottom));
  1256. #if WASM_ENABLE_INTERP != 0 && WASM_ENABLE_FAST_INTERP == 0
  1257. os_printf(" block addr cache size: %u\n",
  1258. sizeof(exec_env->block_addr_cache));
  1259. #endif
  1260. os_printf(" stack size: %u\n", exec_env->wasm_stack_size);
  1261. }
  1262. uint32
  1263. gc_get_heap_highmark_size(void *heap);
  1264. void
  1265. wasm_runtime_dump_mem_consumption(WASMExecEnv *exec_env)
  1266. {
  1267. WASMModuleInstMemConsumption module_inst_mem_consps;
  1268. WASMModuleMemConsumption module_mem_consps;
  1269. WASMModuleInstanceCommon *module_inst_common;
  1270. WASMModuleCommon *module_common = NULL;
  1271. void *heap_handle = NULL;
  1272. uint32 total_size = 0, app_heap_peak_size = 0;
  1273. uint32 max_aux_stack_used = -1;
  1274. module_inst_common = exec_env->module_inst;
  1275. #if WASM_ENABLE_INTERP != 0
  1276. if (module_inst_common->module_type == Wasm_Module_Bytecode) {
  1277. WASMModuleInstance *wasm_module_inst =
  1278. (WASMModuleInstance *)module_inst_common;
  1279. WASMModule *wasm_module = wasm_module_inst->module;
  1280. module_common = (WASMModuleCommon *)wasm_module;
  1281. if (wasm_module_inst->memories) {
  1282. heap_handle = wasm_module_inst->memories[0]->heap_handle;
  1283. }
  1284. wasm_get_module_inst_mem_consumption(wasm_module_inst,
  1285. &module_inst_mem_consps);
  1286. wasm_get_module_mem_consumption(wasm_module, &module_mem_consps);
  1287. if (wasm_module_inst->module->aux_stack_top_global_index != (uint32)-1)
  1288. max_aux_stack_used = wasm_module_inst->e->max_aux_stack_used;
  1289. }
  1290. #endif
  1291. #if WASM_ENABLE_AOT != 0
  1292. if (module_inst_common->module_type == Wasm_Module_AoT) {
  1293. AOTModuleInstance *aot_module_inst =
  1294. (AOTModuleInstance *)module_inst_common;
  1295. AOTModule *aot_module = (AOTModule *)aot_module_inst->module;
  1296. module_common = (WASMModuleCommon *)aot_module;
  1297. if (aot_module_inst->memories) {
  1298. AOTMemoryInstance **memories = aot_module_inst->memories;
  1299. heap_handle = memories[0]->heap_handle;
  1300. }
  1301. aot_get_module_inst_mem_consumption(aot_module_inst,
  1302. &module_inst_mem_consps);
  1303. aot_get_module_mem_consumption(aot_module, &module_mem_consps);
  1304. }
  1305. #endif
  1306. bh_assert(module_common != NULL);
  1307. if (heap_handle) {
  1308. app_heap_peak_size = gc_get_heap_highmark_size(heap_handle);
  1309. }
  1310. total_size = offsetof(WASMExecEnv, wasm_stack.s.bottom)
  1311. + exec_env->wasm_stack_size + module_mem_consps.total_size
  1312. + module_inst_mem_consps.total_size;
  1313. os_printf("\nMemory consumption summary (bytes):\n");
  1314. wasm_runtime_dump_module_mem_consumption(module_common);
  1315. wasm_runtime_dump_module_inst_mem_consumption(module_inst_common);
  1316. wasm_runtime_dump_exec_env_mem_consumption(exec_env);
  1317. os_printf("\nTotal memory consumption of module, module inst and "
  1318. "exec env: %u\n",
  1319. total_size);
  1320. os_printf("Total interpreter stack used: %u\n",
  1321. exec_env->max_wasm_stack_used);
  1322. if (max_aux_stack_used != (uint32)-1)
  1323. os_printf("Total auxiliary stack used: %u\n", max_aux_stack_used);
  1324. else
  1325. os_printf("Total aux stack used: no enough info to profile\n");
  1326. /*
  1327. * Report the native stack usage estimation.
  1328. *
  1329. * Unlike the aux stack above, we report the amount unused
  1330. * because we don't know the stack "bottom".
  1331. *
  1332. * Note that this is just about what the runtime itself observed.
  1333. * It doesn't cover host func implementations, signal handlers, etc.
  1334. */
  1335. if (exec_env->native_stack_top_min != (void *)UINTPTR_MAX)
  1336. os_printf("Native stack left: %zd\n",
  1337. exec_env->native_stack_top_min
  1338. - exec_env->native_stack_boundary);
  1339. else
  1340. os_printf("Native stack left: no enough info to profile\n");
  1341. os_printf("Total app heap used: %u\n", app_heap_peak_size);
  1342. }
  1343. #endif /* end of (WASM_ENABLE_MEMORY_PROFILING != 0) \
  1344. || (WASM_ENABLE_MEMORY_TRACING != 0) */
  1345. #if WASM_ENABLE_PERF_PROFILING != 0
  1346. void
  1347. wasm_runtime_dump_perf_profiling(WASMModuleInstanceCommon *module_inst)
  1348. {
  1349. #if WASM_ENABLE_INTERP != 0
  1350. if (module_inst->module_type == Wasm_Module_Bytecode) {
  1351. wasm_dump_perf_profiling((WASMModuleInstance *)module_inst);
  1352. }
  1353. #endif
  1354. #if WASM_ENABLE_AOT != 0
  1355. if (module_inst->module_type == Wasm_Module_AoT) {
  1356. aot_dump_perf_profiling((AOTModuleInstance *)module_inst);
  1357. }
  1358. #endif
  1359. }
  1360. #endif
  1361. WASMModuleInstanceCommon *
  1362. wasm_runtime_get_module_inst(WASMExecEnv *exec_env)
  1363. {
  1364. return wasm_exec_env_get_module_inst(exec_env);
  1365. }
  1366. void
  1367. wasm_runtime_set_module_inst(WASMExecEnv *exec_env,
  1368. WASMModuleInstanceCommon *const module_inst)
  1369. {
  1370. wasm_exec_env_set_module_inst(exec_env, module_inst);
  1371. }
  1372. void *
  1373. wasm_runtime_get_function_attachment(WASMExecEnv *exec_env)
  1374. {
  1375. return exec_env->attachment;
  1376. }
  1377. void
  1378. wasm_runtime_set_user_data(WASMExecEnv *exec_env, void *user_data)
  1379. {
  1380. exec_env->user_data = user_data;
  1381. }
  1382. void *
  1383. wasm_runtime_get_user_data(WASMExecEnv *exec_env)
  1384. {
  1385. return exec_env->user_data;
  1386. }
  1387. #ifdef OS_ENABLE_HW_BOUND_CHECK
  1388. void
  1389. wasm_runtime_access_exce_check_guard_page()
  1390. {
  1391. if (exec_env_tls && exec_env_tls->handle == os_self_thread()) {
  1392. uint32 page_size = os_getpagesize();
  1393. memset(exec_env_tls->exce_check_guard_page, 0, page_size);
  1394. }
  1395. }
  1396. #endif
  1397. WASMType *
  1398. wasm_runtime_get_function_type(const WASMFunctionInstanceCommon *function,
  1399. uint32 module_type)
  1400. {
  1401. WASMType *type = NULL;
  1402. #if WASM_ENABLE_INTERP != 0
  1403. if (module_type == Wasm_Module_Bytecode) {
  1404. WASMFunctionInstance *wasm_func = (WASMFunctionInstance *)function;
  1405. type = wasm_func->is_import_func ? wasm_func->u.func_import->func_type
  1406. : wasm_func->u.func->func_type;
  1407. }
  1408. #endif
  1409. #if WASM_ENABLE_AOT != 0
  1410. if (module_type == Wasm_Module_AoT) {
  1411. AOTFunctionInstance *aot_func = (AOTFunctionInstance *)function;
  1412. type = aot_func->is_import_func ? aot_func->u.func_import->func_type
  1413. : aot_func->u.func.func_type;
  1414. }
  1415. #endif
  1416. return type;
  1417. }
  1418. WASMFunctionInstanceCommon *
  1419. wasm_runtime_lookup_function(WASMModuleInstanceCommon *const module_inst,
  1420. const char *name, const char *signature)
  1421. {
  1422. #if WASM_ENABLE_INTERP != 0
  1423. if (module_inst->module_type == Wasm_Module_Bytecode)
  1424. return (WASMFunctionInstanceCommon *)wasm_lookup_function(
  1425. (const WASMModuleInstance *)module_inst, name, signature);
  1426. #endif
  1427. #if WASM_ENABLE_AOT != 0
  1428. if (module_inst->module_type == Wasm_Module_AoT)
  1429. return (WASMFunctionInstanceCommon *)aot_lookup_function(
  1430. (const AOTModuleInstance *)module_inst, name, signature);
  1431. #endif
  1432. return NULL;
  1433. }
  1434. uint32
  1435. wasm_func_get_param_count(WASMFunctionInstanceCommon *const func_inst,
  1436. WASMModuleInstanceCommon *const module_inst)
  1437. {
  1438. WASMType *type =
  1439. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1440. bh_assert(type);
  1441. return type->param_count;
  1442. }
  1443. uint32
  1444. wasm_func_get_result_count(WASMFunctionInstanceCommon *const func_inst,
  1445. WASMModuleInstanceCommon *const module_inst)
  1446. {
  1447. WASMType *type =
  1448. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1449. bh_assert(type);
  1450. return type->result_count;
  1451. }
  1452. static uint8
  1453. val_type_to_val_kind(uint8 value_type)
  1454. {
  1455. switch (value_type) {
  1456. case VALUE_TYPE_I32:
  1457. return WASM_I32;
  1458. case VALUE_TYPE_I64:
  1459. return WASM_I64;
  1460. case VALUE_TYPE_F32:
  1461. return WASM_F32;
  1462. case VALUE_TYPE_F64:
  1463. return WASM_F64;
  1464. case VALUE_TYPE_FUNCREF:
  1465. return WASM_FUNCREF;
  1466. case VALUE_TYPE_EXTERNREF:
  1467. return WASM_ANYREF;
  1468. default:
  1469. bh_assert(0);
  1470. return 0;
  1471. }
  1472. }
  1473. void
  1474. wasm_func_get_param_types(WASMFunctionInstanceCommon *const func_inst,
  1475. WASMModuleInstanceCommon *const module_inst,
  1476. wasm_valkind_t *param_types)
  1477. {
  1478. WASMType *type =
  1479. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1480. uint32 i;
  1481. bh_assert(type);
  1482. for (i = 0; i < type->param_count; i++) {
  1483. param_types[i] = val_type_to_val_kind(type->types[i]);
  1484. }
  1485. }
  1486. void
  1487. wasm_func_get_result_types(WASMFunctionInstanceCommon *const func_inst,
  1488. WASMModuleInstanceCommon *const module_inst,
  1489. wasm_valkind_t *result_types)
  1490. {
  1491. WASMType *type =
  1492. wasm_runtime_get_function_type(func_inst, module_inst->module_type);
  1493. uint32 i;
  1494. bh_assert(type);
  1495. for (i = 0; i < type->result_count; i++) {
  1496. result_types[i] =
  1497. val_type_to_val_kind(type->types[type->param_count + i]);
  1498. }
  1499. }
  1500. #if WASM_ENABLE_REF_TYPES != 0
  1501. /* (uintptr_t)externref -> (uint32)index */
  1502. /* argv -> *ret_argv */
  1503. static bool
  1504. wasm_runtime_prepare_call_function(WASMExecEnv *exec_env,
  1505. WASMFunctionInstanceCommon *function,
  1506. uint32 *argv, uint32 argc, uint32 **ret_argv,
  1507. uint32 *ret_argc_param,
  1508. uint32 *ret_argc_result)
  1509. {
  1510. uint32 *new_argv = NULL, argv_i = 0, new_argv_i = 0, param_i = 0,
  1511. result_i = 0;
  1512. bool need_param_transform = false, need_result_transform = false;
  1513. uint64 size = 0;
  1514. WASMType *func_type = wasm_runtime_get_function_type(
  1515. function, exec_env->module_inst->module_type);
  1516. bh_assert(func_type);
  1517. *ret_argc_param = func_type->param_cell_num;
  1518. *ret_argc_result = func_type->ret_cell_num;
  1519. for (param_i = 0; param_i < func_type->param_count; param_i++) {
  1520. if (VALUE_TYPE_EXTERNREF == func_type->types[param_i]) {
  1521. need_param_transform = true;
  1522. }
  1523. }
  1524. for (result_i = 0; result_i < func_type->result_count; result_i++) {
  1525. if (VALUE_TYPE_EXTERNREF
  1526. == func_type->types[func_type->param_count + result_i]) {
  1527. need_result_transform = true;
  1528. }
  1529. }
  1530. if (!need_param_transform && !need_result_transform) {
  1531. *ret_argv = argv;
  1532. return true;
  1533. }
  1534. if (func_type->param_cell_num >= func_type->ret_cell_num) {
  1535. size = sizeof(uint32) * func_type->param_cell_num;
  1536. }
  1537. else {
  1538. size = sizeof(uint32) * func_type->ret_cell_num;
  1539. }
  1540. if (!(new_argv = runtime_malloc(size, exec_env->module_inst, NULL, 0))) {
  1541. return false;
  1542. }
  1543. if (!need_param_transform) {
  1544. bh_memcpy_s(new_argv, (uint32)size, argv, (uint32)size);
  1545. }
  1546. else {
  1547. for (param_i = 0; param_i < func_type->param_count && argv_i < argc
  1548. && new_argv_i < func_type->param_cell_num;
  1549. param_i++) {
  1550. uint8 param_type = func_type->types[param_i];
  1551. if (VALUE_TYPE_EXTERNREF == param_type) {
  1552. void *externref_obj;
  1553. uint32 externref_index;
  1554. #if UINTPTR_MAX == UINT32_MAX
  1555. externref_obj = (void *)argv[argv_i];
  1556. #else
  1557. union {
  1558. uintptr_t val;
  1559. uint32 parts[2];
  1560. } u;
  1561. u.parts[0] = argv[argv_i];
  1562. u.parts[1] = argv[argv_i + 1];
  1563. externref_obj = (void *)u.val;
  1564. #endif
  1565. if (!wasm_externref_obj2ref(exec_env->module_inst,
  1566. externref_obj, &externref_index)) {
  1567. wasm_runtime_free(new_argv);
  1568. return false;
  1569. }
  1570. new_argv[new_argv_i] = externref_index;
  1571. argv_i += sizeof(uintptr_t) / sizeof(uint32);
  1572. new_argv_i++;
  1573. }
  1574. else {
  1575. uint16 param_cell_num = wasm_value_type_cell_num(param_type);
  1576. uint32 param_size = sizeof(uint32) * param_cell_num;
  1577. bh_memcpy_s(new_argv + new_argv_i, param_size, argv + argv_i,
  1578. param_size);
  1579. argv_i += param_cell_num;
  1580. new_argv_i += param_cell_num;
  1581. }
  1582. }
  1583. }
  1584. *ret_argv = new_argv;
  1585. return true;
  1586. }
  1587. /* (uintptr_t)externref <- (uint32)index */
  1588. /* argv <- new_argv */
  1589. static bool
  1590. wasm_runtime_finalize_call_function(WASMExecEnv *exec_env,
  1591. WASMFunctionInstanceCommon *function,
  1592. uint32 *argv, uint32 argc, uint32 *ret_argv)
  1593. {
  1594. uint32 argv_i = 0, result_i = 0, ret_argv_i = 0;
  1595. WASMType *func_type;
  1596. bh_assert((argv && ret_argv) || (argc == 0));
  1597. if (argv == ret_argv) {
  1598. /* no need to transfrom externref results */
  1599. return true;
  1600. }
  1601. func_type = wasm_runtime_get_function_type(
  1602. function, exec_env->module_inst->module_type);
  1603. bh_assert(func_type);
  1604. for (result_i = 0; result_i < func_type->result_count && argv_i < argc;
  1605. result_i++) {
  1606. uint8 result_type = func_type->types[func_type->param_count + result_i];
  1607. if (result_type == VALUE_TYPE_EXTERNREF) {
  1608. void *externref_obj;
  1609. #if UINTPTR_MAX != UINT32_MAX
  1610. union {
  1611. uintptr_t val;
  1612. uint32 parts[2];
  1613. } u;
  1614. #endif
  1615. if (!wasm_externref_ref2obj(argv[argv_i], &externref_obj)) {
  1616. wasm_runtime_free(argv);
  1617. return false;
  1618. }
  1619. #if UINTPTR_MAX == UINT32_MAX
  1620. ret_argv[ret_argv_i] = (uintptr_t)externref_obj;
  1621. #else
  1622. u.val = (uintptr_t)externref_obj;
  1623. ret_argv[ret_argv_i] = u.parts[0];
  1624. ret_argv[ret_argv_i + 1] = u.parts[1];
  1625. #endif
  1626. argv_i += 1;
  1627. ret_argv_i += sizeof(uintptr_t) / sizeof(uint32);
  1628. }
  1629. else {
  1630. uint16 result_cell_num = wasm_value_type_cell_num(result_type);
  1631. uint32 result_size = sizeof(uint32) * result_cell_num;
  1632. bh_memcpy_s(ret_argv + ret_argv_i, result_size, argv + argv_i,
  1633. result_size);
  1634. argv_i += result_cell_num;
  1635. ret_argv_i += result_cell_num;
  1636. }
  1637. }
  1638. wasm_runtime_free(argv);
  1639. return true;
  1640. }
  1641. #endif
  1642. static bool
  1643. clear_wasi_proc_exit_exception(WASMModuleInstanceCommon *module_inst_comm)
  1644. {
  1645. #if WASM_ENABLE_LIBC_WASI != 0
  1646. bool has_exception;
  1647. char exception[EXCEPTION_BUF_LEN];
  1648. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  1649. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  1650. || module_inst_comm->module_type == Wasm_Module_AoT);
  1651. has_exception = wasm_copy_exception(module_inst, exception);
  1652. if (has_exception && !strcmp(exception, "Exception: wasi proc exit")) {
  1653. /* The "wasi proc exit" exception is thrown by native lib to
  1654. let wasm app exit, which is a normal behavior, we clear
  1655. the exception here. And just clear the exception of current
  1656. thread, don't call `wasm_set_exception(module_inst, NULL)`
  1657. which will clear the exception of all threads. */
  1658. module_inst->cur_exception[0] = '\0';
  1659. return true;
  1660. }
  1661. return false;
  1662. #else
  1663. return false;
  1664. #endif
  1665. }
  1666. bool
  1667. wasm_runtime_call_wasm(WASMExecEnv *exec_env,
  1668. WASMFunctionInstanceCommon *function, uint32 argc,
  1669. uint32 argv[])
  1670. {
  1671. bool ret = false;
  1672. uint32 *new_argv = NULL, param_argc;
  1673. #if WASM_ENABLE_REF_TYPES != 0
  1674. uint32 result_argc = 0;
  1675. #endif
  1676. if (!wasm_runtime_exec_env_check(exec_env)) {
  1677. LOG_ERROR("Invalid exec env stack info.");
  1678. return false;
  1679. }
  1680. #if WASM_ENABLE_REF_TYPES != 0
  1681. if (!wasm_runtime_prepare_call_function(exec_env, function, argv, argc,
  1682. &new_argv, &param_argc,
  1683. &result_argc)) {
  1684. wasm_runtime_set_exception(exec_env->module_inst,
  1685. "the arguments conversion is failed");
  1686. return false;
  1687. }
  1688. #else
  1689. new_argv = argv;
  1690. param_argc = argc;
  1691. #endif
  1692. #if WASM_ENABLE_INTERP != 0
  1693. if (exec_env->module_inst->module_type == Wasm_Module_Bytecode)
  1694. ret = wasm_call_function(exec_env, (WASMFunctionInstance *)function,
  1695. param_argc, new_argv);
  1696. #endif
  1697. #if WASM_ENABLE_AOT != 0
  1698. if (exec_env->module_inst->module_type == Wasm_Module_AoT)
  1699. ret = aot_call_function(exec_env, (AOTFunctionInstance *)function,
  1700. param_argc, new_argv);
  1701. #endif
  1702. if (!ret) {
  1703. if (clear_wasi_proc_exit_exception(exec_env->module_inst)) {
  1704. ret = true;
  1705. }
  1706. else {
  1707. if (new_argv != argv) {
  1708. wasm_runtime_free(new_argv);
  1709. }
  1710. return false;
  1711. }
  1712. }
  1713. #if WASM_ENABLE_REF_TYPES != 0
  1714. if (!wasm_runtime_finalize_call_function(exec_env, function, new_argv,
  1715. result_argc, argv)) {
  1716. wasm_runtime_set_exception(exec_env->module_inst,
  1717. "the result conversion is failed");
  1718. return false;
  1719. }
  1720. #endif
  1721. return ret;
  1722. }
  1723. static void
  1724. parse_args_to_uint32_array(WASMType *type, wasm_val_t *args, uint32 *out_argv)
  1725. {
  1726. uint32 i, p;
  1727. for (i = 0, p = 0; i < type->param_count; i++) {
  1728. switch (args[i].kind) {
  1729. case WASM_I32:
  1730. out_argv[p++] = args[i].of.i32;
  1731. break;
  1732. case WASM_I64:
  1733. {
  1734. union {
  1735. uint64 val;
  1736. uint32 parts[2];
  1737. } u;
  1738. u.val = args[i].of.i64;
  1739. out_argv[p++] = u.parts[0];
  1740. out_argv[p++] = u.parts[1];
  1741. break;
  1742. }
  1743. case WASM_F32:
  1744. {
  1745. union {
  1746. float32 val;
  1747. uint32 part;
  1748. } u;
  1749. u.val = args[i].of.f32;
  1750. out_argv[p++] = u.part;
  1751. break;
  1752. }
  1753. case WASM_F64:
  1754. {
  1755. union {
  1756. float64 val;
  1757. uint32 parts[2];
  1758. } u;
  1759. u.val = args[i].of.f64;
  1760. out_argv[p++] = u.parts[0];
  1761. out_argv[p++] = u.parts[1];
  1762. break;
  1763. }
  1764. #if WASM_ENABLE_REF_TYPES != 0
  1765. case WASM_FUNCREF:
  1766. {
  1767. out_argv[p++] = args[i].of.i32;
  1768. break;
  1769. }
  1770. case WASM_ANYREF:
  1771. {
  1772. #if UINTPTR_MAX == UINT32_MAX
  1773. out_argv[p++] = args[i].of.foreign;
  1774. #else
  1775. union {
  1776. uintptr_t val;
  1777. uint32 parts[2];
  1778. } u;
  1779. u.val = (uintptr_t)args[i].of.foreign;
  1780. out_argv[p++] = u.parts[0];
  1781. out_argv[p++] = u.parts[1];
  1782. #endif
  1783. break;
  1784. }
  1785. #endif
  1786. default:
  1787. bh_assert(0);
  1788. break;
  1789. }
  1790. }
  1791. }
  1792. static void
  1793. parse_uint32_array_to_results(WASMType *type, uint32 *argv,
  1794. wasm_val_t *out_results)
  1795. {
  1796. uint32 i, p;
  1797. for (i = 0, p = 0; i < type->result_count; i++) {
  1798. switch (type->types[type->param_count + i]) {
  1799. case VALUE_TYPE_I32:
  1800. out_results[i].kind = WASM_I32;
  1801. out_results[i].of.i32 = (int32)argv[p++];
  1802. break;
  1803. case VALUE_TYPE_I64:
  1804. {
  1805. union {
  1806. uint64 val;
  1807. uint32 parts[2];
  1808. } u;
  1809. u.parts[0] = argv[p++];
  1810. u.parts[1] = argv[p++];
  1811. out_results[i].kind = WASM_I64;
  1812. out_results[i].of.i64 = u.val;
  1813. break;
  1814. }
  1815. case VALUE_TYPE_F32:
  1816. {
  1817. union {
  1818. float32 val;
  1819. uint32 part;
  1820. } u;
  1821. u.part = argv[p++];
  1822. out_results[i].kind = WASM_F32;
  1823. out_results[i].of.f32 = u.val;
  1824. break;
  1825. }
  1826. case VALUE_TYPE_F64:
  1827. {
  1828. union {
  1829. float64 val;
  1830. uint32 parts[2];
  1831. } u;
  1832. u.parts[0] = argv[p++];
  1833. u.parts[1] = argv[p++];
  1834. out_results[i].kind = WASM_F64;
  1835. out_results[i].of.f64 = u.val;
  1836. break;
  1837. }
  1838. #if WASM_ENABLE_REF_TYPES != 0
  1839. case VALUE_TYPE_FUNCREF:
  1840. {
  1841. out_results[i].kind = WASM_I32;
  1842. out_results[i].of.i32 = (int32)argv[p++];
  1843. break;
  1844. }
  1845. case VALUE_TYPE_EXTERNREF:
  1846. {
  1847. #if UINTPTR_MAX == UINT32_MAX
  1848. out_results[i].kind = WASM_ANYREF;
  1849. out_results[i].of.foreign = (uintptr_t)argv[p++];
  1850. #else
  1851. union {
  1852. uintptr_t val;
  1853. uint32 parts[2];
  1854. } u;
  1855. u.parts[0] = argv[p++];
  1856. u.parts[1] = argv[p++];
  1857. out_results[i].kind = WASM_ANYREF;
  1858. out_results[i].of.foreign = u.val;
  1859. #endif
  1860. break;
  1861. }
  1862. #endif
  1863. default:
  1864. bh_assert(0);
  1865. break;
  1866. }
  1867. }
  1868. }
  1869. bool
  1870. wasm_runtime_call_wasm_a(WASMExecEnv *exec_env,
  1871. WASMFunctionInstanceCommon *function,
  1872. uint32 num_results, wasm_val_t results[],
  1873. uint32 num_args, wasm_val_t args[])
  1874. {
  1875. uint32 argc, argv_buf[16] = { 0 }, *argv = argv_buf, cell_num, module_type;
  1876. #if WASM_ENABLE_REF_TYPES != 0
  1877. uint32 i, param_size_in_double_world = 0, result_size_in_double_world = 0;
  1878. #endif
  1879. uint64 total_size;
  1880. WASMType *type;
  1881. bool ret = false;
  1882. module_type = exec_env->module_inst->module_type;
  1883. type = wasm_runtime_get_function_type(function, module_type);
  1884. if (!type) {
  1885. LOG_ERROR("Function type get failed, WAMR Interpreter and AOT must be "
  1886. "enabled at least one.");
  1887. goto fail1;
  1888. }
  1889. #if WASM_ENABLE_REF_TYPES != 0
  1890. for (i = 0; i < type->param_count; i++) {
  1891. param_size_in_double_world +=
  1892. wasm_value_type_cell_num_outside(type->types[i]);
  1893. }
  1894. for (i = 0; i < type->result_count; i++) {
  1895. result_size_in_double_world += wasm_value_type_cell_num_outside(
  1896. type->types[type->param_count + i]);
  1897. }
  1898. argc = param_size_in_double_world;
  1899. cell_num = (argc >= result_size_in_double_world)
  1900. ? argc
  1901. : result_size_in_double_world;
  1902. #else
  1903. argc = type->param_cell_num;
  1904. cell_num = (argc > type->ret_cell_num) ? argc : type->ret_cell_num;
  1905. #endif
  1906. if (num_results != type->result_count) {
  1907. LOG_ERROR(
  1908. "The result value number does not match the function declaration.");
  1909. goto fail1;
  1910. }
  1911. if (num_args != type->param_count) {
  1912. LOG_ERROR("The argument value number does not match the function "
  1913. "declaration.");
  1914. goto fail1;
  1915. }
  1916. total_size = sizeof(uint32) * (uint64)(cell_num > 2 ? cell_num : 2);
  1917. if (total_size > sizeof(argv_buf)) {
  1918. if (!(argv =
  1919. runtime_malloc(total_size, exec_env->module_inst, NULL, 0))) {
  1920. goto fail1;
  1921. }
  1922. }
  1923. parse_args_to_uint32_array(type, args, argv);
  1924. if (!(ret = wasm_runtime_call_wasm(exec_env, function, argc, argv)))
  1925. goto fail2;
  1926. parse_uint32_array_to_results(type, argv, results);
  1927. fail2:
  1928. if (argv != argv_buf)
  1929. wasm_runtime_free(argv);
  1930. fail1:
  1931. return ret;
  1932. }
  1933. bool
  1934. wasm_runtime_call_wasm_v(WASMExecEnv *exec_env,
  1935. WASMFunctionInstanceCommon *function,
  1936. uint32 num_results, wasm_val_t results[],
  1937. uint32 num_args, ...)
  1938. {
  1939. wasm_val_t args_buf[8] = { 0 }, *args = args_buf;
  1940. WASMType *type = NULL;
  1941. bool ret = false;
  1942. uint64 total_size;
  1943. uint32 i = 0, module_type;
  1944. va_list vargs;
  1945. module_type = exec_env->module_inst->module_type;
  1946. type = wasm_runtime_get_function_type(function, module_type);
  1947. if (!type) {
  1948. LOG_ERROR("Function type get failed, WAMR Interpreter and AOT "
  1949. "must be enabled at least one.");
  1950. goto fail1;
  1951. }
  1952. if (num_args != type->param_count) {
  1953. LOG_ERROR("The argument value number does not match the "
  1954. "function declaration.");
  1955. goto fail1;
  1956. }
  1957. total_size = sizeof(wasm_val_t) * (uint64)num_args;
  1958. if (total_size > sizeof(args_buf)) {
  1959. if (!(args =
  1960. runtime_malloc(total_size, exec_env->module_inst, NULL, 0))) {
  1961. goto fail1;
  1962. }
  1963. }
  1964. va_start(vargs, num_args);
  1965. for (i = 0; i < num_args; i++) {
  1966. switch (type->types[i]) {
  1967. case VALUE_TYPE_I32:
  1968. args[i].kind = WASM_I32;
  1969. args[i].of.i32 = va_arg(vargs, uint32);
  1970. break;
  1971. case VALUE_TYPE_I64:
  1972. args[i].kind = WASM_I64;
  1973. args[i].of.i64 = va_arg(vargs, uint64);
  1974. break;
  1975. case VALUE_TYPE_F32:
  1976. args[i].kind = WASM_F32;
  1977. args[i].of.f32 = (float32)va_arg(vargs, float64);
  1978. break;
  1979. case VALUE_TYPE_F64:
  1980. args[i].kind = WASM_F64;
  1981. args[i].of.f64 = va_arg(vargs, float64);
  1982. break;
  1983. #if WASM_ENABLE_REF_TYPES != 0
  1984. case VALUE_TYPE_FUNCREF:
  1985. {
  1986. args[i].kind = WASM_FUNCREF;
  1987. args[i].of.i32 = va_arg(vargs, uint32);
  1988. break;
  1989. }
  1990. case VALUE_TYPE_EXTERNREF:
  1991. {
  1992. args[i].kind = WASM_ANYREF;
  1993. args[i].of.foreign = va_arg(vargs, uintptr_t);
  1994. break;
  1995. }
  1996. #endif
  1997. default:
  1998. bh_assert(0);
  1999. break;
  2000. }
  2001. }
  2002. va_end(vargs);
  2003. ret = wasm_runtime_call_wasm_a(exec_env, function, num_results, results,
  2004. num_args, args);
  2005. if (args != args_buf)
  2006. wasm_runtime_free(args);
  2007. fail1:
  2008. return ret;
  2009. }
  2010. bool
  2011. wasm_runtime_create_exec_env_singleton(
  2012. WASMModuleInstanceCommon *module_inst_comm)
  2013. {
  2014. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2015. WASMExecEnv *exec_env = NULL;
  2016. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2017. || module_inst_comm->module_type == Wasm_Module_AoT);
  2018. if (module_inst->exec_env_singleton) {
  2019. return true;
  2020. }
  2021. exec_env = wasm_exec_env_create(module_inst_comm,
  2022. module_inst->default_wasm_stack_size);
  2023. if (exec_env)
  2024. module_inst->exec_env_singleton = exec_env;
  2025. return exec_env ? true : false;
  2026. }
  2027. WASMExecEnv *
  2028. wasm_runtime_get_exec_env_singleton(WASMModuleInstanceCommon *module_inst_comm)
  2029. {
  2030. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2031. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2032. || module_inst_comm->module_type == Wasm_Module_AoT);
  2033. if (!module_inst->exec_env_singleton) {
  2034. wasm_runtime_create_exec_env_singleton(module_inst_comm);
  2035. }
  2036. return module_inst->exec_env_singleton;
  2037. }
  2038. void
  2039. wasm_set_exception(WASMModuleInstance *module_inst, const char *exception)
  2040. {
  2041. WASMExecEnv *exec_env = NULL;
  2042. #if WASM_ENABLE_SHARED_MEMORY != 0
  2043. WASMSharedMemNode *node =
  2044. wasm_module_get_shared_memory((WASMModuleCommon *)module_inst->module);
  2045. if (node)
  2046. os_mutex_lock(&node->shared_mem_lock);
  2047. #endif
  2048. if (exception) {
  2049. snprintf(module_inst->cur_exception, sizeof(module_inst->cur_exception),
  2050. "Exception: %s", exception);
  2051. }
  2052. else {
  2053. module_inst->cur_exception[0] = '\0';
  2054. }
  2055. #if WASM_ENABLE_SHARED_MEMORY != 0
  2056. if (node)
  2057. os_mutex_unlock(&node->shared_mem_lock);
  2058. #endif
  2059. #if WASM_ENABLE_THREAD_MGR != 0
  2060. exec_env =
  2061. wasm_clusters_search_exec_env((WASMModuleInstanceCommon *)module_inst);
  2062. if (exec_env) {
  2063. wasm_cluster_spread_exception(exec_env, exception ? false : true);
  2064. }
  2065. #else
  2066. (void)exec_env;
  2067. #endif
  2068. }
  2069. /* clang-format off */
  2070. static const char *exception_msgs[] = {
  2071. "unreachable", /* EXCE_UNREACHABLE */
  2072. "allocate memory failed", /* EXCE_OUT_OF_MEMORY */
  2073. "out of bounds memory access", /* EXCE_OUT_OF_BOUNDS_MEMORY_ACCESS */
  2074. "integer overflow", /* EXCE_INTEGER_OVERFLOW */
  2075. "integer divide by zero", /* EXCE_INTEGER_DIVIDE_BY_ZERO */
  2076. "invalid conversion to integer", /* EXCE_INVALID_CONVERSION_TO_INTEGER */
  2077. "indirect call type mismatch", /* EXCE_INVALID_FUNCTION_TYPE_INDEX */
  2078. "invalid function index", /* EXCE_INVALID_FUNCTION_INDEX */
  2079. "undefined element", /* EXCE_UNDEFINED_ELEMENT */
  2080. "uninitialized element", /* EXCE_UNINITIALIZED_ELEMENT */
  2081. "failed to call unlinked import function", /* EXCE_CALL_UNLINKED_IMPORT_FUNC */
  2082. "native stack overflow", /* EXCE_NATIVE_STACK_OVERFLOW */
  2083. "unaligned atomic", /* EXCE_UNALIGNED_ATOMIC */
  2084. "wasm auxiliary stack overflow", /* EXCE_AUX_STACK_OVERFLOW */
  2085. "wasm auxiliary stack underflow", /* EXCE_AUX_STACK_UNDERFLOW */
  2086. "out of bounds table access", /* EXCE_OUT_OF_BOUNDS_TABLE_ACCESS */
  2087. "wasm operand stack overflow", /* EXCE_OPERAND_STACK_OVERFLOW */
  2088. "failed to compile fast jit function", /* EXCE_FAILED_TO_COMPILE_FAST_JIT_FUNC */
  2089. "", /* EXCE_ALREADY_THROWN */
  2090. };
  2091. /* clang-format on */
  2092. void
  2093. wasm_set_exception_with_id(WASMModuleInstance *module_inst, uint32 id)
  2094. {
  2095. if (id < EXCE_NUM)
  2096. wasm_set_exception(module_inst, exception_msgs[id]);
  2097. else
  2098. wasm_set_exception(module_inst, "unknown exception");
  2099. }
  2100. const char *
  2101. wasm_get_exception(WASMModuleInstance *module_inst)
  2102. {
  2103. if (module_inst->cur_exception[0] == '\0')
  2104. return NULL;
  2105. else
  2106. return module_inst->cur_exception;
  2107. }
  2108. bool
  2109. wasm_copy_exception(WASMModuleInstance *module_inst, char *exception_buf)
  2110. {
  2111. bool has_exception = false;
  2112. #if WASM_ENABLE_SHARED_MEMORY != 0
  2113. WASMSharedMemNode *node =
  2114. wasm_module_get_shared_memory((WASMModuleCommon *)module_inst->module);
  2115. if (node)
  2116. os_mutex_lock(&node->shared_mem_lock);
  2117. #endif
  2118. if (module_inst->cur_exception[0] != '\0') {
  2119. /* NULL is passed if the caller is not interested in getting the
  2120. * exception content, but only in knowing if an exception has been
  2121. * raised
  2122. */
  2123. if (exception_buf != NULL)
  2124. bh_memcpy_s(exception_buf, sizeof(module_inst->cur_exception),
  2125. module_inst->cur_exception,
  2126. sizeof(module_inst->cur_exception));
  2127. has_exception = true;
  2128. }
  2129. #if WASM_ENABLE_SHARED_MEMORY != 0
  2130. if (node)
  2131. os_mutex_unlock(&node->shared_mem_lock);
  2132. #endif
  2133. return has_exception;
  2134. }
  2135. void
  2136. wasm_runtime_set_exception(WASMModuleInstanceCommon *module_inst_comm,
  2137. const char *exception)
  2138. {
  2139. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2140. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2141. || module_inst_comm->module_type == Wasm_Module_AoT);
  2142. wasm_set_exception(module_inst, exception);
  2143. }
  2144. const char *
  2145. wasm_runtime_get_exception(WASMModuleInstanceCommon *module_inst_comm)
  2146. {
  2147. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2148. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2149. || module_inst_comm->module_type == Wasm_Module_AoT);
  2150. return wasm_get_exception(module_inst);
  2151. }
  2152. bool
  2153. wasm_runtime_copy_exception(WASMModuleInstanceCommon *module_inst_comm,
  2154. char *exception_buf)
  2155. {
  2156. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2157. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2158. || module_inst_comm->module_type == Wasm_Module_AoT);
  2159. return wasm_copy_exception(module_inst, exception_buf);
  2160. }
  2161. void
  2162. wasm_runtime_clear_exception(WASMModuleInstanceCommon *module_inst_comm)
  2163. {
  2164. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2165. || module_inst_comm->module_type == Wasm_Module_AoT);
  2166. wasm_runtime_set_exception(module_inst_comm, NULL);
  2167. }
  2168. void
  2169. wasm_runtime_set_custom_data_internal(
  2170. WASMModuleInstanceCommon *module_inst_comm, void *custom_data)
  2171. {
  2172. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2173. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2174. || module_inst_comm->module_type == Wasm_Module_AoT);
  2175. module_inst->custom_data = custom_data;
  2176. }
  2177. void
  2178. wasm_runtime_set_custom_data(WASMModuleInstanceCommon *module_inst,
  2179. void *custom_data)
  2180. {
  2181. #if WASM_ENABLE_THREAD_MGR != 0
  2182. wasm_cluster_spread_custom_data(module_inst, custom_data);
  2183. #else
  2184. wasm_runtime_set_custom_data_internal(module_inst, custom_data);
  2185. #endif
  2186. }
  2187. void *
  2188. wasm_runtime_get_custom_data(WASMModuleInstanceCommon *module_inst_comm)
  2189. {
  2190. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2191. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2192. || module_inst_comm->module_type == Wasm_Module_AoT);
  2193. return module_inst->custom_data;
  2194. }
  2195. uint32
  2196. wasm_runtime_module_malloc_internal(WASMModuleInstanceCommon *module_inst,
  2197. WASMExecEnv *exec_env, uint32 size,
  2198. void **p_native_addr)
  2199. {
  2200. #if WASM_ENABLE_INTERP != 0
  2201. if (module_inst->module_type == Wasm_Module_Bytecode)
  2202. return wasm_module_malloc_internal((WASMModuleInstance *)module_inst,
  2203. exec_env, size, p_native_addr);
  2204. #endif
  2205. #if WASM_ENABLE_AOT != 0
  2206. if (module_inst->module_type == Wasm_Module_AoT)
  2207. return aot_module_malloc_internal((AOTModuleInstance *)module_inst,
  2208. exec_env, size, p_native_addr);
  2209. #endif
  2210. return 0;
  2211. }
  2212. uint32
  2213. wasm_runtime_module_realloc_internal(WASMModuleInstanceCommon *module_inst,
  2214. WASMExecEnv *exec_env, uint32 ptr,
  2215. uint32 size, void **p_native_addr)
  2216. {
  2217. #if WASM_ENABLE_INTERP != 0
  2218. if (module_inst->module_type == Wasm_Module_Bytecode)
  2219. return wasm_module_realloc_internal((WASMModuleInstance *)module_inst,
  2220. exec_env, ptr, size, p_native_addr);
  2221. #endif
  2222. #if WASM_ENABLE_AOT != 0
  2223. if (module_inst->module_type == Wasm_Module_AoT)
  2224. return aot_module_realloc_internal((AOTModuleInstance *)module_inst,
  2225. exec_env, ptr, size, p_native_addr);
  2226. #endif
  2227. return 0;
  2228. }
  2229. void
  2230. wasm_runtime_module_free_internal(WASMModuleInstanceCommon *module_inst,
  2231. WASMExecEnv *exec_env, uint32 ptr)
  2232. {
  2233. #if WASM_ENABLE_INTERP != 0
  2234. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2235. wasm_module_free_internal((WASMModuleInstance *)module_inst, exec_env,
  2236. ptr);
  2237. return;
  2238. }
  2239. #endif
  2240. #if WASM_ENABLE_AOT != 0
  2241. if (module_inst->module_type == Wasm_Module_AoT) {
  2242. aot_module_free_internal((AOTModuleInstance *)module_inst, exec_env,
  2243. ptr);
  2244. return;
  2245. }
  2246. #endif
  2247. }
  2248. uint32
  2249. wasm_runtime_module_malloc(WASMModuleInstanceCommon *module_inst, uint32 size,
  2250. void **p_native_addr)
  2251. {
  2252. #if WASM_ENABLE_INTERP != 0
  2253. if (module_inst->module_type == Wasm_Module_Bytecode)
  2254. return wasm_module_malloc((WASMModuleInstance *)module_inst, size,
  2255. p_native_addr);
  2256. #endif
  2257. #if WASM_ENABLE_AOT != 0
  2258. if (module_inst->module_type == Wasm_Module_AoT)
  2259. return aot_module_malloc((AOTModuleInstance *)module_inst, size,
  2260. p_native_addr);
  2261. #endif
  2262. return 0;
  2263. }
  2264. uint32
  2265. wasm_runtime_module_realloc(WASMModuleInstanceCommon *module_inst, uint32 ptr,
  2266. uint32 size, void **p_native_addr)
  2267. {
  2268. #if WASM_ENABLE_INTERP != 0
  2269. if (module_inst->module_type == Wasm_Module_Bytecode)
  2270. return wasm_module_realloc((WASMModuleInstance *)module_inst, ptr, size,
  2271. p_native_addr);
  2272. #endif
  2273. #if WASM_ENABLE_AOT != 0
  2274. if (module_inst->module_type == Wasm_Module_AoT)
  2275. return aot_module_realloc((AOTModuleInstance *)module_inst, ptr, size,
  2276. p_native_addr);
  2277. #endif
  2278. return 0;
  2279. }
  2280. void
  2281. wasm_runtime_module_free(WASMModuleInstanceCommon *module_inst, uint32 ptr)
  2282. {
  2283. #if WASM_ENABLE_INTERP != 0
  2284. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2285. wasm_module_free((WASMModuleInstance *)module_inst, ptr);
  2286. return;
  2287. }
  2288. #endif
  2289. #if WASM_ENABLE_AOT != 0
  2290. if (module_inst->module_type == Wasm_Module_AoT) {
  2291. aot_module_free((AOTModuleInstance *)module_inst, ptr);
  2292. return;
  2293. }
  2294. #endif
  2295. }
  2296. uint32
  2297. wasm_runtime_module_dup_data(WASMModuleInstanceCommon *module_inst,
  2298. const char *src, uint32 size)
  2299. {
  2300. #if WASM_ENABLE_INTERP != 0
  2301. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2302. return wasm_module_dup_data((WASMModuleInstance *)module_inst, src,
  2303. size);
  2304. }
  2305. #endif
  2306. #if WASM_ENABLE_AOT != 0
  2307. if (module_inst->module_type == Wasm_Module_AoT) {
  2308. return aot_module_dup_data((AOTModuleInstance *)module_inst, src, size);
  2309. }
  2310. #endif
  2311. return 0;
  2312. }
  2313. #if WASM_ENABLE_LIBC_WASI != 0
  2314. static WASIArguments *
  2315. get_wasi_args_from_module(wasm_module_t module)
  2316. {
  2317. WASIArguments *wasi_args = NULL;
  2318. #if WASM_ENABLE_INTERP != 0 || WASM_ENABLE_JIT != 0
  2319. if (module->module_type == Wasm_Module_Bytecode)
  2320. wasi_args = &((WASMModule *)module)->wasi_args;
  2321. #endif
  2322. #if WASM_ENABLE_AOT != 0
  2323. if (module->module_type == Wasm_Module_AoT)
  2324. wasi_args = &((AOTModule *)module)->wasi_args;
  2325. #endif
  2326. return wasi_args;
  2327. }
  2328. void
  2329. wasm_runtime_set_wasi_args_ex(WASMModuleCommon *module, const char *dir_list[],
  2330. uint32 dir_count, const char *map_dir_list[],
  2331. uint32 map_dir_count, const char *env_list[],
  2332. uint32 env_count, char *argv[], int argc,
  2333. int stdinfd, int stdoutfd, int stderrfd)
  2334. {
  2335. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2336. bh_assert(wasi_args);
  2337. wasi_args->dir_list = dir_list;
  2338. wasi_args->dir_count = dir_count;
  2339. wasi_args->map_dir_list = map_dir_list;
  2340. wasi_args->map_dir_count = map_dir_count;
  2341. wasi_args->env = env_list;
  2342. wasi_args->env_count = env_count;
  2343. wasi_args->argv = argv;
  2344. wasi_args->argc = (uint32)argc;
  2345. wasi_args->stdio[0] = stdinfd;
  2346. wasi_args->stdio[1] = stdoutfd;
  2347. wasi_args->stdio[2] = stderrfd;
  2348. #if WASM_ENABLE_MULTI_MODULE != 0
  2349. #if WASM_ENABLE_INTERP != 0
  2350. if (module->module_type == Wasm_Module_Bytecode) {
  2351. wasm_propagate_wasi_args((WASMModule *)module);
  2352. }
  2353. #endif
  2354. #endif
  2355. }
  2356. void
  2357. wasm_runtime_set_wasi_args(WASMModuleCommon *module, const char *dir_list[],
  2358. uint32 dir_count, const char *map_dir_list[],
  2359. uint32 map_dir_count, const char *env_list[],
  2360. uint32 env_count, char *argv[], int argc)
  2361. {
  2362. wasm_runtime_set_wasi_args_ex(module, dir_list, dir_count, map_dir_list,
  2363. map_dir_count, env_list, env_count, argv,
  2364. argc, -1, -1, -1);
  2365. }
  2366. void
  2367. wasm_runtime_set_wasi_addr_pool(wasm_module_t module, const char *addr_pool[],
  2368. uint32 addr_pool_size)
  2369. {
  2370. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2371. if (wasi_args) {
  2372. wasi_args->addr_pool = addr_pool;
  2373. wasi_args->addr_count = addr_pool_size;
  2374. }
  2375. }
  2376. void
  2377. wasm_runtime_set_wasi_ns_lookup_pool(wasm_module_t module,
  2378. const char *ns_lookup_pool[],
  2379. uint32 ns_lookup_pool_size)
  2380. {
  2381. WASIArguments *wasi_args = get_wasi_args_from_module(module);
  2382. if (wasi_args) {
  2383. wasi_args->ns_lookup_pool = ns_lookup_pool;
  2384. wasi_args->ns_lookup_count = ns_lookup_pool_size;
  2385. }
  2386. }
  2387. #if WASM_ENABLE_UVWASI == 0
  2388. static bool
  2389. copy_string_array(const char *array[], uint32 array_size, char **buf_ptr,
  2390. char ***list_ptr, uint64 *out_buf_size)
  2391. {
  2392. uint64 buf_size = 0, total_size;
  2393. uint32 buf_offset = 0, i;
  2394. char *buf = NULL, **list = NULL;
  2395. for (i = 0; i < array_size; i++)
  2396. buf_size += strlen(array[i]) + 1;
  2397. /* We add +1 to generate null-terminated array of strings */
  2398. total_size = sizeof(char *) * ((uint64)array_size + 1);
  2399. if (total_size >= UINT32_MAX
  2400. || (total_size > 0 && !(list = wasm_runtime_malloc((uint32)total_size)))
  2401. || buf_size >= UINT32_MAX
  2402. || (buf_size > 0 && !(buf = wasm_runtime_malloc((uint32)buf_size)))) {
  2403. if (buf)
  2404. wasm_runtime_free(buf);
  2405. if (list)
  2406. wasm_runtime_free(list);
  2407. return false;
  2408. }
  2409. for (i = 0; i < array_size; i++) {
  2410. list[i] = buf + buf_offset;
  2411. bh_strcpy_s(buf + buf_offset, (uint32)buf_size - buf_offset, array[i]);
  2412. buf_offset += (uint32)(strlen(array[i]) + 1);
  2413. }
  2414. list[array_size] = NULL;
  2415. *list_ptr = list;
  2416. *buf_ptr = buf;
  2417. if (out_buf_size)
  2418. *out_buf_size = buf_size;
  2419. return true;
  2420. }
  2421. bool
  2422. wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst,
  2423. const char *dir_list[], uint32 dir_count,
  2424. const char *map_dir_list[], uint32 map_dir_count,
  2425. const char *env[], uint32 env_count,
  2426. const char *addr_pool[], uint32 addr_pool_size,
  2427. const char *ns_lookup_pool[], uint32 ns_lookup_pool_size,
  2428. char *argv[], uint32 argc, int stdinfd, int stdoutfd,
  2429. int stderrfd, char *error_buf, uint32 error_buf_size)
  2430. {
  2431. WASIContext *wasi_ctx;
  2432. char *argv_buf = NULL;
  2433. char **argv_list = NULL;
  2434. char *env_buf = NULL;
  2435. char **env_list = NULL;
  2436. char *ns_lookup_buf = NULL;
  2437. char **ns_lookup_list = NULL;
  2438. uint64 argv_buf_size = 0, env_buf_size = 0;
  2439. struct fd_table *curfds = NULL;
  2440. struct fd_prestats *prestats = NULL;
  2441. struct argv_environ_values *argv_environ = NULL;
  2442. struct addr_pool *apool = NULL;
  2443. bool fd_table_inited = false, fd_prestats_inited = false;
  2444. bool argv_environ_inited = false;
  2445. bool addr_pool_inited = false;
  2446. __wasi_fd_t wasm_fd = 3;
  2447. int32 raw_fd;
  2448. char *path, resolved_path[PATH_MAX];
  2449. uint32 i;
  2450. if (!(wasi_ctx = runtime_malloc(sizeof(WASIContext), NULL, error_buf,
  2451. error_buf_size))) {
  2452. return false;
  2453. }
  2454. wasm_runtime_set_wasi_ctx(module_inst, wasi_ctx);
  2455. /* process argv[0], trip the path and suffix, only keep the program name
  2456. */
  2457. if (!copy_string_array((const char **)argv, argc, &argv_buf, &argv_list,
  2458. &argv_buf_size)) {
  2459. set_error_buf(error_buf, error_buf_size,
  2460. "Init wasi environment failed: allocate memory failed");
  2461. goto fail;
  2462. }
  2463. if (!copy_string_array(env, env_count, &env_buf, &env_list,
  2464. &env_buf_size)) {
  2465. set_error_buf(error_buf, error_buf_size,
  2466. "Init wasi environment failed: allocate memory failed");
  2467. goto fail;
  2468. }
  2469. if (!(curfds = wasm_runtime_malloc(sizeof(struct fd_table)))
  2470. || !(prestats = wasm_runtime_malloc(sizeof(struct fd_prestats)))
  2471. || !(argv_environ =
  2472. wasm_runtime_malloc(sizeof(struct argv_environ_values)))
  2473. || !(apool = wasm_runtime_malloc(sizeof(struct addr_pool)))) {
  2474. set_error_buf(error_buf, error_buf_size,
  2475. "Init wasi environment failed: allocate memory failed");
  2476. goto fail;
  2477. }
  2478. if (!fd_table_init(curfds)) {
  2479. set_error_buf(error_buf, error_buf_size,
  2480. "Init wasi environment failed: "
  2481. "init fd table failed");
  2482. goto fail;
  2483. }
  2484. fd_table_inited = true;
  2485. if (!fd_prestats_init(prestats)) {
  2486. set_error_buf(error_buf, error_buf_size,
  2487. "Init wasi environment failed: "
  2488. "init fd prestats failed");
  2489. goto fail;
  2490. }
  2491. fd_prestats_inited = true;
  2492. if (!argv_environ_init(argv_environ, argv_buf, argv_buf_size, argv_list,
  2493. argc, env_buf, env_buf_size, env_list, env_count)) {
  2494. set_error_buf(error_buf, error_buf_size,
  2495. "Init wasi environment failed: "
  2496. "init argument environment failed");
  2497. goto fail;
  2498. }
  2499. argv_environ_inited = true;
  2500. if (!addr_pool_init(apool)) {
  2501. set_error_buf(error_buf, error_buf_size,
  2502. "Init wasi environment failed: "
  2503. "init the address pool failed");
  2504. goto fail;
  2505. }
  2506. addr_pool_inited = true;
  2507. /* Prepopulate curfds with stdin, stdout, and stderr file descriptors.
  2508. *
  2509. * If -1 is given, use STDIN_FILENO (0), STDOUT_FILENO (1),
  2510. * STDERR_FILENO (2) respectively.
  2511. */
  2512. if (!fd_table_insert_existing(curfds, 0, (stdinfd != -1) ? stdinfd : 0)
  2513. || !fd_table_insert_existing(curfds, 1, (stdoutfd != -1) ? stdoutfd : 1)
  2514. || !fd_table_insert_existing(curfds, 2,
  2515. (stderrfd != -1) ? stderrfd : 2)) {
  2516. set_error_buf(error_buf, error_buf_size,
  2517. "Init wasi environment failed: init fd table failed");
  2518. goto fail;
  2519. }
  2520. wasm_fd = 3;
  2521. for (i = 0; i < dir_count; i++, wasm_fd++) {
  2522. path = realpath(dir_list[i], resolved_path);
  2523. if (!path) {
  2524. if (error_buf)
  2525. snprintf(error_buf, error_buf_size,
  2526. "error while pre-opening directory %s: %d\n",
  2527. dir_list[i], errno);
  2528. goto fail;
  2529. }
  2530. raw_fd = open(path, O_RDONLY | O_DIRECTORY, 0);
  2531. if (raw_fd == -1) {
  2532. if (error_buf)
  2533. snprintf(error_buf, error_buf_size,
  2534. "error while pre-opening directory %s: %d\n",
  2535. dir_list[i], errno);
  2536. goto fail;
  2537. }
  2538. fd_table_insert_existing(curfds, wasm_fd, raw_fd);
  2539. fd_prestats_insert(prestats, dir_list[i], wasm_fd);
  2540. }
  2541. /* addr_pool(textual) -> apool */
  2542. for (i = 0; i < addr_pool_size; i++) {
  2543. char *cp, *address, *mask;
  2544. bool ret = false;
  2545. cp = bh_strdup(addr_pool[i]);
  2546. if (!cp) {
  2547. set_error_buf(error_buf, error_buf_size,
  2548. "Init wasi environment failed: copy address failed");
  2549. goto fail;
  2550. }
  2551. address = strtok(cp, "/");
  2552. mask = strtok(NULL, "/");
  2553. ret = addr_pool_insert(apool, address, (uint8)(mask ? atoi(mask) : 0));
  2554. wasm_runtime_free(cp);
  2555. if (!ret) {
  2556. set_error_buf(error_buf, error_buf_size,
  2557. "Init wasi environment failed: store address failed");
  2558. goto fail;
  2559. }
  2560. }
  2561. if (!copy_string_array(ns_lookup_pool, ns_lookup_pool_size, &ns_lookup_buf,
  2562. &ns_lookup_list, NULL)) {
  2563. set_error_buf(error_buf, error_buf_size,
  2564. "Init wasi environment failed: allocate memory failed");
  2565. goto fail;
  2566. }
  2567. wasi_ctx->curfds = curfds;
  2568. wasi_ctx->prestats = prestats;
  2569. wasi_ctx->argv_environ = argv_environ;
  2570. wasi_ctx->addr_pool = apool;
  2571. wasi_ctx->argv_buf = argv_buf;
  2572. wasi_ctx->argv_list = argv_list;
  2573. wasi_ctx->env_buf = env_buf;
  2574. wasi_ctx->env_list = env_list;
  2575. wasi_ctx->ns_lookup_buf = ns_lookup_buf;
  2576. wasi_ctx->ns_lookup_list = ns_lookup_list;
  2577. return true;
  2578. fail:
  2579. if (argv_environ_inited)
  2580. argv_environ_destroy(argv_environ);
  2581. if (fd_prestats_inited)
  2582. fd_prestats_destroy(prestats);
  2583. if (fd_table_inited)
  2584. fd_table_destroy(curfds);
  2585. if (addr_pool_inited)
  2586. addr_pool_destroy(apool);
  2587. if (curfds)
  2588. wasm_runtime_free(curfds);
  2589. if (prestats)
  2590. wasm_runtime_free(prestats);
  2591. if (argv_environ)
  2592. wasm_runtime_free(argv_environ);
  2593. if (apool)
  2594. wasm_runtime_free(apool);
  2595. if (argv_buf)
  2596. wasm_runtime_free(argv_buf);
  2597. if (argv_list)
  2598. wasm_runtime_free(argv_list);
  2599. if (env_buf)
  2600. wasm_runtime_free(env_buf);
  2601. if (env_list)
  2602. wasm_runtime_free(env_list);
  2603. if (ns_lookup_buf)
  2604. wasm_runtime_free(ns_lookup_buf);
  2605. if (ns_lookup_list)
  2606. wasm_runtime_free(ns_lookup_list);
  2607. return false;
  2608. }
  2609. #else /* else of WASM_ENABLE_UVWASI == 0 */
  2610. static void *
  2611. wasm_uvwasi_malloc(size_t size, void *mem_user_data)
  2612. {
  2613. return runtime_malloc(size, NULL, NULL, 0);
  2614. (void)mem_user_data;
  2615. }
  2616. static void
  2617. wasm_uvwasi_free(void *ptr, void *mem_user_data)
  2618. {
  2619. if (ptr)
  2620. wasm_runtime_free(ptr);
  2621. (void)mem_user_data;
  2622. }
  2623. static void *
  2624. wasm_uvwasi_calloc(size_t nmemb, size_t size, void *mem_user_data)
  2625. {
  2626. uint64 total_size = (uint64)nmemb * size;
  2627. return runtime_malloc(total_size, NULL, NULL, 0);
  2628. (void)mem_user_data;
  2629. }
  2630. static void *
  2631. wasm_uvwasi_realloc(void *ptr, size_t size, void *mem_user_data)
  2632. {
  2633. if (size >= UINT32_MAX) {
  2634. return NULL;
  2635. }
  2636. return wasm_runtime_realloc(ptr, (uint32)size);
  2637. }
  2638. /* clang-format off */
  2639. static uvwasi_mem_t uvwasi_allocator = {
  2640. .mem_user_data = 0,
  2641. .malloc = wasm_uvwasi_malloc,
  2642. .free = wasm_uvwasi_free,
  2643. .calloc = wasm_uvwasi_calloc,
  2644. .realloc = wasm_uvwasi_realloc
  2645. };
  2646. /* clang-format on */
  2647. bool
  2648. wasm_runtime_init_wasi(WASMModuleInstanceCommon *module_inst,
  2649. const char *dir_list[], uint32 dir_count,
  2650. const char *map_dir_list[], uint32 map_dir_count,
  2651. const char *env[], uint32 env_count,
  2652. const char *addr_pool[], uint32 addr_pool_size,
  2653. const char *ns_lookup_pool[], uint32 ns_lookup_pool_size,
  2654. char *argv[], uint32 argc, int stdinfd, int stdoutfd,
  2655. int stderrfd, char *error_buf, uint32 error_buf_size)
  2656. {
  2657. WASIContext *ctx;
  2658. uvwasi_t *uvwasi;
  2659. uvwasi_options_t init_options;
  2660. const char **envp = NULL;
  2661. uint64 total_size;
  2662. uint32 i;
  2663. bool ret = false;
  2664. ctx = runtime_malloc(sizeof(*ctx), module_inst, error_buf, error_buf_size);
  2665. if (!ctx)
  2666. return false;
  2667. uvwasi = &ctx->uvwasi;
  2668. /* Setup the initialization options */
  2669. uvwasi_options_init(&init_options);
  2670. init_options.allocator = &uvwasi_allocator;
  2671. init_options.argc = argc;
  2672. init_options.argv = (const char **)argv;
  2673. init_options.in = (stdinfd != -1) ? (uvwasi_fd_t)stdinfd : init_options.in;
  2674. init_options.out =
  2675. (stdoutfd != -1) ? (uvwasi_fd_t)stdoutfd : init_options.out;
  2676. init_options.err =
  2677. (stderrfd != -1) ? (uvwasi_fd_t)stderrfd : init_options.err;
  2678. if (dir_count > 0) {
  2679. init_options.preopenc = dir_count;
  2680. total_size = sizeof(uvwasi_preopen_t) * (uint64)init_options.preopenc;
  2681. init_options.preopens = (uvwasi_preopen_t *)runtime_malloc(
  2682. total_size, module_inst, error_buf, error_buf_size);
  2683. if (init_options.preopens == NULL)
  2684. goto fail;
  2685. for (i = 0; i < init_options.preopenc; i++) {
  2686. init_options.preopens[i].real_path = dir_list[i];
  2687. init_options.preopens[i].mapped_path =
  2688. (i < map_dir_count) ? map_dir_list[i] : dir_list[i];
  2689. }
  2690. }
  2691. if (env_count > 0) {
  2692. total_size = sizeof(char *) * (uint64)(env_count + 1);
  2693. envp =
  2694. runtime_malloc(total_size, module_inst, error_buf, error_buf_size);
  2695. if (envp == NULL)
  2696. goto fail;
  2697. for (i = 0; i < env_count; i++) {
  2698. envp[i] = env[i];
  2699. }
  2700. envp[env_count] = NULL;
  2701. init_options.envp = envp;
  2702. }
  2703. if (UVWASI_ESUCCESS != uvwasi_init(uvwasi, &init_options)) {
  2704. set_error_buf(error_buf, error_buf_size, "uvwasi init failed");
  2705. goto fail;
  2706. }
  2707. wasm_runtime_set_wasi_ctx(module_inst, ctx);
  2708. ret = true;
  2709. fail:
  2710. if (envp)
  2711. wasm_runtime_free((void *)envp);
  2712. if (init_options.preopens)
  2713. wasm_runtime_free(init_options.preopens);
  2714. if (!ret && uvwasi)
  2715. wasm_runtime_free(uvwasi);
  2716. return ret;
  2717. }
  2718. #endif /* end of WASM_ENABLE_UVWASI */
  2719. bool
  2720. wasm_runtime_is_wasi_mode(WASMModuleInstanceCommon *module_inst)
  2721. {
  2722. #if WASM_ENABLE_INTERP != 0
  2723. if (module_inst->module_type == Wasm_Module_Bytecode
  2724. && ((WASMModuleInstance *)module_inst)->module->import_wasi_api)
  2725. return true;
  2726. #endif
  2727. #if WASM_ENABLE_AOT != 0
  2728. if (module_inst->module_type == Wasm_Module_AoT
  2729. && ((AOTModule *)((AOTModuleInstance *)module_inst)->module)
  2730. ->import_wasi_api)
  2731. return true;
  2732. #endif
  2733. return false;
  2734. }
  2735. WASMFunctionInstanceCommon *
  2736. wasm_runtime_lookup_wasi_start_function(WASMModuleInstanceCommon *module_inst)
  2737. {
  2738. uint32 i;
  2739. #if WASM_ENABLE_INTERP != 0
  2740. if (module_inst->module_type == Wasm_Module_Bytecode) {
  2741. WASMModuleInstance *wasm_inst = (WASMModuleInstance *)module_inst;
  2742. WASMFunctionInstance *func;
  2743. for (i = 0; i < wasm_inst->export_func_count; i++) {
  2744. if (!strcmp(wasm_inst->export_functions[i].name, "_start")) {
  2745. func = wasm_inst->export_functions[i].function;
  2746. if (func->u.func->func_type->param_count != 0
  2747. || func->u.func->func_type->result_count != 0) {
  2748. LOG_ERROR("Lookup wasi _start function failed: "
  2749. "invalid function type.\n");
  2750. return NULL;
  2751. }
  2752. return (WASMFunctionInstanceCommon *)func;
  2753. }
  2754. }
  2755. return NULL;
  2756. }
  2757. #endif
  2758. #if WASM_ENABLE_AOT != 0
  2759. if (module_inst->module_type == Wasm_Module_AoT) {
  2760. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  2761. AOTFunctionInstance *export_funcs =
  2762. (AOTFunctionInstance *)aot_inst->export_functions;
  2763. for (i = 0; i < aot_inst->export_func_count; i++) {
  2764. if (!strcmp(export_funcs[i].func_name, "_start")) {
  2765. AOTFuncType *func_type = export_funcs[i].u.func.func_type;
  2766. if (func_type->param_count != 0
  2767. || func_type->result_count != 0) {
  2768. LOG_ERROR("Lookup wasi _start function failed: "
  2769. "invalid function type.\n");
  2770. return NULL;
  2771. }
  2772. return (WASMFunctionInstanceCommon *)&export_funcs[i];
  2773. }
  2774. }
  2775. return NULL;
  2776. }
  2777. #endif /* end of WASM_ENABLE_AOT */
  2778. return NULL;
  2779. }
  2780. #if WASM_ENABLE_UVWASI == 0
  2781. void
  2782. wasm_runtime_destroy_wasi(WASMModuleInstanceCommon *module_inst)
  2783. {
  2784. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  2785. if (wasi_ctx) {
  2786. if (wasi_ctx->argv_environ) {
  2787. argv_environ_destroy(wasi_ctx->argv_environ);
  2788. wasm_runtime_free(wasi_ctx->argv_environ);
  2789. }
  2790. if (wasi_ctx->curfds) {
  2791. fd_table_destroy(wasi_ctx->curfds);
  2792. wasm_runtime_free(wasi_ctx->curfds);
  2793. }
  2794. if (wasi_ctx->prestats) {
  2795. fd_prestats_destroy(wasi_ctx->prestats);
  2796. wasm_runtime_free(wasi_ctx->prestats);
  2797. }
  2798. if (wasi_ctx->addr_pool) {
  2799. addr_pool_destroy(wasi_ctx->addr_pool);
  2800. wasm_runtime_free(wasi_ctx->addr_pool);
  2801. }
  2802. if (wasi_ctx->argv_buf)
  2803. wasm_runtime_free(wasi_ctx->argv_buf);
  2804. if (wasi_ctx->argv_list)
  2805. wasm_runtime_free(wasi_ctx->argv_list);
  2806. if (wasi_ctx->env_buf)
  2807. wasm_runtime_free(wasi_ctx->env_buf);
  2808. if (wasi_ctx->env_list)
  2809. wasm_runtime_free(wasi_ctx->env_list);
  2810. if (wasi_ctx->ns_lookup_buf)
  2811. wasm_runtime_free(wasi_ctx->ns_lookup_buf);
  2812. if (wasi_ctx->ns_lookup_list)
  2813. wasm_runtime_free(wasi_ctx->ns_lookup_list);
  2814. wasm_runtime_free(wasi_ctx);
  2815. }
  2816. }
  2817. #else
  2818. void
  2819. wasm_runtime_destroy_wasi(WASMModuleInstanceCommon *module_inst)
  2820. {
  2821. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  2822. if (wasi_ctx) {
  2823. uvwasi_destroy(&wasi_ctx->uvwasi);
  2824. wasm_runtime_free(wasi_ctx);
  2825. }
  2826. }
  2827. #endif
  2828. uint32_t
  2829. wasm_runtime_get_wasi_exit_code(WASMModuleInstanceCommon *module_inst)
  2830. {
  2831. WASIContext *wasi_ctx = wasm_runtime_get_wasi_ctx(module_inst);
  2832. #if WASM_ENABLE_THREAD_MGR != 0
  2833. WASMCluster *cluster;
  2834. WASMExecEnv *exec_env;
  2835. exec_env = wasm_runtime_get_exec_env_singleton(module_inst);
  2836. if (exec_env && (cluster = wasm_exec_env_get_cluster(exec_env))) {
  2837. /**
  2838. * The main thread may exit earlier than other threads, and
  2839. * the exit_code of wasi_ctx may be changed by other thread
  2840. * when it runs into wasi_proc_exit, here we wait until all
  2841. * other threads exit to avoid getting invalid exit_code.
  2842. */
  2843. wasm_cluster_wait_for_all_except_self(cluster, exec_env);
  2844. }
  2845. #endif
  2846. return wasi_ctx->exit_code;
  2847. }
  2848. WASIContext *
  2849. wasm_runtime_get_wasi_ctx(WASMModuleInstanceCommon *module_inst_comm)
  2850. {
  2851. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2852. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2853. || module_inst_comm->module_type == Wasm_Module_AoT);
  2854. return module_inst->wasi_ctx;
  2855. }
  2856. void
  2857. wasm_runtime_set_wasi_ctx(WASMModuleInstanceCommon *module_inst_comm,
  2858. WASIContext *wasi_ctx)
  2859. {
  2860. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2861. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2862. || module_inst_comm->module_type == Wasm_Module_AoT);
  2863. module_inst->wasi_ctx = wasi_ctx;
  2864. }
  2865. #endif /* end of WASM_ENABLE_LIBC_WASI */
  2866. WASMModuleCommon *
  2867. wasm_exec_env_get_module(WASMExecEnv *exec_env)
  2868. {
  2869. WASMModuleInstanceCommon *module_inst_comm =
  2870. wasm_runtime_get_module_inst(exec_env);
  2871. WASMModuleInstance *module_inst = (WASMModuleInstance *)module_inst_comm;
  2872. bh_assert(module_inst_comm->module_type == Wasm_Module_Bytecode
  2873. || module_inst_comm->module_type == Wasm_Module_AoT);
  2874. return (WASMModuleCommon *)module_inst->module;
  2875. }
  2876. #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0
  2877. const uint8 *
  2878. wasm_runtime_get_custom_section(WASMModuleCommon *const module_comm,
  2879. const char *name, uint32 *len)
  2880. {
  2881. #if WASM_ENABLE_INTERP != 0
  2882. if (module_comm->module_type == Wasm_Module_Bytecode)
  2883. return wasm_loader_get_custom_section((WASMModule *)module_comm, name,
  2884. len);
  2885. #endif
  2886. #if WASM_ENABLE_AOT != 0
  2887. if (module_comm->module_type == Wasm_Module_AoT)
  2888. return aot_get_custom_section((AOTModule *)module_comm, name, len);
  2889. #endif
  2890. return NULL;
  2891. }
  2892. #endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION != 0 */
  2893. static union {
  2894. int a;
  2895. char b;
  2896. } __ue = { .a = 1 };
  2897. #define is_little_endian() (__ue.b == 1)
  2898. bool
  2899. wasm_runtime_register_natives(const char *module_name,
  2900. NativeSymbol *native_symbols,
  2901. uint32 n_native_symbols)
  2902. {
  2903. return wasm_native_register_natives(module_name, native_symbols,
  2904. n_native_symbols);
  2905. }
  2906. bool
  2907. wasm_runtime_register_natives_raw(const char *module_name,
  2908. NativeSymbol *native_symbols,
  2909. uint32 n_native_symbols)
  2910. {
  2911. return wasm_native_register_natives_raw(module_name, native_symbols,
  2912. n_native_symbols);
  2913. }
  2914. bool
  2915. wasm_runtime_unregister_natives(const char *module_name,
  2916. NativeSymbol *native_symbols)
  2917. {
  2918. return wasm_native_unregister_natives(module_name, native_symbols);
  2919. }
  2920. bool
  2921. wasm_runtime_invoke_native_raw(WASMExecEnv *exec_env, void *func_ptr,
  2922. const WASMType *func_type, const char *signature,
  2923. void *attachment, uint32 *argv, uint32 argc,
  2924. uint32 *argv_ret)
  2925. {
  2926. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  2927. typedef void (*NativeRawFuncPtr)(WASMExecEnv *, uint64 *);
  2928. NativeRawFuncPtr invokeNativeRaw = (NativeRawFuncPtr)func_ptr;
  2929. uint64 argv_buf[16] = { 0 }, *argv1 = argv_buf, *argv_dst, size;
  2930. uint32 *argv_src = argv, i, argc1, ptr_len;
  2931. uint32 arg_i32;
  2932. bool ret = false;
  2933. argc1 = func_type->param_count;
  2934. if (argc1 > sizeof(argv_buf) / sizeof(uint64)) {
  2935. size = sizeof(uint64) * (uint64)argc1;
  2936. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  2937. 0))) {
  2938. return false;
  2939. }
  2940. }
  2941. argv_dst = argv1;
  2942. /* Traverse secondly to fill in each argument */
  2943. for (i = 0; i < func_type->param_count; i++, argv_dst++) {
  2944. switch (func_type->types[i]) {
  2945. case VALUE_TYPE_I32:
  2946. #if WASM_ENABLE_REF_TYPES != 0
  2947. case VALUE_TYPE_FUNCREF:
  2948. #endif
  2949. {
  2950. *(uint32 *)argv_dst = arg_i32 = *argv_src++;
  2951. if (signature) {
  2952. if (signature[i + 1] == '*') {
  2953. /* param is a pointer */
  2954. if (signature[i + 2] == '~')
  2955. /* pointer with length followed */
  2956. ptr_len = *argv_src;
  2957. else
  2958. /* pointer without length followed */
  2959. ptr_len = 1;
  2960. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  2961. ptr_len))
  2962. goto fail;
  2963. *(uintptr_t *)argv_dst =
  2964. (uintptr_t)wasm_runtime_addr_app_to_native(module,
  2965. arg_i32);
  2966. }
  2967. else if (signature[i + 1] == '$') {
  2968. /* param is a string */
  2969. if (!wasm_runtime_validate_app_str_addr(module,
  2970. arg_i32))
  2971. goto fail;
  2972. *(uintptr_t *)argv_dst =
  2973. (uintptr_t)wasm_runtime_addr_app_to_native(module,
  2974. arg_i32);
  2975. }
  2976. }
  2977. break;
  2978. }
  2979. case VALUE_TYPE_I64:
  2980. case VALUE_TYPE_F64:
  2981. bh_memcpy_s(argv_dst, sizeof(uint64), argv_src,
  2982. sizeof(uint32) * 2);
  2983. argv_src += 2;
  2984. break;
  2985. case VALUE_TYPE_F32:
  2986. *(float32 *)argv_dst = *(float32 *)argv_src++;
  2987. break;
  2988. #if WASM_ENABLE_REF_TYPES != 0
  2989. case VALUE_TYPE_EXTERNREF:
  2990. {
  2991. uint32 externref_idx = *argv_src++;
  2992. void *externref_obj;
  2993. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  2994. goto fail;
  2995. bh_memcpy_s(argv_dst, sizeof(uintptr_t), argv_src,
  2996. sizeof(uintptr_t));
  2997. break;
  2998. }
  2999. #endif
  3000. default:
  3001. bh_assert(0);
  3002. break;
  3003. }
  3004. }
  3005. exec_env->attachment = attachment;
  3006. invokeNativeRaw(exec_env, argv1);
  3007. exec_env->attachment = NULL;
  3008. if (func_type->result_count > 0) {
  3009. switch (func_type->types[func_type->param_count]) {
  3010. case VALUE_TYPE_I32:
  3011. #if WASM_ENABLE_REF_TYPES != 0
  3012. case VALUE_TYPE_FUNCREF:
  3013. #endif
  3014. argv_ret[0] = *(uint32 *)argv1;
  3015. break;
  3016. case VALUE_TYPE_F32:
  3017. *(float32 *)argv_ret = *(float32 *)argv1;
  3018. break;
  3019. case VALUE_TYPE_I64:
  3020. case VALUE_TYPE_F64:
  3021. bh_memcpy_s(argv_ret, sizeof(uint32) * 2, argv1,
  3022. sizeof(uint64));
  3023. break;
  3024. #if WASM_ENABLE_REF_TYPES != 0
  3025. case VALUE_TYPE_EXTERNREF:
  3026. {
  3027. uint32 externref_idx;
  3028. uint64 externref_obj;
  3029. bh_memcpy_s(&externref_obj, sizeof(uint64), argv1,
  3030. sizeof(uint64));
  3031. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3032. (void *)(uintptr_t)externref_obj,
  3033. &externref_idx))
  3034. goto fail;
  3035. argv_ret[0] = externref_idx;
  3036. break;
  3037. }
  3038. #endif
  3039. default:
  3040. bh_assert(0);
  3041. break;
  3042. }
  3043. }
  3044. ret = !wasm_runtime_copy_exception(module, NULL);
  3045. fail:
  3046. if (argv1 != argv_buf)
  3047. wasm_runtime_free(argv1);
  3048. return ret;
  3049. }
  3050. /**
  3051. * Implementation of wasm_runtime_invoke_native()
  3052. */
  3053. /* The invoke native implementation on ARM platform with VFP co-processor */
  3054. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP) \
  3055. || defined(BUILD_TARGET_RISCV32_ILP32D) \
  3056. || defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3057. typedef void (*GenericFunctionPointer)();
  3058. void
  3059. invokeNative(GenericFunctionPointer f, uint32 *args, uint32 n_stacks);
  3060. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3061. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3062. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3063. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3064. typedef void (*VoidFuncPtr)(GenericFunctionPointer, uint32 *, uint32);
  3065. static volatile Float64FuncPtr invokeNative_Float64 =
  3066. (Float64FuncPtr)(uintptr_t)invokeNative;
  3067. static volatile Float32FuncPtr invokeNative_Float32 =
  3068. (Float32FuncPtr)(uintptr_t)invokeNative;
  3069. static volatile Int64FuncPtr invokeNative_Int64 =
  3070. (Int64FuncPtr)(uintptr_t)invokeNative;
  3071. static volatile Int32FuncPtr invokeNative_Int32 =
  3072. (Int32FuncPtr)(uintptr_t)invokeNative;
  3073. static volatile VoidFuncPtr invokeNative_Void =
  3074. (VoidFuncPtr)(uintptr_t)invokeNative;
  3075. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3076. #define MAX_REG_INTS 4
  3077. #define MAX_REG_FLOATS 16
  3078. #else
  3079. #define MAX_REG_INTS 8
  3080. #define MAX_REG_FLOATS 8
  3081. #endif
  3082. bool
  3083. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  3084. const WASMType *func_type, const char *signature,
  3085. void *attachment, uint32 *argv, uint32 argc,
  3086. uint32 *argv_ret)
  3087. {
  3088. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3089. /* argv buf layout: int args(fix cnt) + float args(fix cnt) + stack args
  3090. */
  3091. uint32 argv_buf[32], *argv1 = argv_buf, *ints, *stacks, size;
  3092. uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0;
  3093. uint32 arg_i32, ptr_len;
  3094. uint32 result_count = func_type->result_count;
  3095. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  3096. bool ret = false;
  3097. #if WASM_ENABLE_REF_TYPES != 0
  3098. bool is_aot_func = (NULL == signature);
  3099. #endif
  3100. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3101. uint32 *fps;
  3102. int n_fps = 0;
  3103. #else
  3104. #define fps ints
  3105. #define n_fps n_ints
  3106. #endif
  3107. n_ints++; /* exec env */
  3108. /* Traverse firstly to calculate stack args count */
  3109. for (i = 0; i < func_type->param_count; i++) {
  3110. switch (func_type->types[i]) {
  3111. case VALUE_TYPE_I32:
  3112. #if WASM_ENABLE_REF_TYPES != 0
  3113. case VALUE_TYPE_FUNCREF:
  3114. case VALUE_TYPE_EXTERNREF:
  3115. #endif
  3116. if (n_ints < MAX_REG_INTS)
  3117. n_ints++;
  3118. else
  3119. n_stacks++;
  3120. break;
  3121. case VALUE_TYPE_I64:
  3122. if (n_ints < MAX_REG_INTS - 1) {
  3123. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3124. /* 64-bit data must be 8 bytes aligned in arm */
  3125. if (n_ints & 1)
  3126. n_ints++;
  3127. #endif
  3128. n_ints += 2;
  3129. }
  3130. #if defined(BUILD_TARGET_RISCV32_ILP32) \
  3131. || defined(BUILD_TARGET_RISCV32_ILP32D) || defined(BUILD_TARGET_ARC)
  3132. /* part in register, part in stack */
  3133. else if (n_ints == MAX_REG_INTS - 1) {
  3134. n_ints++;
  3135. n_stacks++;
  3136. }
  3137. #endif
  3138. else {
  3139. /* 64-bit data in stack must be 8 bytes aligned
  3140. in arm and riscv32 */
  3141. #if !defined(BUILD_TARGET_ARC)
  3142. if (n_stacks & 1)
  3143. n_stacks++;
  3144. #endif
  3145. n_stacks += 2;
  3146. }
  3147. break;
  3148. #if !defined(BUILD_TARGET_RISCV32_ILP32D)
  3149. case VALUE_TYPE_F32:
  3150. if (n_fps < MAX_REG_FLOATS)
  3151. n_fps++;
  3152. else
  3153. n_stacks++;
  3154. break;
  3155. case VALUE_TYPE_F64:
  3156. if (n_fps < MAX_REG_FLOATS - 1) {
  3157. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3158. /* 64-bit data must be 8 bytes aligned in arm */
  3159. if (n_fps & 1)
  3160. n_fps++;
  3161. #endif
  3162. n_fps += 2;
  3163. }
  3164. #if defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3165. else if (n_fps == MAX_REG_FLOATS - 1) {
  3166. n_fps++;
  3167. n_stacks++;
  3168. }
  3169. #endif
  3170. else {
  3171. /* 64-bit data in stack must be 8 bytes aligned
  3172. in arm and riscv32 */
  3173. #if !defined(BUILD_TARGET_ARC)
  3174. if (n_stacks & 1)
  3175. n_stacks++;
  3176. #endif
  3177. n_stacks += 2;
  3178. }
  3179. break;
  3180. #else /* BUILD_TARGET_RISCV32_ILP32D */
  3181. case VALUE_TYPE_F32:
  3182. case VALUE_TYPE_F64:
  3183. if (n_fps < MAX_REG_FLOATS) {
  3184. n_fps++;
  3185. }
  3186. else if (func_type->types[i] == VALUE_TYPE_F32
  3187. && n_ints < MAX_REG_INTS) {
  3188. /* use int reg firstly if available */
  3189. n_ints++;
  3190. }
  3191. else if (func_type->types[i] == VALUE_TYPE_F64
  3192. && n_ints < MAX_REG_INTS - 1) {
  3193. /* use int regs firstly if available */
  3194. if (n_ints & 1)
  3195. n_ints++;
  3196. ints += 2;
  3197. }
  3198. else {
  3199. /* 64-bit data in stack must be 8 bytes aligned in riscv32
  3200. */
  3201. if (n_stacks & 1)
  3202. n_stacks++;
  3203. n_stacks += 2;
  3204. }
  3205. break;
  3206. #endif /* BUILD_TARGET_RISCV32_ILP32D */
  3207. default:
  3208. bh_assert(0);
  3209. break;
  3210. }
  3211. }
  3212. for (i = 0; i < ext_ret_count; i++) {
  3213. if (n_ints < MAX_REG_INTS)
  3214. n_ints++;
  3215. else
  3216. n_stacks++;
  3217. }
  3218. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3219. argc1 = MAX_REG_INTS + MAX_REG_FLOATS + n_stacks;
  3220. #elif defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3221. argc1 = MAX_REG_INTS + n_stacks;
  3222. #else /* for BUILD_TARGET_RISCV32_ILP32D */
  3223. argc1 = MAX_REG_INTS + MAX_REG_FLOATS * 2 + n_stacks;
  3224. #endif
  3225. if (argc1 > sizeof(argv_buf) / sizeof(uint32)) {
  3226. size = sizeof(uint32) * (uint32)argc1;
  3227. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3228. 0))) {
  3229. return false;
  3230. }
  3231. }
  3232. ints = argv1;
  3233. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3234. fps = ints + MAX_REG_INTS;
  3235. stacks = fps + MAX_REG_FLOATS;
  3236. #elif defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3237. stacks = ints + MAX_REG_INTS;
  3238. #else /* for BUILD_TARGET_RISCV32_ILP32D */
  3239. fps = ints + MAX_REG_INTS;
  3240. stacks = fps + MAX_REG_FLOATS * 2;
  3241. #endif
  3242. n_ints = 0;
  3243. n_fps = 0;
  3244. n_stacks = 0;
  3245. ints[n_ints++] = (uint32)(uintptr_t)exec_env;
  3246. /* Traverse secondly to fill in each argument */
  3247. for (i = 0; i < func_type->param_count; i++) {
  3248. switch (func_type->types[i]) {
  3249. case VALUE_TYPE_I32:
  3250. #if WASM_ENABLE_REF_TYPES != 0
  3251. case VALUE_TYPE_FUNCREF:
  3252. #endif
  3253. {
  3254. arg_i32 = *argv_src++;
  3255. if (signature) {
  3256. if (signature[i + 1] == '*') {
  3257. /* param is a pointer */
  3258. if (signature[i + 2] == '~')
  3259. /* pointer with length followed */
  3260. ptr_len = *argv_src;
  3261. else
  3262. /* pointer without length followed */
  3263. ptr_len = 1;
  3264. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3265. ptr_len))
  3266. goto fail;
  3267. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3268. module, arg_i32);
  3269. }
  3270. else if (signature[i + 1] == '$') {
  3271. /* param is a string */
  3272. if (!wasm_runtime_validate_app_str_addr(module,
  3273. arg_i32))
  3274. goto fail;
  3275. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3276. module, arg_i32);
  3277. }
  3278. }
  3279. if (n_ints < MAX_REG_INTS)
  3280. ints[n_ints++] = arg_i32;
  3281. else
  3282. stacks[n_stacks++] = arg_i32;
  3283. break;
  3284. }
  3285. case VALUE_TYPE_I64:
  3286. {
  3287. if (n_ints < MAX_REG_INTS - 1) {
  3288. #if defined(BUILD_TARGET_ARM_VFP) || defined(BUILD_TARGET_THUMB_VFP)
  3289. /* 64-bit data must be 8 bytes aligned in arm */
  3290. if (n_ints & 1)
  3291. n_ints++;
  3292. #endif
  3293. ints[n_ints++] = *argv_src++;
  3294. ints[n_ints++] = *argv_src++;
  3295. }
  3296. #if defined(BUILD_TARGET_RISCV32_ILP32) \
  3297. || defined(BUILD_TARGET_RISCV32_ILP32D) || defined(BUILD_TARGET_ARC)
  3298. else if (n_ints == MAX_REG_INTS - 1) {
  3299. ints[n_ints++] = *argv_src++;
  3300. stacks[n_stacks++] = *argv_src++;
  3301. }
  3302. #endif
  3303. else {
  3304. /* 64-bit data in stack must be 8 bytes aligned
  3305. in arm and riscv32 */
  3306. #if !defined(BUILD_TARGET_ARC)
  3307. if (n_stacks & 1)
  3308. n_stacks++;
  3309. #endif
  3310. stacks[n_stacks++] = *argv_src++;
  3311. stacks[n_stacks++] = *argv_src++;
  3312. }
  3313. break;
  3314. }
  3315. #if !defined(BUILD_TARGET_RISCV32_ILP32D)
  3316. case VALUE_TYPE_F32:
  3317. {
  3318. if (n_fps < MAX_REG_FLOATS)
  3319. *(float32 *)&fps[n_fps++] = *(float32 *)argv_src++;
  3320. else
  3321. *(float32 *)&stacks[n_stacks++] = *(float32 *)argv_src++;
  3322. break;
  3323. }
  3324. case VALUE_TYPE_F64:
  3325. {
  3326. if (n_fps < MAX_REG_FLOATS - 1) {
  3327. #if !defined(BUILD_TARGET_RISCV32_ILP32) && !defined(BUILD_TARGET_ARC)
  3328. /* 64-bit data must be 8 bytes aligned in arm */
  3329. if (n_fps & 1)
  3330. n_fps++;
  3331. #endif
  3332. fps[n_fps++] = *argv_src++;
  3333. fps[n_fps++] = *argv_src++;
  3334. }
  3335. #if defined(BUILD_TARGET_RISCV32_ILP32) || defined(BUILD_TARGET_ARC)
  3336. else if (n_fps == MAX_REG_FLOATS - 1) {
  3337. fps[n_fps++] = *argv_src++;
  3338. stacks[n_stacks++] = *argv_src++;
  3339. }
  3340. #endif
  3341. else {
  3342. /* 64-bit data in stack must be 8 bytes aligned
  3343. in arm and riscv32 */
  3344. #if !defined(BUILD_TARGET_ARC)
  3345. if (n_stacks & 1)
  3346. n_stacks++;
  3347. #endif
  3348. stacks[n_stacks++] = *argv_src++;
  3349. stacks[n_stacks++] = *argv_src++;
  3350. }
  3351. break;
  3352. }
  3353. #else /* BUILD_TARGET_RISCV32_ILP32D */
  3354. case VALUE_TYPE_F32:
  3355. case VALUE_TYPE_F64:
  3356. {
  3357. if (n_fps < MAX_REG_FLOATS) {
  3358. if (func_type->types[i] == VALUE_TYPE_F32) {
  3359. *(float32 *)&fps[n_fps * 2] = *(float32 *)argv_src++;
  3360. /* NaN boxing, the upper bits of a valid NaN-boxed
  3361. value must be all 1s. */
  3362. fps[n_fps * 2 + 1] = 0xFFFFFFFF;
  3363. }
  3364. else {
  3365. *(float64 *)&fps[n_fps * 2] = *(float64 *)argv_src;
  3366. argv_src += 2;
  3367. }
  3368. n_fps++;
  3369. }
  3370. else if (func_type->types[i] == VALUE_TYPE_F32
  3371. && n_ints < MAX_REG_INTS) {
  3372. /* use int reg firstly if available */
  3373. *(float32 *)&ints[n_ints++] = *(float32 *)argv_src++;
  3374. }
  3375. else if (func_type->types[i] == VALUE_TYPE_F64
  3376. && n_ints < MAX_REG_INTS - 1) {
  3377. /* use int regs firstly if available */
  3378. if (n_ints & 1)
  3379. n_ints++;
  3380. *(float64 *)&ints[n_ints] = *(float64 *)argv_src;
  3381. n_ints += 2;
  3382. argv_src += 2;
  3383. }
  3384. else {
  3385. /* 64-bit data in stack must be 8 bytes aligned in riscv32
  3386. */
  3387. if (n_stacks & 1)
  3388. n_stacks++;
  3389. if (func_type->types[i] == VALUE_TYPE_F32) {
  3390. *(float32 *)&stacks[n_stacks] = *(float32 *)argv_src++;
  3391. /* NaN boxing, the upper bits of a valid NaN-boxed
  3392. value must be all 1s. */
  3393. stacks[n_stacks + 1] = 0xFFFFFFFF;
  3394. }
  3395. else {
  3396. *(float64 *)&stacks[n_stacks] = *(float64 *)argv_src;
  3397. argv_src += 2;
  3398. }
  3399. n_stacks += 2;
  3400. }
  3401. break;
  3402. }
  3403. #endif /* BUILD_TARGET_RISCV32_ILP32D */
  3404. #if WASM_ENABLE_REF_TYPES != 0
  3405. case VALUE_TYPE_EXTERNREF:
  3406. {
  3407. uint32 externref_idx = *argv_src++;
  3408. if (is_aot_func) {
  3409. if (n_ints < MAX_REG_INTS)
  3410. ints[n_ints++] = externref_idx;
  3411. else
  3412. stacks[n_stacks++] = externref_idx;
  3413. }
  3414. else {
  3415. void *externref_obj;
  3416. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3417. goto fail;
  3418. if (n_ints < MAX_REG_INTS)
  3419. ints[n_ints++] = (uintptr_t)externref_obj;
  3420. else
  3421. stacks[n_stacks++] = (uintptr_t)externref_obj;
  3422. }
  3423. break;
  3424. }
  3425. #endif
  3426. default:
  3427. bh_assert(0);
  3428. break;
  3429. }
  3430. }
  3431. /* Save extra result values' address to argv1 */
  3432. for (i = 0; i < ext_ret_count; i++) {
  3433. if (n_ints < MAX_REG_INTS)
  3434. ints[n_ints++] = *(uint32 *)argv_src++;
  3435. else
  3436. stacks[n_stacks++] = *(uint32 *)argv_src++;
  3437. }
  3438. exec_env->attachment = attachment;
  3439. if (func_type->result_count == 0) {
  3440. invokeNative_Void(func_ptr, argv1, n_stacks);
  3441. }
  3442. else {
  3443. switch (func_type->types[func_type->param_count]) {
  3444. case VALUE_TYPE_I32:
  3445. #if WASM_ENABLE_REF_TYPES != 0
  3446. case VALUE_TYPE_FUNCREF:
  3447. #endif
  3448. argv_ret[0] =
  3449. (uint32)invokeNative_Int32(func_ptr, argv1, n_stacks);
  3450. break;
  3451. case VALUE_TYPE_I64:
  3452. PUT_I64_TO_ADDR(argv_ret,
  3453. invokeNative_Int64(func_ptr, argv1, n_stacks));
  3454. break;
  3455. case VALUE_TYPE_F32:
  3456. *(float32 *)argv_ret =
  3457. invokeNative_Float32(func_ptr, argv1, n_stacks);
  3458. break;
  3459. case VALUE_TYPE_F64:
  3460. PUT_F64_TO_ADDR(
  3461. argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks));
  3462. break;
  3463. #if WASM_ENABLE_REF_TYPES != 0
  3464. case VALUE_TYPE_EXTERNREF:
  3465. {
  3466. if (is_aot_func) {
  3467. uint32 externref_idx =
  3468. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  3469. argv_ret[0] = externref_idx;
  3470. }
  3471. else {
  3472. uint32 externref_idx;
  3473. void *externref_obj;
  3474. externref_obj = (void *)(uintptr_t)invokeNative_Int32(
  3475. func_ptr, argv1, argc1);
  3476. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3477. externref_obj, &externref_idx))
  3478. goto fail;
  3479. argv_ret[0] = externref_idx;
  3480. }
  3481. break;
  3482. }
  3483. #endif
  3484. default:
  3485. bh_assert(0);
  3486. break;
  3487. }
  3488. }
  3489. exec_env->attachment = NULL;
  3490. ret = !wasm_runtime_copy_exception(module, NULL);
  3491. fail:
  3492. if (argv1 != argv_buf)
  3493. wasm_runtime_free(argv1);
  3494. return ret;
  3495. }
  3496. #endif /* end of defined(BUILD_TARGET_ARM_VFP) \
  3497. || defined(BUILD_TARGET_THUMB_VFP) \
  3498. || defined(BUILD_TARGET_RISCV32_ILP32D) \
  3499. || defined(BUILD_TARGET_RISCV32_ILP32) \
  3500. || defined(BUILD_TARGET_ARC) */
  3501. #if defined(BUILD_TARGET_X86_32) || defined(BUILD_TARGET_ARM) \
  3502. || defined(BUILD_TARGET_THUMB) || defined(BUILD_TARGET_MIPS) \
  3503. || defined(BUILD_TARGET_XTENSA)
  3504. typedef void (*GenericFunctionPointer)();
  3505. void
  3506. invokeNative(GenericFunctionPointer f, uint32 *args, uint32 sz);
  3507. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3508. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3509. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3510. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3511. typedef void (*VoidFuncPtr)(GenericFunctionPointer f, uint32 *, uint32);
  3512. static volatile Int64FuncPtr invokeNative_Int64 =
  3513. (Int64FuncPtr)(uintptr_t)invokeNative;
  3514. static volatile Int32FuncPtr invokeNative_Int32 =
  3515. (Int32FuncPtr)(uintptr_t)invokeNative;
  3516. static volatile Float64FuncPtr invokeNative_Float64 =
  3517. (Float64FuncPtr)(uintptr_t)invokeNative;
  3518. static volatile Float32FuncPtr invokeNative_Float32 =
  3519. (Float32FuncPtr)(uintptr_t)invokeNative;
  3520. static volatile VoidFuncPtr invokeNative_Void =
  3521. (VoidFuncPtr)(uintptr_t)invokeNative;
  3522. static inline void
  3523. word_copy(uint32 *dest, uint32 *src, unsigned num)
  3524. {
  3525. for (; num > 0; num--)
  3526. *dest++ = *src++;
  3527. }
  3528. bool
  3529. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  3530. const WASMType *func_type, const char *signature,
  3531. void *attachment, uint32 *argv, uint32 argc,
  3532. uint32 *argv_ret)
  3533. {
  3534. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3535. uint32 argv_buf[32], *argv1 = argv_buf, argc1, i, j = 0;
  3536. uint32 arg_i32, ptr_len;
  3537. uint32 result_count = func_type->result_count;
  3538. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  3539. uint64 size;
  3540. bool ret = false;
  3541. #if WASM_ENABLE_REF_TYPES != 0
  3542. bool is_aot_func = (NULL == signature);
  3543. #endif
  3544. #if defined(BUILD_TARGET_X86_32)
  3545. argc1 = argc + ext_ret_count + 2;
  3546. #else
  3547. /* arm/thumb/mips/xtensa, 64-bit data must be 8 bytes aligned,
  3548. so we need to allocate more memory. */
  3549. argc1 = func_type->param_count * 2 + ext_ret_count + 2;
  3550. #endif
  3551. if (argc1 > sizeof(argv_buf) / sizeof(uint32)) {
  3552. size = sizeof(uint32) * (uint64)argc1;
  3553. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3554. 0))) {
  3555. return false;
  3556. }
  3557. }
  3558. for (i = 0; i < sizeof(WASMExecEnv *) / sizeof(uint32); i++)
  3559. argv1[j++] = ((uint32 *)&exec_env)[i];
  3560. for (i = 0; i < func_type->param_count; i++) {
  3561. switch (func_type->types[i]) {
  3562. case VALUE_TYPE_I32:
  3563. #if WASM_ENABLE_REF_TYPES != 0
  3564. case VALUE_TYPE_FUNCREF:
  3565. #endif
  3566. {
  3567. arg_i32 = *argv++;
  3568. if (signature) {
  3569. if (signature[i + 1] == '*') {
  3570. /* param is a pointer */
  3571. if (signature[i + 2] == '~')
  3572. /* pointer with length followed */
  3573. ptr_len = *argv;
  3574. else
  3575. /* pointer without length followed */
  3576. ptr_len = 1;
  3577. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3578. ptr_len))
  3579. goto fail;
  3580. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3581. module, arg_i32);
  3582. }
  3583. else if (signature[i + 1] == '$') {
  3584. /* param is a string */
  3585. if (!wasm_runtime_validate_app_str_addr(module,
  3586. arg_i32))
  3587. goto fail;
  3588. arg_i32 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3589. module, arg_i32);
  3590. }
  3591. }
  3592. argv1[j++] = arg_i32;
  3593. break;
  3594. }
  3595. case VALUE_TYPE_I64:
  3596. case VALUE_TYPE_F64:
  3597. #if !defined(BUILD_TARGET_X86_32)
  3598. /* 64-bit data must be 8 bytes aligned in arm, thumb, mips
  3599. and xtensa */
  3600. if (j & 1)
  3601. j++;
  3602. #endif
  3603. argv1[j++] = *argv++;
  3604. argv1[j++] = *argv++;
  3605. break;
  3606. case VALUE_TYPE_F32:
  3607. argv1[j++] = *argv++;
  3608. break;
  3609. #if WASM_ENABLE_REF_TYPES != 0
  3610. case VALUE_TYPE_EXTERNREF:
  3611. {
  3612. uint32 externref_idx = *argv++;
  3613. if (is_aot_func) {
  3614. argv1[j++] = externref_idx;
  3615. }
  3616. else {
  3617. void *externref_obj;
  3618. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3619. goto fail;
  3620. argv1[j++] = (uintptr_t)externref_obj;
  3621. }
  3622. break;
  3623. }
  3624. #endif
  3625. default:
  3626. bh_assert(0);
  3627. break;
  3628. }
  3629. }
  3630. /* Save extra result values' address to argv1 */
  3631. word_copy(argv1 + j, argv, ext_ret_count);
  3632. argc1 = j + ext_ret_count;
  3633. exec_env->attachment = attachment;
  3634. if (func_type->result_count == 0) {
  3635. invokeNative_Void(func_ptr, argv1, argc1);
  3636. }
  3637. else {
  3638. switch (func_type->types[func_type->param_count]) {
  3639. case VALUE_TYPE_I32:
  3640. #if WASM_ENABLE_REF_TYPES != 0
  3641. case VALUE_TYPE_FUNCREF:
  3642. #endif
  3643. argv_ret[0] =
  3644. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  3645. break;
  3646. case VALUE_TYPE_I64:
  3647. PUT_I64_TO_ADDR(argv_ret,
  3648. invokeNative_Int64(func_ptr, argv1, argc1));
  3649. break;
  3650. case VALUE_TYPE_F32:
  3651. *(float32 *)argv_ret =
  3652. invokeNative_Float32(func_ptr, argv1, argc1);
  3653. break;
  3654. case VALUE_TYPE_F64:
  3655. PUT_F64_TO_ADDR(argv_ret,
  3656. invokeNative_Float64(func_ptr, argv1, argc1));
  3657. break;
  3658. #if WASM_ENABLE_REF_TYPES != 0
  3659. case VALUE_TYPE_EXTERNREF:
  3660. {
  3661. if (is_aot_func) {
  3662. uint32 externref_idx =
  3663. (uint32)invokeNative_Int32(func_ptr, argv1, argc1);
  3664. argv_ret[0] = externref_idx;
  3665. }
  3666. else {
  3667. void *externref_obj = (void *)(uintptr_t)invokeNative_Int32(
  3668. func_ptr, argv1, argc1);
  3669. uint32 externref_idx;
  3670. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3671. externref_obj, &externref_idx))
  3672. goto fail;
  3673. argv_ret[0] = externref_idx;
  3674. }
  3675. break;
  3676. }
  3677. #endif
  3678. default:
  3679. bh_assert(0);
  3680. break;
  3681. }
  3682. }
  3683. exec_env->attachment = NULL;
  3684. ret = !wasm_runtime_copy_exception(module, NULL);
  3685. fail:
  3686. if (argv1 != argv_buf)
  3687. wasm_runtime_free(argv1);
  3688. return ret;
  3689. }
  3690. #endif /* end of defined(BUILD_TARGET_X86_32) \
  3691. || defined(BUILD_TARGET_ARM) \
  3692. || defined(BUILD_TARGET_THUMB) \
  3693. || defined(BUILD_TARGET_MIPS) \
  3694. || defined(BUILD_TARGET_XTENSA) */
  3695. #if defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \
  3696. || defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \
  3697. || defined(BUILD_TARGET_RISCV64_LP64)
  3698. #if WASM_ENABLE_SIMD != 0
  3699. #ifdef v128
  3700. #undef v128
  3701. #endif
  3702. #if defined(_WIN32) || defined(_WIN32_)
  3703. typedef union __declspec(intrin_type) __declspec(align(8)) v128 {
  3704. __int8 m128i_i8[16];
  3705. __int16 m128i_i16[8];
  3706. __int32 m128i_i32[4];
  3707. __int64 m128i_i64[2];
  3708. unsigned __int8 m128i_u8[16];
  3709. unsigned __int16 m128i_u16[8];
  3710. unsigned __int32 m128i_u32[4];
  3711. unsigned __int64 m128i_u64[2];
  3712. } v128;
  3713. #elif defined(BUILD_TARGET_X86_64) || defined(BUILD_TARGET_AMD_64) \
  3714. || defined(BUILD_TARGET_RISCV64_LP64D) \
  3715. || defined(BUILD_TARGET_RISCV64_LP64)
  3716. typedef long long v128
  3717. __attribute__((__vector_size__(16), __may_alias__, __aligned__(1)));
  3718. #elif defined(BUILD_TARGET_AARCH64)
  3719. #include <arm_neon.h>
  3720. typedef uint32x4_t __m128i;
  3721. #define v128 __m128i
  3722. #endif
  3723. #endif /* end of WASM_ENABLE_SIMD != 0 */
  3724. typedef void (*GenericFunctionPointer)();
  3725. void
  3726. invokeNative(GenericFunctionPointer f, uint64 *args, uint64 n_stacks);
  3727. typedef float64 (*Float64FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3728. typedef float32 (*Float32FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3729. typedef int64 (*Int64FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3730. typedef int32 (*Int32FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3731. typedef void (*VoidFuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3732. static volatile Float64FuncPtr invokeNative_Float64 =
  3733. (Float64FuncPtr)(uintptr_t)invokeNative;
  3734. static volatile Float32FuncPtr invokeNative_Float32 =
  3735. (Float32FuncPtr)(uintptr_t)invokeNative;
  3736. static volatile Int64FuncPtr invokeNative_Int64 =
  3737. (Int64FuncPtr)(uintptr_t)invokeNative;
  3738. static volatile Int32FuncPtr invokeNative_Int32 =
  3739. (Int32FuncPtr)(uintptr_t)invokeNative;
  3740. static volatile VoidFuncPtr invokeNative_Void =
  3741. (VoidFuncPtr)(uintptr_t)invokeNative;
  3742. #if WASM_ENABLE_SIMD != 0
  3743. typedef v128 (*V128FuncPtr)(GenericFunctionPointer, uint64 *, uint64);
  3744. static V128FuncPtr invokeNative_V128 = (V128FuncPtr)(uintptr_t)invokeNative;
  3745. #endif
  3746. #if defined(_WIN32) || defined(_WIN32_)
  3747. #define MAX_REG_FLOATS 4
  3748. #define MAX_REG_INTS 4
  3749. #else /* else of defined(_WIN32) || defined(_WIN32_) */
  3750. #define MAX_REG_FLOATS 8
  3751. #if defined(BUILD_TARGET_AARCH64) || defined(BUILD_TARGET_RISCV64_LP64D) \
  3752. || defined(BUILD_TARGET_RISCV64_LP64)
  3753. #define MAX_REG_INTS 8
  3754. #else
  3755. #define MAX_REG_INTS 6
  3756. #endif /* end of defined(BUILD_TARGET_AARCH64) \
  3757. || defined(BUILD_TARGET_RISCV64_LP64D) \
  3758. || defined(BUILD_TARGET_RISCV64_LP64) */
  3759. #endif /* end of defined(_WIN32) || defined(_WIN32_) */
  3760. /* ASAN is not designed to work with custom stack unwind or other low-level \
  3761. things. > Ignore a function that does some low-level magic. (e.g. walking \
  3762. through the thread's stack bypassing the frame boundaries) */
  3763. #if defined(__GNUC__)
  3764. __attribute__((no_sanitize_address))
  3765. #endif
  3766. bool
  3767. wasm_runtime_invoke_native(WASMExecEnv *exec_env, void *func_ptr,
  3768. const WASMType *func_type, const char *signature,
  3769. void *attachment, uint32 *argv, uint32 argc,
  3770. uint32 *argv_ret)
  3771. {
  3772. WASMModuleInstanceCommon *module = wasm_runtime_get_module_inst(exec_env);
  3773. uint64 argv_buf[32] = { 0 }, *argv1 = argv_buf, *ints, *stacks, size,
  3774. arg_i64;
  3775. uint32 *argv_src = argv, i, argc1, n_ints = 0, n_stacks = 0;
  3776. uint32 arg_i32, ptr_len;
  3777. uint32 result_count = func_type->result_count;
  3778. uint32 ext_ret_count = result_count > 1 ? result_count - 1 : 0;
  3779. bool ret = false;
  3780. #if WASM_ENABLE_REF_TYPES != 0
  3781. bool is_aot_func = (NULL == signature);
  3782. #endif
  3783. #ifndef BUILD_TARGET_RISCV64_LP64
  3784. #if WASM_ENABLE_SIMD == 0
  3785. uint64 *fps;
  3786. #else
  3787. v128 *fps;
  3788. #endif
  3789. #else /* else of BUILD_TARGET_RISCV64_LP64 */
  3790. #define fps ints
  3791. #endif /* end of BUILD_TARGET_RISCV64_LP64 */
  3792. #if defined(_WIN32) || defined(_WIN32_) || defined(BUILD_TARGET_RISCV64_LP64)
  3793. /* important difference in calling conventions */
  3794. #define n_fps n_ints
  3795. #else
  3796. int n_fps = 0;
  3797. #endif
  3798. #if WASM_ENABLE_SIMD == 0
  3799. argc1 = 1 + MAX_REG_FLOATS + (uint32)func_type->param_count + ext_ret_count;
  3800. #else
  3801. argc1 = 1 + MAX_REG_FLOATS * 2 + (uint32)func_type->param_count * 2
  3802. + ext_ret_count;
  3803. #endif
  3804. if (argc1 > sizeof(argv_buf) / sizeof(uint64)) {
  3805. size = sizeof(uint64) * (uint64)argc1;
  3806. if (!(argv1 = runtime_malloc((uint32)size, exec_env->module_inst, NULL,
  3807. 0))) {
  3808. return false;
  3809. }
  3810. }
  3811. #ifndef BUILD_TARGET_RISCV64_LP64
  3812. #if WASM_ENABLE_SIMD == 0
  3813. fps = argv1;
  3814. ints = fps + MAX_REG_FLOATS;
  3815. #else
  3816. fps = (v128 *)argv1;
  3817. ints = (uint64 *)(fps + MAX_REG_FLOATS);
  3818. #endif
  3819. #else /* else of BUILD_TARGET_RISCV64_LP64 */
  3820. ints = argv1;
  3821. #endif /* end of BUILD_TARGET_RISCV64_LP64 */
  3822. stacks = ints + MAX_REG_INTS;
  3823. ints[n_ints++] = (uint64)(uintptr_t)exec_env;
  3824. for (i = 0; i < func_type->param_count; i++) {
  3825. switch (func_type->types[i]) {
  3826. case VALUE_TYPE_I32:
  3827. #if WASM_ENABLE_REF_TYPES != 0
  3828. case VALUE_TYPE_FUNCREF:
  3829. #endif
  3830. {
  3831. arg_i32 = *argv_src++;
  3832. arg_i64 = arg_i32;
  3833. if (signature) {
  3834. if (signature[i + 1] == '*') {
  3835. /* param is a pointer */
  3836. if (signature[i + 2] == '~')
  3837. /* pointer with length followed */
  3838. ptr_len = *argv_src;
  3839. else
  3840. /* pointer without length followed */
  3841. ptr_len = 1;
  3842. if (!wasm_runtime_validate_app_addr(module, arg_i32,
  3843. ptr_len))
  3844. goto fail;
  3845. arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3846. module, arg_i32);
  3847. }
  3848. else if (signature[i + 1] == '$') {
  3849. /* param is a string */
  3850. if (!wasm_runtime_validate_app_str_addr(module,
  3851. arg_i32))
  3852. goto fail;
  3853. arg_i64 = (uintptr_t)wasm_runtime_addr_app_to_native(
  3854. module, arg_i32);
  3855. }
  3856. }
  3857. if (n_ints < MAX_REG_INTS)
  3858. ints[n_ints++] = arg_i64;
  3859. else
  3860. stacks[n_stacks++] = arg_i64;
  3861. break;
  3862. }
  3863. case VALUE_TYPE_I64:
  3864. if (n_ints < MAX_REG_INTS)
  3865. ints[n_ints++] = *(uint64 *)argv_src;
  3866. else
  3867. stacks[n_stacks++] = *(uint64 *)argv_src;
  3868. argv_src += 2;
  3869. break;
  3870. case VALUE_TYPE_F32:
  3871. if (n_fps < MAX_REG_FLOATS) {
  3872. *(float32 *)&fps[n_fps++] = *(float32 *)argv_src++;
  3873. }
  3874. else {
  3875. *(float32 *)&stacks[n_stacks++] = *(float32 *)argv_src++;
  3876. }
  3877. break;
  3878. case VALUE_TYPE_F64:
  3879. if (n_fps < MAX_REG_FLOATS) {
  3880. *(float64 *)&fps[n_fps++] = *(float64 *)argv_src;
  3881. }
  3882. else {
  3883. *(float64 *)&stacks[n_stacks++] = *(float64 *)argv_src;
  3884. }
  3885. argv_src += 2;
  3886. break;
  3887. #if WASM_ENABLE_REF_TYPES != 0
  3888. case VALUE_TYPE_EXTERNREF:
  3889. {
  3890. uint32 externref_idx = *argv_src++;
  3891. if (is_aot_func) {
  3892. if (n_ints < MAX_REG_INTS)
  3893. ints[n_ints++] = externref_idx;
  3894. else
  3895. stacks[n_stacks++] = externref_idx;
  3896. }
  3897. else {
  3898. void *externref_obj;
  3899. if (!wasm_externref_ref2obj(externref_idx, &externref_obj))
  3900. goto fail;
  3901. if (n_ints < MAX_REG_INTS)
  3902. ints[n_ints++] = (uintptr_t)externref_obj;
  3903. else
  3904. stacks[n_stacks++] = (uintptr_t)externref_obj;
  3905. }
  3906. break;
  3907. }
  3908. #endif
  3909. #if WASM_ENABLE_SIMD != 0
  3910. case VALUE_TYPE_V128:
  3911. if (n_fps < MAX_REG_FLOATS) {
  3912. *(v128 *)&fps[n_fps++] = *(v128 *)argv_src;
  3913. }
  3914. else {
  3915. *(v128 *)&stacks[n_stacks++] = *(v128 *)argv_src;
  3916. n_stacks++;
  3917. }
  3918. argv_src += 4;
  3919. break;
  3920. #endif
  3921. default:
  3922. bh_assert(0);
  3923. break;
  3924. }
  3925. }
  3926. /* Save extra result values' address to argv1 */
  3927. for (i = 0; i < ext_ret_count; i++) {
  3928. if (n_ints < MAX_REG_INTS)
  3929. ints[n_ints++] = *(uint64 *)argv_src;
  3930. else
  3931. stacks[n_stacks++] = *(uint64 *)argv_src;
  3932. argv_src += 2;
  3933. }
  3934. exec_env->attachment = attachment;
  3935. if (result_count == 0) {
  3936. invokeNative_Void(func_ptr, argv1, n_stacks);
  3937. }
  3938. else {
  3939. /* Invoke the native function and get the first result value */
  3940. switch (func_type->types[func_type->param_count]) {
  3941. case VALUE_TYPE_I32:
  3942. #if WASM_ENABLE_REF_TYPES != 0
  3943. case VALUE_TYPE_FUNCREF:
  3944. #endif
  3945. argv_ret[0] =
  3946. (uint32)invokeNative_Int32(func_ptr, argv1, n_stacks);
  3947. break;
  3948. case VALUE_TYPE_I64:
  3949. PUT_I64_TO_ADDR(argv_ret,
  3950. invokeNative_Int64(func_ptr, argv1, n_stacks));
  3951. break;
  3952. case VALUE_TYPE_F32:
  3953. *(float32 *)argv_ret =
  3954. invokeNative_Float32(func_ptr, argv1, n_stacks);
  3955. break;
  3956. case VALUE_TYPE_F64:
  3957. PUT_F64_TO_ADDR(
  3958. argv_ret, invokeNative_Float64(func_ptr, argv1, n_stacks));
  3959. break;
  3960. #if WASM_ENABLE_REF_TYPES != 0
  3961. case VALUE_TYPE_EXTERNREF:
  3962. {
  3963. if (is_aot_func) {
  3964. argv_ret[0] = invokeNative_Int32(func_ptr, argv1, n_stacks);
  3965. }
  3966. else {
  3967. uint32 externref_idx;
  3968. void *externref_obj = (void *)(uintptr_t)invokeNative_Int64(
  3969. func_ptr, argv1, n_stacks);
  3970. if (!wasm_externref_obj2ref(exec_env->module_inst,
  3971. externref_obj, &externref_idx))
  3972. goto fail;
  3973. argv_ret[0] = externref_idx;
  3974. }
  3975. break;
  3976. }
  3977. #endif
  3978. #if WASM_ENABLE_SIMD != 0
  3979. case VALUE_TYPE_V128:
  3980. *(v128 *)argv_ret =
  3981. invokeNative_V128(func_ptr, argv1, n_stacks);
  3982. break;
  3983. #endif
  3984. default:
  3985. bh_assert(0);
  3986. break;
  3987. }
  3988. }
  3989. exec_env->attachment = NULL;
  3990. ret = !wasm_runtime_copy_exception(module, NULL);
  3991. fail:
  3992. if (argv1 != argv_buf)
  3993. wasm_runtime_free(argv1);
  3994. return ret;
  3995. }
  3996. #endif /* end of defined(BUILD_TARGET_X86_64) \
  3997. || defined(BUILD_TARGET_AMD_64) \
  3998. || defined(BUILD_TARGET_AARCH64) \
  3999. || defined(BUILD_TARGET_RISCV64_LP64D) \
  4000. || defined(BUILD_TARGET_RISCV64_LP64) */
  4001. bool
  4002. wasm_runtime_call_indirect(WASMExecEnv *exec_env, uint32 element_index,
  4003. uint32 argc, uint32 argv[])
  4004. {
  4005. bool ret = false;
  4006. if (!wasm_runtime_exec_env_check(exec_env)) {
  4007. LOG_ERROR("Invalid exec env stack info.");
  4008. return false;
  4009. }
  4010. /* this function is called from native code, so exec_env->handle and
  4011. exec_env->native_stack_boundary must have been set, we don't set
  4012. it again */
  4013. #if WASM_ENABLE_INTERP != 0
  4014. if (exec_env->module_inst->module_type == Wasm_Module_Bytecode)
  4015. ret = wasm_call_indirect(exec_env, 0, element_index, argc, argv);
  4016. #endif
  4017. #if WASM_ENABLE_AOT != 0
  4018. if (exec_env->module_inst->module_type == Wasm_Module_AoT)
  4019. ret = aot_call_indirect(exec_env, 0, element_index, argc, argv);
  4020. #endif
  4021. if (!ret && clear_wasi_proc_exit_exception(exec_env->module_inst)) {
  4022. ret = true;
  4023. }
  4024. return ret;
  4025. }
  4026. static void
  4027. exchange_uint32(uint8 *p_data)
  4028. {
  4029. uint8 value = *p_data;
  4030. *p_data = *(p_data + 3);
  4031. *(p_data + 3) = value;
  4032. value = *(p_data + 1);
  4033. *(p_data + 1) = *(p_data + 2);
  4034. *(p_data + 2) = value;
  4035. }
  4036. static void
  4037. exchange_uint64(uint8 *p_data)
  4038. {
  4039. uint32 value;
  4040. value = *(uint32 *)p_data;
  4041. *(uint32 *)p_data = *(uint32 *)(p_data + 4);
  4042. *(uint32 *)(p_data + 4) = value;
  4043. exchange_uint32(p_data);
  4044. exchange_uint32(p_data + 4);
  4045. }
  4046. void
  4047. wasm_runtime_read_v128(const uint8 *bytes, uint64 *ret1, uint64 *ret2)
  4048. {
  4049. uint64 u1, u2;
  4050. bh_memcpy_s(&u1, 8, bytes, 8);
  4051. bh_memcpy_s(&u2, 8, bytes + 8, 8);
  4052. if (!is_little_endian()) {
  4053. exchange_uint64((uint8 *)&u1);
  4054. exchange_uint64((uint8 *)&u2);
  4055. *ret1 = u2;
  4056. *ret2 = u1;
  4057. }
  4058. else {
  4059. *ret1 = u1;
  4060. *ret2 = u2;
  4061. }
  4062. }
  4063. #if WASM_ENABLE_THREAD_MGR != 0
  4064. typedef struct WASMThreadArg {
  4065. WASMExecEnv *new_exec_env;
  4066. wasm_thread_callback_t callback;
  4067. void *arg;
  4068. } WASMThreadArg;
  4069. WASMExecEnv *
  4070. wasm_runtime_spawn_exec_env(WASMExecEnv *exec_env)
  4071. {
  4072. return wasm_cluster_spawn_exec_env(exec_env);
  4073. }
  4074. void
  4075. wasm_runtime_destroy_spawned_exec_env(WASMExecEnv *exec_env)
  4076. {
  4077. wasm_cluster_destroy_spawned_exec_env(exec_env);
  4078. }
  4079. static void *
  4080. wasm_runtime_thread_routine(void *arg)
  4081. {
  4082. WASMThreadArg *thread_arg = (WASMThreadArg *)arg;
  4083. void *ret;
  4084. bh_assert(thread_arg->new_exec_env);
  4085. ret = thread_arg->callback(thread_arg->new_exec_env, thread_arg->arg);
  4086. wasm_runtime_destroy_spawned_exec_env(thread_arg->new_exec_env);
  4087. wasm_runtime_free(thread_arg);
  4088. os_thread_exit(ret);
  4089. return ret;
  4090. }
  4091. int32
  4092. wasm_runtime_spawn_thread(WASMExecEnv *exec_env, wasm_thread_t *tid,
  4093. wasm_thread_callback_t callback, void *arg)
  4094. {
  4095. WASMExecEnv *new_exec_env = wasm_runtime_spawn_exec_env(exec_env);
  4096. WASMThreadArg *thread_arg;
  4097. int32 ret;
  4098. if (!new_exec_env)
  4099. return -1;
  4100. if (!(thread_arg = wasm_runtime_malloc(sizeof(WASMThreadArg)))) {
  4101. wasm_runtime_destroy_spawned_exec_env(new_exec_env);
  4102. return -1;
  4103. }
  4104. thread_arg->new_exec_env = new_exec_env;
  4105. thread_arg->callback = callback;
  4106. thread_arg->arg = arg;
  4107. ret = os_thread_create((korp_tid *)tid, wasm_runtime_thread_routine,
  4108. thread_arg, APP_THREAD_STACK_SIZE_DEFAULT);
  4109. if (ret != 0) {
  4110. wasm_runtime_destroy_spawned_exec_env(new_exec_env);
  4111. wasm_runtime_free(thread_arg);
  4112. }
  4113. return ret;
  4114. }
  4115. int32
  4116. wasm_runtime_join_thread(wasm_thread_t tid, void **retval)
  4117. {
  4118. return os_thread_join((korp_tid)tid, retval);
  4119. }
  4120. #endif /* end of WASM_ENABLE_THREAD_MGR */
  4121. #if WASM_ENABLE_REF_TYPES != 0
  4122. static korp_mutex externref_lock;
  4123. static uint32 externref_global_id = 1;
  4124. static HashMap *externref_map;
  4125. typedef struct ExternRefMapNode {
  4126. /* The extern object from runtime embedder */
  4127. void *extern_obj;
  4128. /* The module instance it belongs to */
  4129. WASMModuleInstanceCommon *module_inst;
  4130. /* Whether it is retained */
  4131. bool retained;
  4132. /* Whether it is marked by runtime */
  4133. bool marked;
  4134. } ExternRefMapNode;
  4135. static uint32
  4136. wasm_externref_hash(const void *key)
  4137. {
  4138. uint32 externref_idx = (uint32)(uintptr_t)key;
  4139. return externref_idx;
  4140. }
  4141. static bool
  4142. wasm_externref_equal(void *key1, void *key2)
  4143. {
  4144. uint32 externref_idx1 = (uint32)(uintptr_t)key1;
  4145. uint32 externref_idx2 = (uint32)(uintptr_t)key2;
  4146. return externref_idx1 == externref_idx2 ? true : false;
  4147. }
  4148. static bool
  4149. wasm_externref_map_init()
  4150. {
  4151. if (os_mutex_init(&externref_lock) != 0)
  4152. return false;
  4153. if (!(externref_map = bh_hash_map_create(32, false, wasm_externref_hash,
  4154. wasm_externref_equal, NULL,
  4155. wasm_runtime_free))) {
  4156. os_mutex_destroy(&externref_lock);
  4157. return false;
  4158. }
  4159. externref_global_id = 1;
  4160. return true;
  4161. }
  4162. static void
  4163. wasm_externref_map_destroy()
  4164. {
  4165. bh_hash_map_destroy(externref_map);
  4166. os_mutex_destroy(&externref_lock);
  4167. }
  4168. typedef struct LookupExtObj_UserData {
  4169. ExternRefMapNode node;
  4170. bool found;
  4171. uint32 externref_idx;
  4172. } LookupExtObj_UserData;
  4173. static void
  4174. lookup_extobj_callback(void *key, void *value, void *user_data)
  4175. {
  4176. uint32 externref_idx = (uint32)(uintptr_t)key;
  4177. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4178. LookupExtObj_UserData *user_data_lookup =
  4179. (LookupExtObj_UserData *)user_data;
  4180. if (node->extern_obj == user_data_lookup->node.extern_obj
  4181. && node->module_inst == user_data_lookup->node.module_inst) {
  4182. user_data_lookup->found = true;
  4183. user_data_lookup->externref_idx = externref_idx;
  4184. }
  4185. }
  4186. bool
  4187. wasm_externref_obj2ref(WASMModuleInstanceCommon *module_inst, void *extern_obj,
  4188. uint32 *p_externref_idx)
  4189. {
  4190. LookupExtObj_UserData lookup_user_data = { 0 };
  4191. ExternRefMapNode *node;
  4192. uint32 externref_idx;
  4193. /*
  4194. * to catch a parameter from `wasm_application_execute_func`,
  4195. * which represents a string 'null'
  4196. */
  4197. #if UINTPTR_MAX == UINT32_MAX
  4198. if ((uint32)-1 == (uintptr_t)extern_obj) {
  4199. #else
  4200. if ((uint64)-1LL == (uintptr_t)extern_obj) {
  4201. #endif
  4202. *p_externref_idx = NULL_REF;
  4203. return true;
  4204. }
  4205. /* in a wrapper, extern_obj could be any value */
  4206. lookup_user_data.node.extern_obj = extern_obj;
  4207. lookup_user_data.node.module_inst = module_inst;
  4208. lookup_user_data.found = false;
  4209. os_mutex_lock(&externref_lock);
  4210. /* Lookup hashmap firstly */
  4211. bh_hash_map_traverse(externref_map, lookup_extobj_callback,
  4212. (void *)&lookup_user_data);
  4213. if (lookup_user_data.found) {
  4214. *p_externref_idx = lookup_user_data.externref_idx;
  4215. os_mutex_unlock(&externref_lock);
  4216. return true;
  4217. }
  4218. /* Not found in hashmap */
  4219. if (externref_global_id == NULL_REF || externref_global_id == 0) {
  4220. goto fail1;
  4221. }
  4222. if (!(node = wasm_runtime_malloc(sizeof(ExternRefMapNode)))) {
  4223. goto fail1;
  4224. }
  4225. memset(node, 0, sizeof(ExternRefMapNode));
  4226. node->extern_obj = extern_obj;
  4227. node->module_inst = module_inst;
  4228. externref_idx = externref_global_id;
  4229. if (!bh_hash_map_insert(externref_map, (void *)(uintptr_t)externref_idx,
  4230. (void *)node)) {
  4231. goto fail2;
  4232. }
  4233. externref_global_id++;
  4234. *p_externref_idx = externref_idx;
  4235. os_mutex_unlock(&externref_lock);
  4236. return true;
  4237. fail2:
  4238. wasm_runtime_free(node);
  4239. fail1:
  4240. os_mutex_unlock(&externref_lock);
  4241. return false;
  4242. }
  4243. bool
  4244. wasm_externref_ref2obj(uint32 externref_idx, void **p_extern_obj)
  4245. {
  4246. ExternRefMapNode *node;
  4247. /* catch a `ref.null` vairable */
  4248. if (externref_idx == NULL_REF) {
  4249. *p_extern_obj = NULL;
  4250. return true;
  4251. }
  4252. os_mutex_lock(&externref_lock);
  4253. node = bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4254. os_mutex_unlock(&externref_lock);
  4255. if (!node)
  4256. return false;
  4257. *p_extern_obj = node->extern_obj;
  4258. return true;
  4259. }
  4260. static void
  4261. reclaim_extobj_callback(void *key, void *value, void *user_data)
  4262. {
  4263. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4264. WASMModuleInstanceCommon *module_inst =
  4265. (WASMModuleInstanceCommon *)user_data;
  4266. if (node->module_inst == module_inst) {
  4267. if (!node->marked && !node->retained) {
  4268. bh_hash_map_remove(externref_map, key, NULL, NULL);
  4269. wasm_runtime_free(value);
  4270. }
  4271. else {
  4272. node->marked = false;
  4273. }
  4274. }
  4275. }
  4276. static void
  4277. mark_externref(uint32 externref_idx)
  4278. {
  4279. ExternRefMapNode *node;
  4280. if (externref_idx != NULL_REF) {
  4281. node =
  4282. bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4283. if (node) {
  4284. node->marked = true;
  4285. }
  4286. }
  4287. }
  4288. #if WASM_ENABLE_INTERP != 0
  4289. static void
  4290. interp_mark_all_externrefs(WASMModuleInstance *module_inst)
  4291. {
  4292. uint32 i, j, externref_idx, *table_data;
  4293. uint8 *global_data = module_inst->global_data;
  4294. WASMGlobalInstance *global;
  4295. WASMTableInstance *table;
  4296. global = module_inst->e->globals;
  4297. for (i = 0; i < module_inst->e->global_count; i++, global++) {
  4298. if (global->type == VALUE_TYPE_EXTERNREF) {
  4299. externref_idx = *(uint32 *)(global_data + global->data_offset);
  4300. mark_externref(externref_idx);
  4301. }
  4302. }
  4303. for (i = 0; i < module_inst->table_count; i++) {
  4304. uint8 elem_type = 0;
  4305. uint32 init_size, max_size;
  4306. table = wasm_get_table_inst(module_inst, i);
  4307. (void)wasm_runtime_get_table_inst_elem_type(
  4308. (WASMModuleInstanceCommon *)module_inst, i, &elem_type, &init_size,
  4309. &max_size);
  4310. if (elem_type == VALUE_TYPE_EXTERNREF) {
  4311. table_data = table->elems;
  4312. for (j = 0; j < table->cur_size; j++) {
  4313. externref_idx = table_data[j];
  4314. mark_externref(externref_idx);
  4315. }
  4316. }
  4317. (void)init_size;
  4318. (void)max_size;
  4319. }
  4320. }
  4321. #endif
  4322. #if WASM_ENABLE_AOT != 0
  4323. static void
  4324. aot_mark_all_externrefs(AOTModuleInstance *module_inst)
  4325. {
  4326. uint32 i = 0, j = 0;
  4327. const AOTModule *module = (AOTModule *)module_inst->module;
  4328. const AOTTable *table = module->tables;
  4329. const AOTGlobal *global = module->globals;
  4330. const AOTTableInstance *table_inst;
  4331. for (i = 0; i < module->global_count; i++, global++) {
  4332. if (global->type == VALUE_TYPE_EXTERNREF) {
  4333. mark_externref(
  4334. *(uint32 *)(module_inst->global_data + global->data_offset));
  4335. }
  4336. }
  4337. for (i = 0; i < module->table_count; i++) {
  4338. table_inst = module_inst->tables[i];
  4339. if ((table + i)->elem_type == VALUE_TYPE_EXTERNREF) {
  4340. while (j < table_inst->cur_size) {
  4341. mark_externref(table_inst->elems[j++]);
  4342. }
  4343. }
  4344. }
  4345. }
  4346. #endif
  4347. void
  4348. wasm_externref_reclaim(WASMModuleInstanceCommon *module_inst)
  4349. {
  4350. os_mutex_lock(&externref_lock);
  4351. #if WASM_ENABLE_INTERP != 0
  4352. if (module_inst->module_type == Wasm_Module_Bytecode)
  4353. interp_mark_all_externrefs((WASMModuleInstance *)module_inst);
  4354. #endif
  4355. #if WASM_ENABLE_AOT != 0
  4356. if (module_inst->module_type == Wasm_Module_AoT)
  4357. aot_mark_all_externrefs((AOTModuleInstance *)module_inst);
  4358. #endif
  4359. bh_hash_map_traverse(externref_map, reclaim_extobj_callback,
  4360. (void *)module_inst);
  4361. os_mutex_unlock(&externref_lock);
  4362. }
  4363. static void
  4364. cleanup_extobj_callback(void *key, void *value, void *user_data)
  4365. {
  4366. ExternRefMapNode *node = (ExternRefMapNode *)value;
  4367. WASMModuleInstanceCommon *module_inst =
  4368. (WASMModuleInstanceCommon *)user_data;
  4369. if (node->module_inst == module_inst) {
  4370. bh_hash_map_remove(externref_map, key, NULL, NULL);
  4371. wasm_runtime_free(value);
  4372. }
  4373. }
  4374. void
  4375. wasm_externref_cleanup(WASMModuleInstanceCommon *module_inst)
  4376. {
  4377. os_mutex_lock(&externref_lock);
  4378. bh_hash_map_traverse(externref_map, cleanup_extobj_callback,
  4379. (void *)module_inst);
  4380. os_mutex_unlock(&externref_lock);
  4381. }
  4382. bool
  4383. wasm_externref_retain(uint32 externref_idx)
  4384. {
  4385. ExternRefMapNode *node;
  4386. os_mutex_lock(&externref_lock);
  4387. if (externref_idx != NULL_REF) {
  4388. node =
  4389. bh_hash_map_find(externref_map, (void *)(uintptr_t)externref_idx);
  4390. if (node) {
  4391. node->retained = true;
  4392. os_mutex_unlock(&externref_lock);
  4393. return true;
  4394. }
  4395. }
  4396. os_mutex_unlock(&externref_lock);
  4397. return false;
  4398. }
  4399. #endif /* end of WASM_ENABLE_REF_TYPES */
  4400. #if WASM_ENABLE_DUMP_CALL_STACK != 0
  4401. uint32
  4402. wasm_runtime_dump_line_buf_impl(const char *line_buf, bool dump_or_print,
  4403. char **buf, uint32 *len)
  4404. {
  4405. if (dump_or_print) {
  4406. return (uint32)os_printf("%s", line_buf);
  4407. }
  4408. else if (*buf) {
  4409. uint32 dump_len;
  4410. dump_len = snprintf(*buf, *len, "%s", line_buf);
  4411. if (dump_len >= *len) {
  4412. dump_len = *len;
  4413. }
  4414. *len = *len - dump_len;
  4415. *buf = *buf + dump_len;
  4416. return dump_len;
  4417. }
  4418. else {
  4419. return (uint32)strlen(line_buf);
  4420. }
  4421. }
  4422. void
  4423. wasm_runtime_dump_call_stack(WASMExecEnv *exec_env)
  4424. {
  4425. WASMModuleInstanceCommon *module_inst =
  4426. wasm_exec_env_get_module_inst(exec_env);
  4427. #if WASM_ENABLE_INTERP != 0
  4428. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4429. wasm_interp_dump_call_stack(exec_env, true, NULL, 0);
  4430. }
  4431. #endif
  4432. #if WASM_ENABLE_AOT != 0
  4433. if (module_inst->module_type == Wasm_Module_AoT) {
  4434. aot_dump_call_stack(exec_env, true, NULL, 0);
  4435. }
  4436. #endif
  4437. }
  4438. uint32
  4439. wasm_runtime_get_call_stack_buf_size(wasm_exec_env_t exec_env)
  4440. {
  4441. WASMModuleInstanceCommon *module_inst =
  4442. wasm_exec_env_get_module_inst(exec_env);
  4443. #if WASM_ENABLE_INTERP != 0
  4444. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4445. return wasm_interp_dump_call_stack(exec_env, false, NULL, 0);
  4446. }
  4447. #endif
  4448. #if WASM_ENABLE_AOT != 0
  4449. if (module_inst->module_type == Wasm_Module_AoT) {
  4450. return aot_dump_call_stack(exec_env, false, NULL, 0);
  4451. }
  4452. #endif
  4453. return 0;
  4454. }
  4455. uint32
  4456. wasm_runtime_dump_call_stack_to_buf(wasm_exec_env_t exec_env, char *buf,
  4457. uint32 len)
  4458. {
  4459. WASMModuleInstanceCommon *module_inst =
  4460. wasm_exec_env_get_module_inst(exec_env);
  4461. #if WASM_ENABLE_INTERP != 0
  4462. if (module_inst->module_type == Wasm_Module_Bytecode) {
  4463. return wasm_interp_dump_call_stack(exec_env, false, buf, len);
  4464. }
  4465. #endif
  4466. #if WASM_ENABLE_AOT != 0
  4467. if (module_inst->module_type == Wasm_Module_AoT) {
  4468. return aot_dump_call_stack(exec_env, false, buf, len);
  4469. }
  4470. #endif
  4471. return 0;
  4472. }
  4473. #endif /* end of WASM_ENABLE_DUMP_CALL_STACK */
  4474. bool
  4475. wasm_runtime_get_table_elem_type(const WASMModuleCommon *module_comm,
  4476. uint32 table_idx, uint8 *out_elem_type,
  4477. uint32 *out_min_size, uint32 *out_max_size)
  4478. {
  4479. #if WASM_ENABLE_INTERP != 0
  4480. if (module_comm->module_type == Wasm_Module_Bytecode) {
  4481. WASMModule *module = (WASMModule *)module_comm;
  4482. if (table_idx < module->import_table_count) {
  4483. WASMTableImport *import_table =
  4484. &((module->import_tables + table_idx)->u.table);
  4485. *out_elem_type = import_table->elem_type;
  4486. *out_min_size = import_table->init_size;
  4487. *out_max_size = import_table->max_size;
  4488. }
  4489. else {
  4490. WASMTable *table =
  4491. module->tables + (table_idx - module->import_table_count);
  4492. *out_elem_type = table->elem_type;
  4493. *out_min_size = table->init_size;
  4494. *out_max_size = table->max_size;
  4495. }
  4496. return true;
  4497. }
  4498. #endif
  4499. #if WASM_ENABLE_AOT != 0
  4500. if (module_comm->module_type == Wasm_Module_AoT) {
  4501. AOTModule *module = (AOTModule *)module_comm;
  4502. if (table_idx < module->import_table_count) {
  4503. AOTImportTable *import_table = module->import_tables + table_idx;
  4504. *out_elem_type = VALUE_TYPE_FUNCREF;
  4505. *out_min_size = import_table->table_init_size;
  4506. *out_max_size = import_table->table_max_size;
  4507. }
  4508. else {
  4509. AOTTable *table =
  4510. module->tables + (table_idx - module->import_table_count);
  4511. *out_elem_type = table->elem_type;
  4512. *out_min_size = table->table_init_size;
  4513. *out_max_size = table->table_max_size;
  4514. }
  4515. return true;
  4516. }
  4517. #endif
  4518. return false;
  4519. }
  4520. bool
  4521. wasm_runtime_get_table_inst_elem_type(
  4522. const WASMModuleInstanceCommon *module_inst_comm, uint32 table_idx,
  4523. uint8 *out_elem_type, uint32 *out_min_size, uint32 *out_max_size)
  4524. {
  4525. #if WASM_ENABLE_INTERP != 0
  4526. if (module_inst_comm->module_type == Wasm_Module_Bytecode) {
  4527. WASMModuleInstance *module_inst =
  4528. (WASMModuleInstance *)module_inst_comm;
  4529. return wasm_runtime_get_table_elem_type(
  4530. (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type,
  4531. out_min_size, out_max_size);
  4532. }
  4533. #endif
  4534. #if WASM_ENABLE_AOT != 0
  4535. if (module_inst_comm->module_type == Wasm_Module_AoT) {
  4536. AOTModuleInstance *module_inst = (AOTModuleInstance *)module_inst_comm;
  4537. return wasm_runtime_get_table_elem_type(
  4538. (WASMModuleCommon *)module_inst->module, table_idx, out_elem_type,
  4539. out_min_size, out_max_size);
  4540. }
  4541. #endif
  4542. return false;
  4543. }
  4544. bool
  4545. wasm_runtime_get_export_func_type(const WASMModuleCommon *module_comm,
  4546. const WASMExport *export, WASMType **out)
  4547. {
  4548. #if WASM_ENABLE_INTERP != 0
  4549. if (module_comm->module_type == Wasm_Module_Bytecode) {
  4550. WASMModule *module = (WASMModule *)module_comm;
  4551. if (export->index < module->import_function_count) {
  4552. *out = module->import_functions[export->index].u.function.func_type;
  4553. }
  4554. else {
  4555. *out =
  4556. module->functions[export->index - module->import_function_count]
  4557. ->func_type;
  4558. }
  4559. return true;
  4560. }
  4561. #endif
  4562. #if WASM_ENABLE_AOT != 0
  4563. if (module_comm->module_type == Wasm_Module_AoT) {
  4564. AOTModule *module = (AOTModule *)module_comm;
  4565. if (export->index < module->import_func_count) {
  4566. *out = module->func_types[module->import_funcs[export->index]
  4567. .func_type_index];
  4568. }
  4569. else {
  4570. *out = module->func_types
  4571. [module->func_type_indexes[export->index
  4572. - module->import_func_count]];
  4573. }
  4574. return true;
  4575. }
  4576. #endif
  4577. return false;
  4578. }
  4579. bool
  4580. wasm_runtime_get_export_global_type(const WASMModuleCommon *module_comm,
  4581. const WASMExport *export,
  4582. uint8 *out_val_type, bool *out_mutability)
  4583. {
  4584. #if WASM_ENABLE_INTERP != 0
  4585. if (module_comm->module_type == Wasm_Module_Bytecode) {
  4586. WASMModule *module = (WASMModule *)module_comm;
  4587. if (export->index < module->import_global_count) {
  4588. WASMGlobalImport *import_global =
  4589. &((module->import_globals + export->index)->u.global);
  4590. *out_val_type = import_global->type;
  4591. *out_mutability = import_global->is_mutable;
  4592. }
  4593. else {
  4594. WASMGlobal *global =
  4595. module->globals + (export->index - module->import_global_count);
  4596. *out_val_type = global->type;
  4597. *out_mutability = global->is_mutable;
  4598. }
  4599. return true;
  4600. }
  4601. #endif
  4602. #if WASM_ENABLE_AOT != 0
  4603. if (module_comm->module_type == Wasm_Module_AoT) {
  4604. AOTModule *module = (AOTModule *)module_comm;
  4605. if (export->index < module->import_global_count) {
  4606. AOTImportGlobal *import_global =
  4607. module->import_globals + export->index;
  4608. *out_val_type = import_global->type;
  4609. *out_mutability = import_global->is_mutable;
  4610. }
  4611. else {
  4612. AOTGlobal *global =
  4613. module->globals + (export->index - module->import_global_count);
  4614. *out_val_type = global->type;
  4615. *out_mutability = global->is_mutable;
  4616. }
  4617. return true;
  4618. }
  4619. #endif
  4620. return false;
  4621. }
  4622. bool
  4623. wasm_runtime_get_export_memory_type(const WASMModuleCommon *module_comm,
  4624. const WASMExport *export,
  4625. uint32 *out_min_page, uint32 *out_max_page)
  4626. {
  4627. #if WASM_ENABLE_INTERP != 0
  4628. if (module_comm->module_type == Wasm_Module_Bytecode) {
  4629. WASMModule *module = (WASMModule *)module_comm;
  4630. if (export->index < module->import_memory_count) {
  4631. WASMMemoryImport *import_memory =
  4632. &((module->import_memories + export->index)->u.memory);
  4633. *out_min_page = import_memory->init_page_count;
  4634. *out_max_page = import_memory->max_page_count;
  4635. }
  4636. else {
  4637. WASMMemory *memory =
  4638. module->memories
  4639. + (export->index - module->import_memory_count);
  4640. *out_min_page = memory->init_page_count;
  4641. *out_max_page = memory->max_page_count;
  4642. }
  4643. return true;
  4644. }
  4645. #endif
  4646. #if WASM_ENABLE_AOT != 0
  4647. if (module_comm->module_type == Wasm_Module_AoT) {
  4648. AOTModule *module = (AOTModule *)module_comm;
  4649. if (export->index < module->import_memory_count) {
  4650. AOTImportMemory *import_memory =
  4651. module->import_memories + export->index;
  4652. *out_min_page = import_memory->mem_init_page_count;
  4653. *out_max_page = import_memory->mem_max_page_count;
  4654. }
  4655. else {
  4656. AOTMemory *memory = module->memories
  4657. + (export->index - module->import_memory_count);
  4658. *out_min_page = memory->mem_init_page_count;
  4659. *out_max_page = memory->mem_max_page_count;
  4660. }
  4661. return true;
  4662. }
  4663. #endif
  4664. return false;
  4665. }
  4666. bool
  4667. wasm_runtime_get_export_table_type(const WASMModuleCommon *module_comm,
  4668. const WASMExport *export,
  4669. uint8 *out_elem_type, uint32 *out_min_size,
  4670. uint32 *out_max_size)
  4671. {
  4672. return wasm_runtime_get_table_elem_type(
  4673. module_comm, export->index, out_elem_type, out_min_size, out_max_size);
  4674. }
  4675. static inline bool
  4676. argv_to_params(wasm_val_t *out_params, const uint32 *argv, WASMType *func_type)
  4677. {
  4678. wasm_val_t *param = out_params;
  4679. uint32 i = 0, *u32;
  4680. for (i = 0; i < func_type->param_count; i++, param++) {
  4681. switch (func_type->types[i]) {
  4682. case VALUE_TYPE_I32:
  4683. param->kind = WASM_I32;
  4684. param->of.i32 = *argv++;
  4685. break;
  4686. case VALUE_TYPE_I64:
  4687. param->kind = WASM_I64;
  4688. u32 = (uint32 *)&param->of.i64;
  4689. u32[0] = *argv++;
  4690. u32[1] = *argv++;
  4691. break;
  4692. case VALUE_TYPE_F32:
  4693. param->kind = WASM_F32;
  4694. param->of.f32 = *(float32 *)argv++;
  4695. break;
  4696. case VALUE_TYPE_F64:
  4697. param->kind = WASM_F64;
  4698. u32 = (uint32 *)&param->of.i64;
  4699. u32[0] = *argv++;
  4700. u32[1] = *argv++;
  4701. break;
  4702. #if WASM_ENABLE_REF_TYPES != 0
  4703. case VALUE_TYPE_EXTERNREF:
  4704. param->kind = WASM_ANYREF;
  4705. if (!wasm_externref_ref2obj(*argv,
  4706. (void **)&param->of.foreign)) {
  4707. return false;
  4708. }
  4709. argv++;
  4710. break;
  4711. #endif
  4712. default:
  4713. return false;
  4714. }
  4715. }
  4716. return true;
  4717. }
  4718. static inline bool
  4719. results_to_argv(WASMModuleInstanceCommon *module_inst, uint32 *out_argv,
  4720. const wasm_val_t *results, WASMType *func_type)
  4721. {
  4722. const wasm_val_t *result = results;
  4723. uint32 *argv = out_argv, *u32, i;
  4724. uint8 *result_types = func_type->types + func_type->param_count;
  4725. for (i = 0; i < func_type->result_count; i++, result++) {
  4726. switch (result_types[i]) {
  4727. case VALUE_TYPE_I32:
  4728. case VALUE_TYPE_F32:
  4729. *(int32 *)argv++ = result->of.i32;
  4730. break;
  4731. case VALUE_TYPE_I64:
  4732. case VALUE_TYPE_F64:
  4733. u32 = (uint32 *)&result->of.i64;
  4734. *argv++ = u32[0];
  4735. *argv++ = u32[1];
  4736. break;
  4737. #if WASM_ENABLE_REF_TYPES != 0
  4738. case VALUE_TYPE_EXTERNREF:
  4739. if (!wasm_externref_obj2ref(module_inst,
  4740. (void *)result->of.foreign, argv)) {
  4741. return false;
  4742. }
  4743. argv++;
  4744. break;
  4745. #endif
  4746. default:
  4747. return false;
  4748. }
  4749. }
  4750. return true;
  4751. }
  4752. bool
  4753. wasm_runtime_invoke_c_api_native(WASMModuleInstanceCommon *module_inst,
  4754. void *func_ptr, WASMType *func_type,
  4755. uint32 argc, uint32 *argv, bool with_env,
  4756. void *wasm_c_api_env)
  4757. {
  4758. wasm_val_t params_buf[16] = { 0 }, results_buf[4] = { 0 };
  4759. wasm_val_t *params = params_buf, *results = results_buf;
  4760. wasm_trap_t *trap = NULL;
  4761. bool ret = false;
  4762. wasm_val_vec_t params_vec, results_vec;
  4763. if (func_type->param_count > 16) {
  4764. if (!(params =
  4765. runtime_malloc(sizeof(wasm_val_t) * func_type->param_count,
  4766. module_inst, NULL, 0))) {
  4767. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  4768. return false;
  4769. }
  4770. }
  4771. if (!argv_to_params(params, argv, func_type)) {
  4772. wasm_runtime_set_exception(module_inst, "unsupported param type");
  4773. goto fail;
  4774. }
  4775. if (func_type->result_count > 4) {
  4776. if (!(results =
  4777. runtime_malloc(sizeof(wasm_val_t) * func_type->result_count,
  4778. module_inst, NULL, 0))) {
  4779. wasm_runtime_set_exception(module_inst, "allocate memory failed");
  4780. goto fail;
  4781. }
  4782. }
  4783. params_vec.data = params;
  4784. params_vec.num_elems = func_type->param_count;
  4785. params_vec.size = func_type->param_count;
  4786. params_vec.size_of_elem = sizeof(wasm_val_t);
  4787. results_vec.data = results;
  4788. results_vec.num_elems = 0;
  4789. results_vec.size = func_type->result_count;
  4790. results_vec.size_of_elem = sizeof(wasm_val_t);
  4791. if (!with_env) {
  4792. wasm_func_callback_t callback = (wasm_func_callback_t)func_ptr;
  4793. trap = callback(&params_vec, &results_vec);
  4794. }
  4795. else {
  4796. wasm_func_callback_with_env_t callback =
  4797. (wasm_func_callback_with_env_t)func_ptr;
  4798. trap = callback(wasm_c_api_env, &params_vec, &results_vec);
  4799. }
  4800. if (trap) {
  4801. if (trap->message->data) {
  4802. /* since trap->message->data does not end with '\0' */
  4803. char trap_message[108] = { 0 };
  4804. uint32 max_size_to_copy = (uint32)sizeof(trap_message) - 1;
  4805. uint32 size_to_copy = (trap->message->size < max_size_to_copy)
  4806. ? (uint32)trap->message->size
  4807. : max_size_to_copy;
  4808. bh_memcpy_s(trap_message, (uint32)sizeof(trap_message),
  4809. trap->message->data, size_to_copy);
  4810. wasm_runtime_set_exception(module_inst, trap_message);
  4811. }
  4812. else {
  4813. wasm_runtime_set_exception(
  4814. module_inst, "native function throw unknown exception");
  4815. }
  4816. wasm_trap_delete(trap);
  4817. goto fail;
  4818. }
  4819. if (!results_to_argv(module_inst, argv, results, func_type)) {
  4820. wasm_runtime_set_exception(module_inst, "unsupported result type");
  4821. goto fail;
  4822. }
  4823. results_vec.num_elems = func_type->result_count;
  4824. ret = true;
  4825. fail:
  4826. if (params != params_buf)
  4827. wasm_runtime_free(params);
  4828. if (results != results_buf)
  4829. wasm_runtime_free(results);
  4830. return ret;
  4831. }
  4832. void
  4833. wasm_runtime_show_app_heap_corrupted_prompt()
  4834. {
  4835. LOG_ERROR("Error: app heap is corrupted, if the wasm file "
  4836. "is compiled by wasi-sdk-12.0 or higher version, "
  4837. "please add -Wl,--export=malloc -Wl,--export=free "
  4838. "to export malloc and free functions. If it is "
  4839. "compiled by asc, please add --exportRuntime to "
  4840. "export the runtime helpers.");
  4841. }
  4842. #if WASM_ENABLE_LOAD_CUSTOM_SECTION != 0
  4843. void
  4844. wasm_runtime_destroy_custom_sections(WASMCustomSection *section_list)
  4845. {
  4846. WASMCustomSection *section = section_list, *next;
  4847. while (section) {
  4848. next = section->next;
  4849. wasm_runtime_free(section);
  4850. section = next;
  4851. }
  4852. }
  4853. #endif /* end of WASM_ENABLE_LOAD_CUSTOM_SECTION */
  4854. void
  4855. wasm_runtime_get_version(uint32_t *major, uint32_t *minor, uint32_t *patch)
  4856. {
  4857. *major = WAMR_VERSION_MAJOR;
  4858. *minor = WAMR_VERSION_MINOR;
  4859. *patch = WAMR_VERSION_PATCH;
  4860. }
  4861. bool
  4862. wasm_runtime_is_import_func_linked(const char *module_name,
  4863. const char *func_name)
  4864. {
  4865. return wasm_native_resolve_symbol(module_name, func_name, NULL, NULL, NULL,
  4866. NULL);
  4867. }
  4868. bool
  4869. wasm_runtime_is_import_global_linked(const char *module_name,
  4870. const char *global_name)
  4871. {
  4872. #if WASM_ENABLE_LIBC_BUILTIN != 0
  4873. WASMGlobalImport global = { 0 };
  4874. return wasm_native_lookup_libc_builtin_global(module_name, global_name,
  4875. &global);
  4876. #else
  4877. return false;
  4878. #endif
  4879. }