aot_runtime.c 194 KB

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