wasm_runtime_common.c 161 KB

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