wasm_runtime.c 189 KB

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