wasm_runtime_common.c 158 KB

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