aot_runtime.c 179 KB

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