ogwasm.pas 246 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329
  1. {
  2. Copyright (c) 2021 by Nikolay Nikolov
  3. Contains the WebAssembly binary module format reader and writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit ogwasm;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cclasses,globtype,
  23. { target }
  24. systems,cpubase,
  25. { assembler }
  26. aasmbase,assemble,aasmcpu,
  27. { WebAssembly module format definitions }
  28. wasmbase,
  29. { output }
  30. ogbase,
  31. owbase;
  32. type
  33. TWasmObjSymbolExtraData = class;
  34. TGlobalInitializer = record
  35. case typ:TWasmBasicType of
  36. wbt_i32: (init_i32: Int32);
  37. wbt_i64: (init_i64: Int64);
  38. wbt_f32: (init_f32: Single);
  39. wbt_f64: (init_f64: Double);
  40. end;
  41. { TWasmObjSymbolLinkingData }
  42. TWasmObjSymbolLinkingData = class
  43. public
  44. ImportModule: string;
  45. ImportName: string;
  46. FuncType: TWasmFuncType;
  47. ExeFunctionIndex: Integer;
  48. ExeIndirectFunctionTableIndex: Integer;
  49. ExeTypeIndex: Integer;
  50. ExeTagIndex: Integer;
  51. GlobalType: TWasmBasicType;
  52. GlobalIsMutable: Boolean;
  53. GlobalInitializer: TGlobalInitializer;
  54. IsExported: Boolean;
  55. ExportName: ansistring;
  56. constructor Create;
  57. destructor Destroy;override;
  58. end;
  59. { TWasmObjSymbol }
  60. TWasmObjSymbol = class(TObjSymbol)
  61. FuncIndex: Integer;
  62. SymbolIndex: Integer;
  63. GlobalIndex: Integer;
  64. TagIndex: Integer;
  65. AliasOf: string;
  66. ExtraData: TWasmObjSymbolExtraData;
  67. LinkingData: TWasmObjSymbolLinkingData;
  68. TlsGlobalSym: TWasmObjSymbol;
  69. TlsDataSym: TWasmObjSymbol;
  70. constructor create(AList:TFPHashObjectList;const AName:string);override;
  71. destructor Destroy;override;
  72. function IsAlias: Boolean;
  73. end;
  74. { TWasmObjRelocation }
  75. TWasmObjRelocation = class(TObjRelocation)
  76. public
  77. TypeIndex: Integer;
  78. Addend: LongInt;
  79. { used during linking }
  80. FuncType: TWasmFuncType;
  81. ExeTypeIndex: Integer;
  82. IsFunctionOffsetI32: Boolean;
  83. constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
  84. constructor CreateFuncType(ADataOffset:TObjSectionOfs; AFuncType: TWasmFuncType);
  85. destructor Destroy;override;
  86. end;
  87. { TWasmObjSymbolExtraData }
  88. TWasmObjSymbolExtraData = class(TFPHashObject)
  89. TypeIdx: Integer;
  90. ExceptionTagTypeIdx: Integer;
  91. ImportModule: string;
  92. ImportName: string;
  93. ExportName: string;
  94. GlobalType: TWasmBasicType;
  95. GlobalIsImmutable: Boolean;
  96. Locals: array of TWasmBasicType;
  97. EncodedLocals: tdynamicarray;
  98. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  99. destructor Destroy; override;
  100. procedure AddLocals(alocals: TWasmLocalsDynArray);
  101. end;
  102. { TWasmObjSection }
  103. TWasmObjSection = class(TObjSection)
  104. public
  105. SegIdx: Integer;
  106. SegSymIdx: Integer;
  107. SegOfs: qword;
  108. FileSectionOfs: qword;
  109. MainFuncSymbol: TWasmObjSymbol;
  110. CustomSectionIdx: Integer;
  111. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  112. function IsCode: Boolean;
  113. function IsData: Boolean;
  114. function IsDebug: Boolean;
  115. end;
  116. { TWasmFuncTypeTable }
  117. TWasmFuncTypeTable = class
  118. private
  119. FFuncTypes: array of TWasmFuncType;
  120. function GetCount: Integer;
  121. function GetItem(Index: Integer): TWasmFuncType;
  122. public
  123. destructor Destroy; override;
  124. function AddOrGetFuncType(wft: TWasmFuncType): integer;
  125. procedure WriteTo(d: tdynamicarray);
  126. property Count: Integer read GetCount;
  127. property Items[Index: Integer]: TWasmFuncType read GetItem; default;
  128. end;
  129. { TWasmObjData }
  130. TWasmObjData = class(TObjData)
  131. private
  132. FFuncTypes: TWasmFuncTypeTable;
  133. FObjSymbolsExtraDataList: TFPHashObjectList;
  134. FLastFuncName: string;
  135. function is_smart_section(atype:TAsmSectiontype):boolean;
  136. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  137. public
  138. constructor create(const n:string);override;
  139. destructor destroy; override;
  140. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  141. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  142. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  143. function globalref(asmsym:TAsmSymbol):TObjSymbol;
  144. function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
  145. procedure DeclareGlobalType(gt: tai_globaltype);
  146. procedure DeclareFuncType_Pass0(ft: tai_functype);
  147. procedure DeclareFuncType_Pass1(ft: tai_functype);
  148. procedure DeclareFuncType_Pass2(ft: tai_functype);
  149. procedure DeclareTagType(tt: tai_tagtype);
  150. procedure DeclareExportName(en: tai_export_name);
  151. procedure DeclareImportModule(aim: tai_import_module);
  152. procedure DeclareImportName(ain: tai_import_name);
  153. procedure DeclareLocals_Pass0(al: tai_local);
  154. procedure DeclareLocals_Pass1(al: tai_local);
  155. procedure WriteLocals_Pass2(al: tai_local);
  156. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  157. property FuncTypes: TWasmFuncTypeTable read FFuncTypes;
  158. end;
  159. { TWasmObjOutput }
  160. TWasmObjOutput = class(tObjOutput)
  161. private
  162. FData: TWasmObjData;
  163. FWasmRelocationCodeTable: tdynamicarray;
  164. FWasmRelocationCodeTableEntriesCount: Integer;
  165. FWasmRelocationDataTable: tdynamicarray;
  166. FWasmRelocationDataTableEntriesCount: Integer;
  167. FWasmRelocationDebugFrameTable: tdynamicarray;
  168. FWasmRelocationDebugFrameTableEntriesCount: Integer;
  169. FWasmRelocationDebugInfoTable: tdynamicarray;
  170. FWasmRelocationDebugInfoTableEntriesCount: Integer;
  171. FWasmRelocationDebugLineTable: tdynamicarray;
  172. FWasmRelocationDebugLineTableEntriesCount: Integer;
  173. FWasmRelocationDebugAbbrevTable: tdynamicarray;
  174. FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
  175. FWasmRelocationDebugArangesTable: tdynamicarray;
  176. FWasmRelocationDebugArangesTableEntriesCount: Integer;
  177. FWasmRelocationDebugRangesTable: tdynamicarray;
  178. FWasmRelocationDebugRangesTableEntriesCount: Integer;
  179. FWasmRelocationDebugStrTable: tdynamicarray;
  180. FWasmRelocationDebugStrTableEntriesCount: Integer;
  181. FWasmSymbolTable: tdynamicarray;
  182. FWasmSymbolTableEntriesCount: Integer;
  183. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  184. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  185. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  186. procedure WriteWasmSection(wsid: TWasmSectionID);
  187. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  188. function IsExternalFunction(sym: TObjSymbol): Boolean;
  189. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  190. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  191. procedure WriteSymbolTable;
  192. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  193. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  194. procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  195. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  196. procedure DoRelocations;
  197. procedure WriteRelocations;
  198. function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  199. protected
  200. function writeData(Data:TObjData):boolean;override;
  201. public
  202. constructor create(AWriter:TObjectWriter);override;
  203. destructor destroy;override;
  204. end;
  205. { TWasmObjInput }
  206. TWasmObjInput = class(TObjInput)
  207. private
  208. FFuncTypes: array of TWasmFuncType;
  209. public
  210. constructor create;override;
  211. destructor Destroy;override;
  212. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  213. function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
  214. end;
  215. { TWasmExeOutput }
  216. TWasmExeOutput = class(TExeOutput)
  217. private
  218. const
  219. DataSections: array [1..3] of string = (
  220. '.rodata',
  221. '.data',
  222. 'fpc.resources');
  223. WasmPageSize = 65536;
  224. type
  225. TCustomSectionNameMapEntry = record
  226. idx: UInt32;
  227. name: string;
  228. end;
  229. TCustomSectionNameMap = array of TCustomSectionNameMapEntry;
  230. private
  231. FImports: TFPHashObjectList;
  232. FFuncTypes: TWasmFuncTypeTable;
  233. FFunctionImports: array of record
  234. ModName: ansistring;
  235. Name: ansistring;
  236. TypeIdx: uint32;
  237. end;
  238. FTagImports: array of record
  239. end;
  240. FIndirectFunctionTable: array of record
  241. FuncIdx: Integer;
  242. end;
  243. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  244. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  245. FWasmNameSubsections: array [TWasmNameSubsectionType] of tdynamicarray;
  246. FStackPointerSym: TWasmObjSymbol;
  247. FTlsBaseSym: TWasmObjSymbol;
  248. FTlsSizeSym: TWasmObjSymbol;
  249. FTlsAlignSym: TWasmObjSymbol;
  250. FInitTlsFunctionSym: TWasmObjSymbol;
  251. FInitSharedMemoryFunctionSym: TWasmObjSymbol;
  252. FMinMemoryPages,
  253. FMaxMemoryPages: Integer;
  254. { use for the Name section }
  255. FFunctionNameMap: TCustomSectionNameMap;
  256. FGlobalNameMap: TCustomSectionNameMap;
  257. FDataNameMap: TCustomSectionNameMap;
  258. FTagNameMap: TCustomSectionNameMap;
  259. procedure AddToNameMap(var nm: TCustomSectionNameMap; aidx: UInt32; const aname: string);
  260. procedure AddToFunctionNameMap(aidx: UInt32; const aname: string);
  261. procedure AddToGlobalNameMap(aidx: UInt32; const aname: string);
  262. procedure AddToDataNameMap(aidx: UInt32; const aname: string);
  263. procedure AddToTagNameMap(aidx: UInt32; const aname: string);
  264. procedure WriteWasmSection(wsid: TWasmSectionID);
  265. procedure WriteWasmSectionIfNotEmpty(wsid: TWasmSectionID);
  266. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  267. procedure PrepareImports;
  268. procedure PrepareFunctions;
  269. procedure PrepareTags;
  270. function AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  271. procedure SetStackPointer;
  272. procedure SetTlsSizeAlignAndBase;
  273. procedure SetThreadVarGlobalsInitValues;
  274. procedure GenerateCode_InitTls;
  275. procedure GenerateCode_InitSharedMemory;
  276. procedure GenerateCode_InvokeHelper;
  277. procedure WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
  278. protected
  279. function writeData:boolean;override;
  280. procedure DoRelocationFixup(objsec:TObjSection);override;
  281. public
  282. constructor create;override;
  283. destructor destroy;override;
  284. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  285. procedure AfterUnusedSectionRemoval;override;
  286. procedure MemPos_ExeSection(const aname:string);override;
  287. procedure Load_Symbol(const aname: string);override;
  288. end;
  289. { TWasmAssembler }
  290. TWasmAssembler = class(tinternalassembler)
  291. constructor create(info: pasminfo; smart:boolean);override;
  292. end;
  293. implementation
  294. uses
  295. cutils,verbose,version,globals,fmodule,ogmap;
  296. const
  297. StackPointerSymStr='__stack_pointer';
  298. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  299. var
  300. b: byte;
  301. i: Integer;
  302. begin
  303. for i:=1 to 5 do
  304. begin
  305. b:=byte(v) and 127;
  306. v:=v shr 7;
  307. if i<>5 then
  308. b:=b or 128;
  309. d.write(b,1);
  310. end;
  311. end;
  312. procedure WriteUleb5(d: tobjsection; v: uint64);
  313. var
  314. b: byte;
  315. i: Integer;
  316. begin
  317. for i:=1 to 5 do
  318. begin
  319. b:=byte(v) and 127;
  320. v:=v shr 7;
  321. if i<>5 then
  322. b:=b or 128;
  323. d.write(b,1);
  324. end;
  325. end;
  326. procedure WriteSleb5(d: tdynamicarray; v: int64);
  327. var
  328. b: byte;
  329. i: Integer;
  330. begin
  331. for i:=1 to 5 do
  332. begin
  333. b:=byte(v) and 127;
  334. v:=SarInt64(v,7);
  335. if i<>5 then
  336. b:=b or 128;
  337. d.write(b,1);
  338. end;
  339. end;
  340. procedure WriteSleb5(d: tobjsection; v: int64);
  341. var
  342. b: byte;
  343. i: Integer;
  344. begin
  345. for i:=1 to 5 do
  346. begin
  347. b:=byte(v) and 127;
  348. v:=SarInt64(v,7);
  349. if i<>5 then
  350. b:=b or 128;
  351. d.write(b,1);
  352. end;
  353. end;
  354. procedure WriteUleb(d: tdynamicarray; v: uint64);
  355. var
  356. b: byte;
  357. begin
  358. repeat
  359. b:=byte(v) and 127;
  360. v:=v shr 7;
  361. if v<>0 then
  362. b:=b or 128;
  363. d.write(b,1);
  364. until v=0;
  365. end;
  366. procedure WriteUleb(d: tobjsection; v: uint64);
  367. var
  368. b: byte;
  369. begin
  370. repeat
  371. b:=byte(v) and 127;
  372. v:=v shr 7;
  373. if v<>0 then
  374. b:=b or 128;
  375. d.write(b,1);
  376. until v=0;
  377. end;
  378. procedure WriteUleb(w: TObjectWriter; v: uint64);
  379. var
  380. b: byte;
  381. begin
  382. repeat
  383. b:=byte(v) and 127;
  384. v:=v shr 7;
  385. if v<>0 then
  386. b:=b or 128;
  387. w.write(b,1);
  388. until v=0;
  389. end;
  390. procedure WriteSleb(d: tdynamicarray; v: int64);
  391. var
  392. b: byte;
  393. Done: Boolean=false;
  394. begin
  395. repeat
  396. b:=byte(v) and 127;
  397. v:=SarInt64(v,7);
  398. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  399. Done:=true
  400. else
  401. b:=b or 128;
  402. d.write(b,1);
  403. until Done;
  404. end;
  405. procedure WriteSleb(d: tobjsection; v: int64);
  406. var
  407. b: byte;
  408. Done: Boolean=false;
  409. begin
  410. repeat
  411. b:=byte(v) and 127;
  412. v:=SarInt64(v,7);
  413. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  414. Done:=true
  415. else
  416. b:=b or 128;
  417. d.write(b,1);
  418. until Done;
  419. end;
  420. function UlebEncodingSize(v: uint64): Integer;
  421. var
  422. b: byte;
  423. begin
  424. Result:=0;
  425. repeat
  426. b:=byte(v) and 127;
  427. v:=v shr 7;
  428. if v<>0 then
  429. b:=b or 128;
  430. Inc(Result);
  431. until v=0;
  432. end;
  433. {$ifdef FPC_LITTLE_ENDIAN}
  434. procedure WriteF32LE(d: tdynamicarray; v: Single);
  435. begin
  436. d.write(v,4);
  437. end;
  438. procedure WriteF64LE(d: tdynamicarray; v: Double);
  439. begin
  440. d.write(v,8);
  441. end;
  442. {$else FPC_LITTLE_ENDIAN}
  443. procedure WriteF32LE(d: tdynamicarray; v: Single);
  444. var
  445. tmpI: UInt32;
  446. begin
  447. Move(v,tmpI,4);
  448. tmpI:=SwapEndian(tmpI);
  449. d.write(tmpI,4);
  450. end;
  451. procedure WriteF64LE(d: tdynamicarray; v: Double);
  452. var
  453. tmpI: UInt64;
  454. begin
  455. Move(v,tmpI,8);
  456. tmpI:=SwapEndian(tmpI);
  457. d.write(tmpI,8);
  458. end;
  459. {$endif FPC_LITTLE_ENDIAN}
  460. procedure WriteByte(d: tdynamicarray; b: byte);
  461. begin
  462. d.write(b,1);
  463. end;
  464. procedure WriteName(d: tdynamicarray; const s: string);
  465. begin
  466. WriteUleb(d,Length(s));
  467. d.writestr(s);
  468. end;
  469. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  470. begin
  471. WriteByte(dest,encode_wasm_basic_type(wbt));
  472. end;
  473. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  474. var
  475. i: Integer;
  476. begin
  477. WriteUleb(dest,Length(wrt));
  478. for i:=low(wrt) to high(wrt) do
  479. WriteWasmBasicType(dest,wrt[i]);
  480. end;
  481. function ReadUleb(d: tdynamicarray): uint64;
  482. var
  483. b: byte;
  484. shift:integer;
  485. begin
  486. b:=0;
  487. result:=0;
  488. shift:=0;
  489. repeat
  490. d.read(b,1);
  491. result:=result or (uint64(b and 127) shl shift);
  492. inc(shift,7);
  493. until (b and 128)=0;
  494. end;
  495. function ReadSleb(d: tdynamicarray): int64;
  496. var
  497. b: byte;
  498. shift:integer;
  499. begin
  500. b:=0;
  501. result:=0;
  502. shift:=0;
  503. repeat
  504. d.read(b,1);
  505. result:=result or (uint64(b and 127) shl shift);
  506. inc(shift,7);
  507. until (b and 128)=0;
  508. {$ifopt Q+}
  509. {$define overflowon}
  510. {$Q-}
  511. {$endif}
  512. {$ifopt R+}
  513. {$define rangeon}
  514. {$R-}
  515. {$endif}
  516. if (b and 64)<>0 then
  517. result:=result or (high(uint64) shl shift);
  518. end;
  519. {$ifdef overflowon}
  520. {$Q+}
  521. {$undef overflowon}
  522. {$endif}
  523. {$ifdef rangeon}
  524. {$R+}
  525. {$undef rangeon}
  526. {$endif}
  527. procedure AddSleb5(d: tdynamicarray; v: int64);
  528. var
  529. q: Int64;
  530. p: LongWord;
  531. begin
  532. p:=d.Pos;
  533. q:=ReadSleb(d);
  534. q:=q+v;
  535. d.seek(p);
  536. WriteSleb5(d,q);
  537. end;
  538. procedure AddUleb5(d: tdynamicarray; v: int64);
  539. var
  540. q: UInt64;
  541. p: LongWord;
  542. begin
  543. p:=d.Pos;
  544. q:=ReadUleb(d);
  545. q:=q+v;
  546. d.seek(p);
  547. WriteUleb5(d,q);
  548. end;
  549. procedure AddInt32(d: tdynamicarray; v: int32);
  550. var
  551. q: int32;
  552. p: LongWord;
  553. begin
  554. p:=d.Pos;
  555. d.read(q,4);
  556. {$ifdef FPC_BIG_ENDIAN}
  557. q:=SwapEndian(q);
  558. {$endif FPC_BIG_ENDIAN}
  559. q:=q+v;
  560. {$ifdef FPC_BIG_ENDIAN}
  561. q:=SwapEndian(q);
  562. {$endif FPC_BIG_ENDIAN}
  563. d.seek(p);
  564. d.write(q,4);
  565. end;
  566. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  567. var
  568. buf: array [0..4095] of byte;
  569. bs: Integer;
  570. begin
  571. while size>0 do
  572. begin
  573. if size<SizeOf(buf) then
  574. bs:=Integer(size)
  575. else
  576. bs:=SizeOf(buf);
  577. src.read(buf,bs);
  578. dest.write(buf,bs);
  579. dec(size,bs);
  580. end;
  581. end;
  582. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  583. var
  584. buf : array[0..1023] of byte;
  585. bs: Integer;
  586. begin
  587. fillchar(buf,sizeof(buf),0);
  588. while size>0 do
  589. begin
  590. if size<SizeOf(buf) then
  591. bs:=Integer(size)
  592. else
  593. bs:=SizeOf(buf);
  594. dest.write(buf,bs);
  595. dec(size,bs);
  596. end;
  597. end;
  598. {****************************************************************************
  599. TWasmObjSymbolLinkingData
  600. ****************************************************************************}
  601. constructor TWasmObjSymbolLinkingData.Create;
  602. begin
  603. ExeFunctionIndex:=-1;
  604. ExeIndirectFunctionTableIndex:=-1;
  605. ExeTypeIndex:=-1;
  606. ExeTagIndex:=-1;
  607. end;
  608. destructor TWasmObjSymbolLinkingData.Destroy;
  609. begin
  610. FuncType.Free;
  611. inherited Destroy;
  612. end;
  613. {****************************************************************************
  614. TWasmObjRelocation
  615. ****************************************************************************}
  616. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  617. begin
  618. DataOffset:=ADataOffset;
  619. Symbol:=nil;
  620. OrgSize:=0;
  621. Group:=nil;
  622. ObjSection:=nil;
  623. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  624. TypeIndex:=ATypeIndex;
  625. FuncType:=nil;
  626. ExeTypeIndex:=-1;
  627. end;
  628. constructor TWasmObjRelocation.CreateFuncType(ADataOffset: TObjSectionOfs; AFuncType: TWasmFuncType);
  629. begin
  630. DataOffset:=ADataOffset;
  631. Symbol:=nil;
  632. OrgSize:=0;
  633. Group:=nil;
  634. ObjSection:=nil;
  635. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  636. TypeIndex:=-1;
  637. ExeTypeIndex:=-1;
  638. FuncType:=TWasmFuncType.Create(AFuncType);
  639. end;
  640. destructor TWasmObjRelocation.Destroy;
  641. begin
  642. FuncType.Free;
  643. inherited Destroy;
  644. end;
  645. {****************************************************************************
  646. TWasmObjSymbol
  647. ****************************************************************************}
  648. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  649. begin
  650. inherited create(AList,AName);
  651. FuncIndex:=-1;
  652. SymbolIndex:=-1;
  653. GlobalIndex:=-1;
  654. TagIndex:=-1;
  655. AliasOf:='';
  656. ExtraData:=nil;
  657. LinkingData:=TWasmObjSymbolLinkingData.Create;
  658. end;
  659. destructor TWasmObjSymbol.Destroy;
  660. begin
  661. LinkingData.Free;
  662. inherited Destroy;
  663. end;
  664. function TWasmObjSymbol.IsAlias: Boolean;
  665. begin
  666. result:=AliasOf<>'';
  667. end;
  668. {****************************************************************************
  669. TWasmObjSymbolExtraData
  670. ****************************************************************************}
  671. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  672. begin
  673. EncodedLocals:=nil;
  674. inherited Create(HashObjectList,s);
  675. TypeIdx:=-1;
  676. ExceptionTagTypeIdx:=-1;
  677. end;
  678. destructor TWasmObjSymbolExtraData.Destroy;
  679. begin
  680. EncodedLocals.Free;
  681. inherited Destroy;
  682. end;
  683. procedure TWasmObjSymbolExtraData.AddLocals(alocals: TWasmLocalsDynArray);
  684. var
  685. i,
  686. rle_entries,
  687. cnt: Integer;
  688. lasttype: TWasmBasicType;
  689. begin
  690. Locals:=alocals;
  691. if Assigned(EncodedLocals) then
  692. internalerror(2024081502);
  693. EncodedLocals:=tdynamicarray.Create(64);
  694. if Length(Locals)=0 then
  695. begin
  696. WriteUleb(EncodedLocals,0);
  697. exit;
  698. end;
  699. rle_entries:=1;
  700. for i:=low(Locals)+1 to high(Locals) do
  701. if Locals[i]<>Locals[i-1] then
  702. inc(rle_entries);
  703. WriteUleb(EncodedLocals,rle_entries);
  704. lasttype:=Locals[Low(Locals)];
  705. cnt:=1;
  706. for i:=low(Locals)+1 to high(Locals) do
  707. if Locals[i]=Locals[i-1] then
  708. inc(cnt)
  709. else
  710. begin
  711. WriteUleb(EncodedLocals,cnt);
  712. WriteWasmBasicType(EncodedLocals,lasttype);
  713. lasttype:=Locals[i];
  714. cnt:=1;
  715. end;
  716. WriteUleb(EncodedLocals,cnt);
  717. WriteWasmBasicType(EncodedLocals,lasttype);
  718. end;
  719. {****************************************************************************
  720. TWasmObjSection
  721. ****************************************************************************}
  722. constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  723. begin
  724. inherited create(AList, Aname, Aalign, Aoptions);
  725. SegIdx:=-1;
  726. SegSymIdx:=-1;
  727. CustomSectionIdx:=-1;
  728. MainFuncSymbol:=nil;
  729. end;
  730. function TWasmObjSection.IsCode: Boolean;
  731. const
  732. CodePrefix = '.text';
  733. begin
  734. result:=(Length(Name)>=Length(CodePrefix)) and
  735. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  736. end;
  737. function TWasmObjSection.IsData: Boolean;
  738. begin
  739. result:=not (IsCode or IsDebug);
  740. end;
  741. function TWasmObjSection.IsDebug: Boolean;
  742. const
  743. DebugPrefix = '.debug';
  744. begin
  745. result:=(Length(Name)>=Length(DebugPrefix)) and
  746. (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
  747. end;
  748. {****************************************************************************
  749. TWasmFuncTypeTable
  750. ****************************************************************************}
  751. function TWasmFuncTypeTable.GetCount: Integer;
  752. begin
  753. Result:=Length(FFuncTypes);
  754. end;
  755. function TWasmFuncTypeTable.GetItem(Index: Integer): TWasmFuncType;
  756. begin
  757. if (Index<Low(FFuncTypes)) or (Index>High(FFuncTypes)) then
  758. internalerror(2023123101);
  759. Result:=FFuncTypes[Index];
  760. end;
  761. destructor TWasmFuncTypeTable.Destroy;
  762. var
  763. i: Integer;
  764. begin
  765. for i:=low(FFuncTypes) to high(FFuncTypes) do
  766. begin
  767. FFuncTypes[i].free;
  768. FFuncTypes[i]:=nil;
  769. end;
  770. end;
  771. function TWasmFuncTypeTable.AddOrGetFuncType(wft: TWasmFuncType): integer;
  772. var
  773. i: Integer;
  774. begin
  775. for i:=low(FFuncTypes) to high(FFuncTypes) do
  776. if wft.Equals(FFuncTypes[i]) then
  777. exit(i);
  778. result:=Length(FFuncTypes);
  779. SetLength(FFuncTypes,result+1);
  780. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  781. end;
  782. procedure TWasmFuncTypeTable.WriteTo(d: tdynamicarray);
  783. var
  784. types_count, i: Integer;
  785. begin
  786. types_count:=Count;
  787. WriteUleb(d,types_count);
  788. for i:=0 to types_count-1 do
  789. with Items[i] do
  790. begin
  791. WriteByte(d,$60);
  792. WriteWasmResultType(d,params);
  793. WriteWasmResultType(d,results);
  794. end;
  795. end;
  796. {****************************************************************************
  797. TWasmObjData
  798. ****************************************************************************}
  799. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  800. begin
  801. { For bss we need to set some flags that are target dependent,
  802. it is easier to disable it for smartlinking. It doesn't take up
  803. filespace }
  804. result:=not(target_info.system in systems_darwin) and
  805. create_smartlink_sections and
  806. (atype<>sec_toc) and
  807. (atype<>sec_user) and
  808. { on embedded systems every byte counts, so smartlink bss too }
  809. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  810. end;
  811. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  812. const aname: string; aorder: TAsmSectionOrder): string;
  813. const
  814. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  815. '.text',
  816. '.data',
  817. { why doesn't .rodata work? (FK) }
  818. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  819. { vtables (and anything else containing relocations), otherwise those are }
  820. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  821. { vtable for a class called Window: }
  822. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  823. { TODO: .data.ro not yet working}
  824. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  825. '.rodata',
  826. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  827. '.data',
  828. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  829. '.rodata',
  830. '.bss',
  831. '.tbss',
  832. '.pdata',
  833. '', { stubs }
  834. '__DATA,__nl_symbol_ptr',
  835. '__DATA,__la_symbol_ptr',
  836. '__DATA,__mod_init_func',
  837. '__DATA,__mod_term_func',
  838. '.stab',
  839. '.stabstr',
  840. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  841. '.eh_frame',
  842. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges','.debug_loc','.debug_loclists',
  843. '.fpc',
  844. '.toc',
  845. '.init',
  846. '.fini',
  847. '.objc_class',
  848. '.objc_meta_class',
  849. '.objc_cat_cls_meth',
  850. '.objc_cat_inst_meth',
  851. '.objc_protocol',
  852. '.objc_string_object',
  853. '.objc_cls_meth',
  854. '.objc_inst_meth',
  855. '.objc_cls_refs',
  856. '.objc_message_refs',
  857. '.objc_symbols',
  858. '.objc_category',
  859. '.objc_class_vars',
  860. '.objc_instance_vars',
  861. '.objc_module_info',
  862. '.objc_class_names',
  863. '.objc_meth_var_types',
  864. '.objc_meth_var_names',
  865. '.objc_selector_strs',
  866. '.objc_protocol_ext',
  867. '.objc_class_ext',
  868. '.objc_property',
  869. '.objc_image_info',
  870. '.objc_cstring_object',
  871. '.objc_sel_fixup',
  872. '__DATA,__objc_data',
  873. '__DATA,__objc_const',
  874. '.objc_superrefs',
  875. '__DATA, __datacoal_nt,coalesced',
  876. '.objc_classlist',
  877. '.objc_nlclasslist',
  878. '.objc_catlist',
  879. '.obcj_nlcatlist',
  880. '.objc_protolist',
  881. '.stack',
  882. '.heap',
  883. '.gcc_except_table',
  884. '.ARM.attributes'
  885. );
  886. var
  887. sep : string[3];
  888. secname : string;
  889. begin
  890. secname:=secnames[atype];
  891. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  892. begin
  893. result:=secname+'.'+aname;
  894. exit;
  895. end;
  896. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  897. Thus, data which normally goes into .rodata and .rodata_norel sections must
  898. end up in .data section }
  899. if (atype in [sec_rodata,sec_rodata_norel]) and
  900. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  901. secname:='.data';
  902. { Windows correctly handles reallocations in readonly sections }
  903. if (atype=sec_rodata) and
  904. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  905. secname:='.rodata';
  906. { section type user gives the user full controll on the section name }
  907. if atype=sec_user then
  908. secname:=aname;
  909. if is_smart_section(atype) and (aname<>'') then
  910. begin
  911. case aorder of
  912. secorder_begin :
  913. sep:='.b_';
  914. secorder_end :
  915. sep:='.z_';
  916. else
  917. sep:='.n_';
  918. end;
  919. result:=secname+sep+aname
  920. end
  921. else
  922. result:=secname;
  923. end;
  924. constructor TWasmObjData.create(const n: string);
  925. begin
  926. inherited;
  927. CObjSection:=TWasmObjSection;
  928. CObjSymbol:=TWasmObjSymbol;
  929. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  930. FFuncTypes:=TWasmFuncTypeTable.Create;
  931. end;
  932. destructor TWasmObjData.destroy;
  933. var
  934. i: Integer;
  935. begin
  936. FObjSymbolsExtraDataList.Free;
  937. FFuncTypes.Free;
  938. inherited destroy;
  939. end;
  940. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  941. const aname: string; aorder: TAsmSectionOrder): string;
  942. begin
  943. if (atype=sec_fpc) or
  944. ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
  945. atype:=sec_data;
  946. Result:=sectionname_gas(atype, aname, aorder);
  947. end;
  948. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  949. p: TObjSymbol; Reloctype: TObjRelocationType);
  950. const
  951. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  952. var
  953. objreloc: TWasmObjRelocation;
  954. begin
  955. if CurrObjSec=nil then
  956. internalerror(200403072);
  957. { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
  958. todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
  959. if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
  960. Reloctype:=RELOC_ABSOLUTE;
  961. objreloc:=nil;
  962. case Reloctype of
  963. RELOC_FUNCTION_INDEX_LEB:
  964. begin
  965. if Data<>0 then
  966. internalerror(2021092502);
  967. if len<>5 then
  968. internalerror(2021092503);
  969. if not assigned(p) then
  970. internalerror(2021092504);
  971. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  972. CurrObjSec.ObjRelocations.Add(objreloc);
  973. writebytes(leb_zero,5);
  974. end;
  975. RELOC_MEMORY_ADDR_LEB,
  976. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  977. begin
  978. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  979. internalerror(2021092602);
  980. if len<>5 then
  981. internalerror(2021092503);
  982. if not assigned(p) then
  983. internalerror(2021092504);
  984. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  985. objreloc.Addend:=Data;
  986. CurrObjSec.ObjRelocations.Add(objreloc);
  987. if RelocType=RELOC_MEMORY_ADDR_LEB then
  988. WriteUleb5(CurrObjSec,Data)
  989. else
  990. WriteSleb5(CurrObjSec,Data);
  991. end;
  992. RELOC_ABSOLUTE:
  993. begin
  994. if len<>4 then
  995. internalerror(2021092607);
  996. if not assigned(p) then
  997. internalerror(2021092608);
  998. if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
  999. (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
  1000. begin
  1001. objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
  1002. objreloc.Addend:=Data+p.Address;
  1003. CurrObjSec.ObjRelocations.Add(objreloc);
  1004. {inc(data,p.address);}
  1005. data:=0;
  1006. Data:=NtoLE(Data);
  1007. writebytes(Data,4);
  1008. end
  1009. else
  1010. begin
  1011. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  1012. objreloc.Addend:=Data;
  1013. CurrObjSec.ObjRelocations.Add(objreloc);
  1014. Data:=NtoLE(Data);
  1015. writebytes(Data,4);
  1016. end;
  1017. end;
  1018. RELOC_TYPE_INDEX_LEB:
  1019. begin
  1020. if len<>5 then
  1021. internalerror(2021092612);
  1022. if assigned(p) then
  1023. internalerror(2021092613);
  1024. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  1025. CurrObjSec.ObjRelocations.Add(objreloc);
  1026. WriteUleb5(CurrObjSec,Data);
  1027. end;
  1028. RELOC_GLOBAL_INDEX_LEB:
  1029. begin
  1030. if len<>5 then
  1031. internalerror(2021092701);
  1032. if Data<>0 then
  1033. internalerror(2021092702);
  1034. if not assigned(p) then
  1035. internalerror(2021092703);
  1036. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  1037. CurrObjSec.ObjRelocations.Add(objreloc);
  1038. WriteUleb5(CurrObjSec,0);
  1039. end;
  1040. RELOC_TAG_INDEX_LEB:
  1041. begin
  1042. if len<>5 then
  1043. internalerror(2021092712);
  1044. if Data<>0 then
  1045. internalerror(2021092713);
  1046. if not assigned(p) then
  1047. internalerror(2021092714);
  1048. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  1049. CurrObjSec.ObjRelocations.Add(objreloc);
  1050. WriteSleb5(CurrObjSec,0);
  1051. end;
  1052. else
  1053. internalerror(2021092501);
  1054. end;
  1055. end;
  1056. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  1057. begin
  1058. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  1059. if not assigned(result) then
  1060. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  1061. end;
  1062. function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
  1063. begin
  1064. if assigned(asmsym) then
  1065. begin
  1066. if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
  1067. internalerror(2021092706);
  1068. result:=symbolref(asmsym);
  1069. result.typ:=asmsym.typ;
  1070. end
  1071. else
  1072. result:=nil;
  1073. end;
  1074. function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
  1075. begin
  1076. if assigned(asmsym) then
  1077. begin
  1078. if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
  1079. internalerror(2021092707);
  1080. result:=symbolref(asmsym);
  1081. result.typ:=AT_WASM_EXCEPTION_TAG;
  1082. end
  1083. else
  1084. result:=nil;
  1085. end;
  1086. procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
  1087. var
  1088. ObjSymExtraData: TWasmObjSymbolExtraData;
  1089. ObjSym: TObjSymbol;
  1090. begin
  1091. if not gt.is_external then
  1092. begin
  1093. ObjSym:=symboldefine(gt.sym);
  1094. ObjSym.typ:=AT_WASM_GLOBAL;
  1095. end;
  1096. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
  1097. ObjSymExtraData.GlobalType:=gt.gtype;
  1098. ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
  1099. end;
  1100. procedure TWasmObjData.DeclareFuncType_Pass0(ft: tai_functype);
  1101. var
  1102. i: Integer;
  1103. ObjSymExtraData: TWasmObjSymbolExtraData;
  1104. begin
  1105. FLastFuncName:=ft.funcname;
  1106. i:=FFuncTypes.AddOrGetFuncType(ft.functype);
  1107. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  1108. ObjSymExtraData.TypeIdx:=i;
  1109. end;
  1110. procedure TWasmObjData.DeclareFuncType_Pass1(ft: tai_functype);
  1111. begin
  1112. FLastFuncName:=ft.funcname;
  1113. end;
  1114. procedure TWasmObjData.DeclareFuncType_Pass2(ft: tai_functype);
  1115. begin
  1116. FLastFuncName:=ft.funcname;
  1117. end;
  1118. procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
  1119. var
  1120. ObjSymExtraData: TWasmObjSymbolExtraData;
  1121. ft: TWasmFuncType;
  1122. i: Integer;
  1123. begin
  1124. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
  1125. ft:=TWasmFuncType.Create([],tt.params);
  1126. i:=FFuncTypes.AddOrGetFuncType(ft);
  1127. ft.free;
  1128. ObjSymExtraData.ExceptionTagTypeIdx:=i;
  1129. end;
  1130. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  1131. var
  1132. ObjSymExtraData: TWasmObjSymbolExtraData;
  1133. begin
  1134. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  1135. ObjSymExtraData.ExportName:=en.extname;
  1136. end;
  1137. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  1138. var
  1139. ObjSymExtraData: TWasmObjSymbolExtraData;
  1140. begin
  1141. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  1142. ObjSymExtraData.ImportModule:=aim.importmodule;
  1143. end;
  1144. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  1145. var
  1146. ObjSymExtraData: TWasmObjSymbolExtraData;
  1147. begin
  1148. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  1149. ObjSymExtraData.ImportName:=ain.importname;
  1150. end;
  1151. procedure TWasmObjData.DeclareLocals_Pass0(al: tai_local);
  1152. var
  1153. ObjSymExtraData: TWasmObjSymbolExtraData;
  1154. begin
  1155. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  1156. ObjSymExtraData.AddLocals(al.locals);
  1157. alloc(ObjSymExtraData.EncodedLocals.size);
  1158. end;
  1159. procedure TWasmObjData.DeclareLocals_Pass1(al: tai_local);
  1160. var
  1161. ObjSymExtraData: TWasmObjSymbolExtraData;
  1162. begin
  1163. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  1164. alloc(ObjSymExtraData.EncodedLocals.size);
  1165. end;
  1166. procedure TWasmObjData.WriteLocals_Pass2(al: tai_local);
  1167. var
  1168. ObjSymExtraData: TWasmObjSymbolExtraData;
  1169. d: tdynamicarray;
  1170. buf: array [0..4095] of byte;
  1171. bs,size: Integer;
  1172. begin
  1173. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  1174. d:=ObjSymExtraData.EncodedLocals;
  1175. d.seek(0);
  1176. size:=d.size;
  1177. while size>0 do
  1178. begin
  1179. if size<SizeOf(buf) then
  1180. bs:=Integer(size)
  1181. else
  1182. bs:=SizeOf(buf);
  1183. d.read(buf,bs);
  1184. writebytes(buf,bs);
  1185. dec(size,bs);
  1186. end;
  1187. end;
  1188. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  1189. var
  1190. valsym: TObjSymbol;
  1191. aliassym: TWasmObjSymbol;
  1192. begin
  1193. valsym:=CreateSymbol(avalue);
  1194. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  1195. aliassym.AliasOf:=valsym.Name;
  1196. end;
  1197. {****************************************************************************
  1198. TWasmObjOutput
  1199. ****************************************************************************}
  1200. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  1201. var
  1202. b: byte;
  1203. begin
  1204. b:=ord(wsid);
  1205. Writer.write(b,1);
  1206. WriteUleb(Writer,FWasmSections[wsid].size);
  1207. Writer.writearray(FWasmSections[wsid]);
  1208. end;
  1209. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  1210. var
  1211. b: byte;
  1212. begin
  1213. b:=0;
  1214. Writer.write(b,1);
  1215. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  1216. Writer.writearray(FWasmCustomSections[wcst]);
  1217. end;
  1218. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  1219. var
  1220. ExtraData: TWasmObjSymbolExtraData;
  1221. begin
  1222. if sym.bind=AB_EXTERNAL then
  1223. begin
  1224. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  1225. result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
  1226. end
  1227. else
  1228. result:=false;
  1229. end;
  1230. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  1231. var
  1232. ExtraData: TWasmObjSymbolExtraData;
  1233. begin
  1234. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  1235. begin
  1236. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  1237. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  1238. end
  1239. else
  1240. result:=false;
  1241. end;
  1242. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  1243. var
  1244. ObjSymExtraData: TWasmObjSymbolExtraData;
  1245. ObjSection: TWasmObjSection;
  1246. codelen: QWord;
  1247. begin
  1248. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1249. ObjSection:=TWasmObjSection(objsym.objsection);
  1250. ObjSection.Data.seek(objsym.address);
  1251. codelen:=objsym.size;
  1252. WriteUleb(dest,codelen);
  1253. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  1254. CopyDynamicArray(ObjSection.Data,dest,codelen);
  1255. end;
  1256. procedure TWasmObjOutput.WriteSymbolTable;
  1257. begin
  1258. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  1259. FWasmSymbolTable.seek(0);
  1260. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  1261. end;
  1262. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  1263. begin
  1264. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  1265. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  1266. FWasmRelocationCodeTable.seek(0);
  1267. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  1268. end;
  1269. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  1270. begin
  1271. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  1272. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  1273. FWasmRelocationDataTable.seek(0);
  1274. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  1275. end;
  1276. procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  1277. begin
  1278. if EntriesCount>0 then
  1279. begin
  1280. WriteUleb(FWasmCustomSections[cst],SectionIndex);
  1281. WriteUleb(FWasmCustomSections[cst],EntriesCount);
  1282. Table.seek(0);
  1283. CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
  1284. WriteWasmCustomSection(cst);
  1285. end;
  1286. end;
  1287. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  1288. begin
  1289. if FWasmLinkingSubsections[wlst].size>0 then
  1290. begin
  1291. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  1292. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1293. FWasmLinkingSubsections[wlst].seek(0);
  1294. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1295. end;
  1296. end;
  1297. procedure TWasmObjOutput.DoRelocations;
  1298. var
  1299. si, ri: Integer;
  1300. objsec: TWasmObjSection;
  1301. objrel: TWasmObjRelocation;
  1302. begin
  1303. for si:=0 to FData.ObjSectionList.Count-1 do
  1304. begin
  1305. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1306. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1307. begin
  1308. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1309. case objrel.typ of
  1310. RELOC_FUNCTION_INDEX_LEB:
  1311. begin
  1312. if not assigned(objrel.symbol) then
  1313. internalerror(2021092509);
  1314. objsec.Data.seek(objrel.DataOffset);
  1315. if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
  1316. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1317. else
  1318. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
  1319. end;
  1320. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1321. begin
  1322. if not assigned(objrel.symbol) then
  1323. internalerror(2021092605);
  1324. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1325. begin
  1326. objsec.Data.seek(objrel.DataOffset);
  1327. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1328. end;
  1329. end;
  1330. RELOC_MEMORY_ADDR_LEB:
  1331. begin
  1332. if not assigned(objrel.symbol) then
  1333. internalerror(2021092606);
  1334. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1335. internalerror(2021092628);
  1336. if objrel.symbol.bind<>AB_EXTERNAL then
  1337. begin
  1338. objsec.Data.seek(objrel.DataOffset);
  1339. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1340. end;
  1341. end;
  1342. RELOC_ABSOLUTE:
  1343. begin
  1344. if assigned(objrel.ObjSection) then
  1345. begin
  1346. { todo: should we do something here? }
  1347. //Writeln('todo: section relocation');
  1348. end
  1349. else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1350. begin
  1351. objsec.Data.seek(objrel.DataOffset);
  1352. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1353. end;
  1354. end;
  1355. RELOC_TYPE_INDEX_LEB:
  1356. ;
  1357. RELOC_GLOBAL_INDEX_LEB:
  1358. begin
  1359. if not assigned(objrel.symbol) then
  1360. internalerror(2021092509);
  1361. objsec.Data.seek(objrel.DataOffset);
  1362. if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
  1363. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1364. else
  1365. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
  1366. end;
  1367. RELOC_TAG_INDEX_LEB:
  1368. begin
  1369. if not assigned(objrel.symbol) then
  1370. internalerror(2021092716);
  1371. objsec.Data.seek(objrel.DataOffset);
  1372. if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
  1373. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1374. else
  1375. WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
  1376. end;
  1377. else
  1378. internalerror(2021092510);
  1379. end;
  1380. end;
  1381. end;
  1382. end;
  1383. procedure TWasmObjOutput.WriteRelocations;
  1384. var
  1385. si, ri: Integer;
  1386. objsec: TWasmObjSection;
  1387. objrel: TWasmObjRelocation;
  1388. relout: tdynamicarray;
  1389. relcount: PInteger;
  1390. FuncSym: TWasmObjSymbol;
  1391. begin
  1392. for si:=0 to FData.ObjSectionList.Count-1 do
  1393. begin
  1394. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1395. if objsec.IsCode then
  1396. begin
  1397. relout:=FWasmRelocationCodeTable;
  1398. relcount:=@FWasmRelocationCodeTableEntriesCount;
  1399. end
  1400. else if objsec.IsData then
  1401. begin
  1402. relout:=FWasmRelocationDataTable;
  1403. relcount:=@FWasmRelocationDataTableEntriesCount;
  1404. end
  1405. else if objsec.IsDebug then
  1406. begin
  1407. case objsec.Name of
  1408. '.debug_frame':
  1409. begin
  1410. relout:=FWasmRelocationDebugFrameTable;
  1411. relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
  1412. end;
  1413. '.debug_info':
  1414. begin
  1415. relout:=FWasmRelocationDebugInfoTable;
  1416. relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
  1417. end;
  1418. '.debug_line':
  1419. begin
  1420. relout:=FWasmRelocationDebugLineTable;
  1421. relcount:=@FWasmRelocationDebugLineTableEntriesCount;
  1422. end;
  1423. '.debug_abbrev':
  1424. begin
  1425. relout:=FWasmRelocationDebugAbbrevTable;
  1426. relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
  1427. end;
  1428. '.debug_aranges':
  1429. begin
  1430. relout:=FWasmRelocationDebugArangesTable;
  1431. relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
  1432. end;
  1433. '.debug_ranges':
  1434. begin
  1435. relout:=FWasmRelocationDebugRangesTable;
  1436. relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
  1437. end;
  1438. '.debug_str':
  1439. begin
  1440. relout:=FWasmRelocationDebugStrTable;
  1441. relcount:=@FWasmRelocationDebugStrTableEntriesCount;
  1442. end;
  1443. else
  1444. internalerror(2022071601);
  1445. end;
  1446. end
  1447. else
  1448. continue;
  1449. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1450. begin
  1451. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1452. case objrel.typ of
  1453. RELOC_FUNCTION_INDEX_LEB:
  1454. begin
  1455. if not assigned(objrel.symbol) then
  1456. internalerror(2021092508);
  1457. Inc(relcount^);
  1458. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  1459. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1460. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1461. end;
  1462. RELOC_MEMORY_ADDR_LEB:
  1463. begin
  1464. if not assigned(objrel.symbol) then
  1465. internalerror(2021092603);
  1466. Inc(relcount^);
  1467. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1468. internalerror(2021092628);
  1469. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  1470. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1471. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1472. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1473. end;
  1474. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1475. begin
  1476. if not assigned(objrel.symbol) then
  1477. internalerror(2021092604);
  1478. Inc(relcount^);
  1479. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1480. begin
  1481. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  1482. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1483. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1484. end
  1485. else
  1486. begin
  1487. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  1488. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1489. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1490. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1491. end;
  1492. end;
  1493. RELOC_ABSOLUTE:
  1494. begin
  1495. // todo: figure this out, why do these exist?
  1496. //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
  1497. // Writeln('!!! ', objrel.symbol.name);
  1498. if assigned(objrel.objsection) then
  1499. begin
  1500. Inc(relcount^);
  1501. WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
  1502. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1503. if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
  1504. message1(asmw_e_illegal_unset_index,objrel.objsection.name)
  1505. else
  1506. WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
  1507. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1508. end
  1509. else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
  1510. begin
  1511. Inc(relcount^);
  1512. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  1513. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1514. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1515. end
  1516. else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
  1517. begin
  1518. Inc(relcount^);
  1519. WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
  1520. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1521. FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
  1522. if FuncSym.SymbolIndex<0 then
  1523. message1(asmw_e_illegal_unset_index,FuncSym.Name)
  1524. else
  1525. WriteUleb(relout,FuncSym.SymbolIndex);
  1526. WriteSleb(relout,objrel.Addend+objrel.symbol.address) { addend to add to the address }
  1527. end
  1528. else if assigned(objrel.symbol) and (objrel.symbol.typ=AT_WASM_GLOBAL) then
  1529. begin
  1530. Inc(relcount^);
  1531. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_I32));
  1532. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1533. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1534. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1535. else
  1536. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1537. end
  1538. else
  1539. begin
  1540. Inc(relcount^);
  1541. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1542. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1543. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1544. begin
  1545. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1546. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1547. end
  1548. else
  1549. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1550. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1551. end;
  1552. end;
  1553. RELOC_TYPE_INDEX_LEB:
  1554. begin
  1555. Inc(relcount^);
  1556. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1557. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1558. WriteUleb(relout,objrel.TypeIndex);
  1559. end;
  1560. RELOC_GLOBAL_INDEX_LEB:
  1561. begin
  1562. if not assigned(objrel.symbol) then
  1563. internalerror(2021092704);
  1564. Inc(relcount^);
  1565. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1566. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1567. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1568. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1569. else
  1570. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1571. end;
  1572. RELOC_TAG_INDEX_LEB:
  1573. begin
  1574. if not assigned(objrel.symbol) then
  1575. internalerror(2021092717);
  1576. Inc(relcount^);
  1577. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1578. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1579. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1580. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1581. else
  1582. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1583. end;
  1584. else
  1585. internalerror(2021092507);
  1586. end;
  1587. end;
  1588. end;
  1589. end;
  1590. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1591. begin
  1592. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1593. end;
  1594. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1595. var
  1596. section_nr: Integer;
  1597. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1598. var
  1599. objsec: TWasmObjSection;
  1600. begin
  1601. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1602. if Assigned(objsec) then
  1603. begin
  1604. debug_section_nr:=section_nr;
  1605. Inc(section_nr);
  1606. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1607. objsec.CustomSectionIdx:=debug_section_nr;
  1608. Inc(FWasmSymbolTableEntriesCount);
  1609. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1610. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1611. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1612. end;
  1613. end;
  1614. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1615. var
  1616. objsec: TWasmObjSection;
  1617. begin
  1618. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1619. if Assigned(objsec) then
  1620. begin
  1621. if oso_Data in objsec.SecOptions then
  1622. begin
  1623. objsec.Data.seek(0);
  1624. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1625. end
  1626. else
  1627. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1628. WriteWasmCustomSection(st);
  1629. end;
  1630. end;
  1631. var
  1632. i: Integer;
  1633. objsec: TWasmObjSection;
  1634. segment_count: Integer = 0;
  1635. cur_seg_ofs: qword = 0;
  1636. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1637. code_section_nr, data_section_nr,
  1638. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1639. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1640. debug_ranges_section_nr,
  1641. NextGlobalIndex, NextTagIndex: Integer;
  1642. import_globals_count: Integer = 0;
  1643. globals_count: Integer = 0;
  1644. import_functions_count: Integer = 0;
  1645. export_functions_count: Integer = 0;
  1646. functions_count: Integer = 0;
  1647. import_exception_tags_count: Integer = 0;
  1648. exception_tags_count: Integer = 0;
  1649. objsym, ObjSymAlias: TWasmObjSymbol;
  1650. cust_sec: TWasmCustomSectionType;
  1651. SegmentFlags, SymbolFlags: UInt64;
  1652. begin
  1653. FData:=TWasmObjData(Data);
  1654. { each custom sections starts with its name }
  1655. for cust_sec in TWasmCustomSectionType do
  1656. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1657. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1658. for i:=0 to Data.ObjSymbolList.Count-1 do
  1659. begin
  1660. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1661. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1662. if objsym.bind=AB_EXTERNAL then
  1663. Inc(import_exception_tags_count)
  1664. else
  1665. Inc(exception_tags_count);
  1666. if objsym.typ=AT_WASM_GLOBAL then
  1667. if objsym.bind=AB_EXTERNAL then
  1668. Inc(import_globals_count)
  1669. else
  1670. Inc(globals_count);
  1671. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1672. Inc(import_globals_count);
  1673. if IsExternalFunction(objsym) then
  1674. Inc(import_functions_count);
  1675. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1676. begin
  1677. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1678. Inc(functions_count);
  1679. end;
  1680. if IsExportedFunction(objsym) then
  1681. Inc(export_functions_count);
  1682. end;
  1683. FData.FFuncTypes.WriteTo(FWasmSections[wsiType]);
  1684. for i:=0 to Data.ObjSectionList.Count-1 do
  1685. begin
  1686. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1687. if objsec.IsCode then
  1688. objsec.SegIdx:=-1
  1689. else if objsec.IsData then
  1690. begin
  1691. objsec.SegIdx:=segment_count;
  1692. objsec.SegOfs:=cur_seg_ofs;
  1693. Inc(segment_count);
  1694. Inc(cur_seg_ofs,objsec.Size);
  1695. end;
  1696. end;
  1697. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1698. WriteUleb(FWasmSections[wsiImport],imports_count);
  1699. { import memories }
  1700. WriteName(FWasmSections[wsiImport],'env');
  1701. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1702. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1703. WriteByte(FWasmSections[wsiImport],$00); { min }
  1704. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1705. { import globals }
  1706. NextGlobalIndex:=0;
  1707. for i:=0 to Data.ObjSymbolList.Count-1 do
  1708. begin
  1709. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1710. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1711. begin
  1712. objsym.GlobalIndex:=NextGlobalIndex;
  1713. Inc(NextGlobalIndex);
  1714. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1715. if objsym.ExtraData.ImportModule<>'' then
  1716. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1717. else
  1718. WriteName(FWasmSections[wsiImport],'env');
  1719. WriteName(FWasmSections[wsiImport],objsym.Name);
  1720. WriteByte(FWasmSections[wsiImport],$03); { global }
  1721. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1722. if objsym.ExtraData.GlobalIsImmutable then
  1723. WriteByte(FWasmSections[wsiImport],$00) { const }
  1724. else
  1725. WriteByte(FWasmSections[wsiImport],$01); { var }
  1726. end
  1727. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1728. begin
  1729. objsym.GlobalIndex:=NextGlobalIndex;
  1730. Inc(NextGlobalIndex);
  1731. objsym.ExtraData:=nil;
  1732. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1733. WriteName(FWasmSections[wsiImport],objsym.Name);
  1734. WriteByte(FWasmSections[wsiImport],$03); { global }
  1735. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1736. WriteByte(FWasmSections[wsiImport],$01); { var }
  1737. end;
  1738. end;
  1739. { import functions }
  1740. NextImportFunctionIndex:=0;
  1741. for i:=0 to Data.ObjSymbolList.Count-1 do
  1742. begin
  1743. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1744. if IsExternalFunction(objsym) then
  1745. begin
  1746. objsym.FuncIndex:=NextImportFunctionIndex;
  1747. Inc(NextImportFunctionIndex);
  1748. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1749. if objsym.ExtraData.ImportModule<>'' then
  1750. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1751. else
  1752. WriteName(FWasmSections[wsiImport],'env');
  1753. WriteName(FWasmSections[wsiImport],objsym.Name);
  1754. WriteByte(FWasmSections[wsiImport],$00); { func }
  1755. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1756. end;
  1757. end;
  1758. { import tables }
  1759. WriteName(FWasmSections[wsiImport],'env');
  1760. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1761. WriteByte(FWasmSections[wsiImport],$01); { table }
  1762. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1763. WriteByte(FWasmSections[wsiImport],$00); { min }
  1764. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1765. { import tags }
  1766. NextTagIndex:=0;
  1767. for i:=0 to Data.ObjSymbolList.Count-1 do
  1768. begin
  1769. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1770. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1771. begin
  1772. objsym.TagIndex:=NextTagIndex;
  1773. Inc(NextTagIndex);
  1774. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1775. if objsym.ExtraData.ImportModule<>'' then
  1776. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1777. else
  1778. WriteName(FWasmSections[wsiImport],'env');
  1779. WriteName(FWasmSections[wsiImport],objsym.Name);
  1780. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1781. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1782. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1783. end;
  1784. end;
  1785. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1786. NextFunctionIndex:=NextImportFunctionIndex;
  1787. for i:=0 to Data.ObjSymbolList.Count-1 do
  1788. begin
  1789. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1790. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1791. begin
  1792. objsym.FuncIndex:=NextFunctionIndex;
  1793. Inc(NextFunctionIndex);
  1794. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1795. end;
  1796. end;
  1797. if exception_tags_count>0 then
  1798. begin
  1799. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1800. for i:=0 to Data.ObjSymbolList.Count-1 do
  1801. begin
  1802. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1803. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1804. begin
  1805. objsym.TagIndex:=NextTagIndex;
  1806. Inc(NextTagIndex);
  1807. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1808. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1809. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1810. end;
  1811. end;
  1812. end;
  1813. if globals_count>0 then
  1814. begin
  1815. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1816. for i:=0 to Data.ObjSymbolList.Count-1 do
  1817. begin
  1818. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1819. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1820. begin
  1821. objsym.GlobalIndex:=NextGlobalIndex;
  1822. Inc(NextGlobalIndex);
  1823. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1824. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1825. if objsym.ExtraData.GlobalIsImmutable then
  1826. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1827. else
  1828. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1829. { init expr }
  1830. case objsym.ExtraData.GlobalType of
  1831. wbt_i32:
  1832. begin
  1833. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1834. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1835. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1836. end;
  1837. wbt_i64:
  1838. begin
  1839. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1840. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1841. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1842. end;
  1843. wbt_f32:
  1844. begin
  1845. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1846. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1847. WriteByte(FWasmSections[wsiGlobal],$00);
  1848. WriteByte(FWasmSections[wsiGlobal],$00);
  1849. WriteByte(FWasmSections[wsiGlobal],$00);
  1850. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1851. end;
  1852. wbt_f64:
  1853. begin
  1854. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1855. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1856. WriteByte(FWasmSections[wsiGlobal],$00);
  1857. WriteByte(FWasmSections[wsiGlobal],$00);
  1858. WriteByte(FWasmSections[wsiGlobal],$00);
  1859. WriteByte(FWasmSections[wsiGlobal],$00);
  1860. WriteByte(FWasmSections[wsiGlobal],$00);
  1861. WriteByte(FWasmSections[wsiGlobal],$00);
  1862. WriteByte(FWasmSections[wsiGlobal],$00);
  1863. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1864. end;
  1865. wbt_externref:
  1866. begin
  1867. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1868. WriteByte(FWasmSections[wsiGlobal],$6F);
  1869. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1870. end;
  1871. wbt_funcref:
  1872. begin
  1873. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1874. WriteByte(FWasmSections[wsiGlobal],$70);
  1875. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1876. end;
  1877. else
  1878. internalerror(2022052801);
  1879. end;
  1880. end;
  1881. end;
  1882. end;
  1883. if export_functions_count>0 then
  1884. begin
  1885. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1886. for i:=0 to Data.ObjSymbolList.Count-1 do
  1887. begin
  1888. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1889. if IsExportedFunction(objsym) then
  1890. begin
  1891. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1892. WriteByte(FWasmSections[wsiExport],0); { func }
  1893. if (objsym.FuncIndex<0) then
  1894. message1(asmw_e_illegal_unset_index,objsym.name)
  1895. else
  1896. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1897. end;
  1898. end;
  1899. end;
  1900. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1901. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1902. if ts_wasm_threads in current_settings.targetswitches then
  1903. begin
  1904. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1905. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1906. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1907. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1908. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1909. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1910. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1911. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1912. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1913. end
  1914. else
  1915. begin
  1916. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  1917. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1918. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1919. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1920. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1921. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1922. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1923. end;
  1924. { Write the producers section:
  1925. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1926. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1927. WriteName(FWasmCustomSections[wcstProducers],'language');
  1928. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1929. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1930. WriteName(FWasmCustomSections[wcstProducers],'');
  1931. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1932. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1933. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1934. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1935. code_section_nr:=-1;
  1936. data_section_nr:=-1;
  1937. debug_abbrev_section_nr:=-1;
  1938. debug_info_section_nr:=-1;
  1939. debug_str_section_nr:=-1;
  1940. debug_line_section_nr:=-1;
  1941. debug_frame_section_nr:=-1;
  1942. debug_aranges_section_nr:=-1;
  1943. debug_ranges_section_nr:=-1;
  1944. section_nr:=0;
  1945. WriteWasmSection(wsiType);
  1946. Inc(section_nr);
  1947. WriteWasmSection(wsiImport);
  1948. Inc(section_nr);
  1949. WriteWasmSection(wsiFunction);
  1950. Inc(section_nr);
  1951. if exception_tags_count>0 then
  1952. begin
  1953. WriteWasmSection(wsiTag);
  1954. Inc(section_nr);
  1955. end;
  1956. if globals_count>0 then
  1957. begin
  1958. WriteWasmSection(wsiGlobal);
  1959. Inc(section_nr);
  1960. end;
  1961. if export_functions_count>0 then
  1962. begin
  1963. WriteWasmSection(wsiExport);
  1964. Inc(section_nr);
  1965. end;
  1966. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1967. if segment_count>0 then
  1968. Inc(section_nr); { the DataCount section }
  1969. code_section_nr:=section_nr; { the Code section }
  1970. Inc(section_nr);
  1971. if segment_count>0 then
  1972. begin
  1973. data_section_nr:=section_nr; { the Data section }
  1974. Inc(section_nr);
  1975. end;
  1976. { the debug sections }
  1977. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1978. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1979. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1980. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1981. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1982. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1983. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1984. for i:=0 to Data.ObjSymbolList.Count-1 do
  1985. begin
  1986. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1987. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1988. begin
  1989. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1990. Inc(FWasmSymbolTableEntriesCount);
  1991. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1992. if objsym.bind=AB_GLOBAL then
  1993. WriteUleb(FWasmSymbolTable,0)
  1994. else if objsym.bind=AB_LOCAL then
  1995. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1996. else if objsym.bind=AB_EXTERNAL then
  1997. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1998. else if objsym.bind=AB_WEAK then
  1999. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  2000. else
  2001. internalerror(2021092715);
  2002. if (objsym.TagIndex<0) then
  2003. message1(asmw_e_illegal_unset_index,objsym.name)
  2004. else
  2005. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  2006. if objsym.bind<>AB_EXTERNAL then
  2007. WriteName(FWasmSymbolTable,objsym.Name);
  2008. end
  2009. else if objsym.typ=AT_WASM_GLOBAL then
  2010. begin
  2011. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2012. Inc(FWasmSymbolTableEntriesCount);
  2013. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  2014. if objsym.bind=AB_EXTERNAL then
  2015. begin
  2016. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  2017. if (objsym.GlobalIndex<0) then
  2018. message1(asmw_e_illegal_unset_index,objsym.name)
  2019. else
  2020. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  2021. end
  2022. else
  2023. begin
  2024. WriteUleb(FWasmSymbolTable,0);
  2025. if (objsym.GlobalIndex<0) then
  2026. message1(asmw_e_illegal_unset_index,objsym.name)
  2027. else
  2028. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  2029. WriteName(FWasmSymbolTable,objsym.Name);
  2030. end;
  2031. end
  2032. else if IsExternalFunction(objsym) then
  2033. begin
  2034. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2035. Inc(FWasmSymbolTableEntriesCount);
  2036. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  2037. if objsym.ExtraData.ImportModule<>'' then
  2038. begin
  2039. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  2040. if (objsym.FuncIndex<0) then
  2041. message1(asmw_e_illegal_unset_index,objsym.name)
  2042. else
  2043. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  2044. WriteName(FWasmSymbolTable,objsym.Name);
  2045. end
  2046. else
  2047. begin
  2048. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  2049. if (objsym.FuncIndex<0) then
  2050. message1(asmw_e_illegal_unset_index,objsym.name)
  2051. else
  2052. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  2053. end;
  2054. end
  2055. else if objsym.typ=AT_FUNCTION then
  2056. begin
  2057. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2058. Inc(FWasmSymbolTableEntriesCount);
  2059. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  2060. if objsym.IsAlias then
  2061. begin
  2062. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  2063. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  2064. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  2065. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  2066. end
  2067. else
  2068. begin
  2069. if IsExportedFunction(objsym) then
  2070. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  2071. else
  2072. WriteUleb(FWasmSymbolTable,0);
  2073. if (objsym.FuncIndex<0) then
  2074. message1(asmw_e_illegal_unset_index,objsym.name)
  2075. else
  2076. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  2077. end;
  2078. WriteName(FWasmSymbolTable,objsym.Name);
  2079. end
  2080. else if (objsym.typ in [AT_DATA,AT_TLS,AT_METADATA]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  2081. begin
  2082. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  2083. begin
  2084. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2085. Inc(FWasmSymbolTableEntriesCount);
  2086. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FPC_CUSTOM));
  2087. if objsym.bind=AB_GLOBAL then
  2088. SymbolFlags:=0
  2089. else if objsym.bind=AB_LOCAL then
  2090. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  2091. else if objsym.bind=AB_EXTERNAL then
  2092. SymbolFlags:=WASM_SYM_UNDEFINED
  2093. else
  2094. internalerror(2024090701);
  2095. WriteUleb(FWasmSymbolTable,SymbolFlags);
  2096. WriteName(FWasmSymbolTable,objsym.Name);
  2097. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).CustomSectionIdx);
  2098. WriteUleb(FWasmSymbolTable,objsym.offset);
  2099. WriteUleb(FWasmSymbolTable,objsym.size);
  2100. end
  2101. else
  2102. begin
  2103. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  2104. Inc(FWasmSymbolTableEntriesCount);
  2105. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  2106. if objsym.bind=AB_GLOBAL then
  2107. SymbolFlags:=0
  2108. else if objsym.bind=AB_LOCAL then
  2109. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  2110. else if objsym.bind=AB_EXTERNAL then
  2111. SymbolFlags:=WASM_SYM_UNDEFINED
  2112. else
  2113. internalerror(2021092506);
  2114. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  2115. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  2116. WriteUleb(FWasmSymbolTable,SymbolFlags);
  2117. WriteName(FWasmSymbolTable,objsym.Name);
  2118. if objsym.bind<>AB_EXTERNAL then
  2119. begin
  2120. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  2121. WriteUleb(FWasmSymbolTable,objsym.offset);
  2122. WriteUleb(FWasmSymbolTable,objsym.size);
  2123. end;
  2124. end;
  2125. end;
  2126. end;
  2127. DoRelocations;
  2128. if segment_count>0 then
  2129. begin
  2130. WriteUleb(FWasmSections[wsiData],segment_count);
  2131. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  2132. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  2133. for i:=0 to Data.ObjSectionList.Count-1 do
  2134. begin
  2135. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  2136. if objsec.IsData then
  2137. begin
  2138. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  2139. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  2140. SegmentFlags:=0;
  2141. if (ts_wasm_threads in current_settings.targetswitches) and
  2142. (oso_threadvar in objsec.SecOptions) then
  2143. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  2144. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  2145. WriteByte(FWasmSections[wsiData],0);
  2146. WriteByte(FWasmSections[wsiData],$41);
  2147. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  2148. WriteByte(FWasmSections[wsiData],$0b);
  2149. WriteUleb(FWasmSections[wsiData],objsec.Size);
  2150. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  2151. if oso_Data in objsec.SecOptions then
  2152. begin
  2153. objsec.Data.seek(0);
  2154. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  2155. end
  2156. else
  2157. begin
  2158. WriteZeros(FWasmSections[wsiData],objsec.Size);
  2159. end;
  2160. end;
  2161. end;
  2162. end;
  2163. WriteUleb(FWasmSections[wsiCode],functions_count);
  2164. for i:=0 to Data.ObjSymbolList.Count-1 do
  2165. begin
  2166. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  2167. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  2168. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  2169. end;
  2170. if segment_count>0 then
  2171. WriteWasmSection(wsiDataCount);
  2172. WriteWasmSection(wsiCode);
  2173. if segment_count>0 then
  2174. WriteWasmSection(wsiData);
  2175. MaybeWriteDebugSection(wcstDebugAbbrev);
  2176. MaybeWriteDebugSection(wcstDebugInfo);
  2177. MaybeWriteDebugSection(wcstDebugStr);
  2178. MaybeWriteDebugSection(wcstDebugLine);
  2179. MaybeWriteDebugSection(wcstDebugFrame);
  2180. MaybeWriteDebugSection(wcstDebugAranges);
  2181. MaybeWriteDebugSection(wcstDebugRanges);
  2182. WriteRelocations;
  2183. WriteSymbolTable;
  2184. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  2185. if segment_count>0 then
  2186. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  2187. WriteRelocationCodeTable(code_section_nr);
  2188. if segment_count>0 then
  2189. WriteRelocationDataTable(data_section_nr);
  2190. WriteWasmCustomSection(wcstLinking);
  2191. Inc(section_nr);
  2192. WriteWasmCustomSection(wcstRelocCode);
  2193. Inc(section_nr);
  2194. if segment_count>0 then
  2195. begin
  2196. WriteWasmCustomSection(wcstRelocData);
  2197. Inc(section_nr);
  2198. end;
  2199. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  2200. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  2201. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  2202. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  2203. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  2204. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  2205. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  2206. WriteWasmCustomSection(wcstProducers);
  2207. Inc(section_nr);
  2208. WriteWasmCustomSection(wcstTargetFeatures);
  2209. Inc(section_nr);
  2210. result:=true;
  2211. end;
  2212. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  2213. var
  2214. i: TWasmSectionID;
  2215. j: TWasmCustomSectionType;
  2216. k: TWasmLinkingSubsectionType;
  2217. begin
  2218. inherited;
  2219. cobjdata:=TWasmObjData;
  2220. for i in TWasmSectionID do
  2221. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  2222. for j in TWasmCustomSectionType do
  2223. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  2224. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2225. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  2226. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  2227. FWasmSymbolTableEntriesCount:=0;
  2228. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  2229. FWasmRelocationCodeTableEntriesCount:=0;
  2230. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  2231. FWasmRelocationDataTableEntriesCount:=0;
  2232. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  2233. FWasmRelocationDebugFrameTableEntriesCount:=0;
  2234. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  2235. FWasmRelocationDebugInfoTableEntriesCount:=0;
  2236. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  2237. FWasmRelocationDebugLineTableEntriesCount:=0;
  2238. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  2239. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  2240. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2241. FWasmRelocationDebugArangesTableEntriesCount:=0;
  2242. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  2243. FWasmRelocationDebugRangesTableEntriesCount:=0;
  2244. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  2245. FWasmRelocationDebugStrTableEntriesCount:=0;
  2246. end;
  2247. destructor TWasmObjOutput.destroy;
  2248. var
  2249. i: TWasmSectionID;
  2250. j: TWasmCustomSectionType;
  2251. k: TWasmLinkingSubsectionType;
  2252. begin
  2253. for i in TWasmSectionID do
  2254. FWasmSections[i].Free;
  2255. for j in TWasmCustomSectionType do
  2256. FWasmCustomSections[j].Free;
  2257. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  2258. FWasmLinkingSubsections[k].Free;
  2259. FWasmSymbolTable.Free;
  2260. FWasmRelocationCodeTable.Free;
  2261. FWasmRelocationDataTable.Free;
  2262. FWasmRelocationDebugFrameTable.Free;
  2263. FWasmRelocationDebugInfoTable.Free;
  2264. FWasmRelocationDebugLineTable.Free;
  2265. FWasmRelocationDebugAbbrevTable.Free;
  2266. FWasmRelocationDebugArangesTable.Free;
  2267. FWasmRelocationDebugRangesTable.Free;
  2268. FWasmRelocationDebugStrTable.Free;
  2269. inherited destroy;
  2270. end;
  2271. {****************************************************************************
  2272. TWasmObjInput
  2273. ****************************************************************************}
  2274. constructor TWasmObjInput.create;
  2275. begin
  2276. inherited create;
  2277. cobjdata:=TWasmObjData;
  2278. end;
  2279. destructor TWasmObjInput.Destroy;
  2280. var
  2281. i: Integer;
  2282. begin
  2283. for i:=low(FFuncTypes) to high(FFuncTypes) do
  2284. begin
  2285. FFuncTypes[i].free;
  2286. FFuncTypes[i]:=nil;
  2287. end;
  2288. inherited Destroy;
  2289. end;
  2290. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2291. var
  2292. ModuleMagic: array [0..3] of Byte;
  2293. ModuleVersion: array [0..3] of Byte;
  2294. i: Integer;
  2295. begin
  2296. result:=false;
  2297. if not AReader.read(ModuleMagic,4) then
  2298. exit;
  2299. for i:=0 to 3 do
  2300. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2301. exit;
  2302. if not AReader.read(ModuleVersion,4) then
  2303. exit;
  2304. for i:=0 to 3 do
  2305. if ModuleVersion[i]<>WasmVersion[i] then
  2306. exit;
  2307. result:=true;
  2308. end;
  2309. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2310. type
  2311. TLimits = record
  2312. Min, Max: uint32;
  2313. HasMax: Boolean;
  2314. end;
  2315. var
  2316. SectionIndex: Integer = -1;
  2317. SectionId: Byte;
  2318. SectionSize: uint32;
  2319. SectionStart: LongInt;
  2320. CheckSectionBounds: Boolean;
  2321. TypeSectionRead: Boolean = false;
  2322. ImportSectionRead: Boolean = false;
  2323. FunctionSectionRead: Boolean = false;
  2324. GlobalSectionRead: Boolean = false;
  2325. ExportSectionRead: Boolean = false;
  2326. ElementSectionRead: Boolean = false;
  2327. TagSectionRead: Boolean = false;
  2328. CodeSectionRead: Boolean = false;
  2329. DataSectionRead: Boolean = false;
  2330. DataCountSectionRead: Boolean = false;
  2331. SegmentInfoSectionRead: Boolean = false;
  2332. SymbolTableSectionRead: Boolean = false;
  2333. CodeSectionIndex: Integer = -1;
  2334. DataSectionIndex: Integer = -1;
  2335. DebugSectionIndex: array [TWasmCustomDebugSectionType] of Integer = (-1,-1,-1,-1,-1,-1,-1);
  2336. FuncTypes: array of record
  2337. IsImport: Boolean;
  2338. ImportName: ansistring;
  2339. ImportModName: ansistring;
  2340. typidx: uint32;
  2341. IsExported: Boolean;
  2342. ExportName: ansistring;
  2343. end;
  2344. FuncTypeImportsCount: uint32;
  2345. TableTypes: array of record
  2346. IsImport: Boolean;
  2347. ImportName: ansistring;
  2348. ImportModName: ansistring;
  2349. reftype: TWasmBAsicType;
  2350. limits: TLimits;
  2351. IsExported: Boolean;
  2352. ExportName: ansistring;
  2353. end;
  2354. TableTypeImportsCount: uint32;
  2355. MemTypes: array of record
  2356. IsImport: Boolean;
  2357. ImportName: ansistring;
  2358. ImportModName: ansistring;
  2359. limits: TLimits;
  2360. IsExported: Boolean;
  2361. ExportName: ansistring;
  2362. end;
  2363. MemTypeImportsCount: uint32;
  2364. GlobalTypes: array of record
  2365. IsImport: Boolean;
  2366. ImportName: ansistring;
  2367. ImportModName: ansistring;
  2368. valtype: TWasmBasicType;
  2369. IsMutable: Boolean;
  2370. IsExported: Boolean;
  2371. ExportName: ansistring;
  2372. GlobalInit: TGlobalInitializer;
  2373. end;
  2374. GlobalTypeImportsCount: uint32;
  2375. TagTypes: array of record
  2376. IsImport: Boolean;
  2377. ImportName: ansistring;
  2378. ImportModName: ansistring;
  2379. TagAttr: Byte;
  2380. TagTypeIdx: uint32;
  2381. IsExported: Boolean;
  2382. ExportName: ansistring;
  2383. end;
  2384. TagTypeImportsCount: uint32;
  2385. CodeSegments: array of record
  2386. CodeSectionOffset: uint32;
  2387. CodeSize: uint32;
  2388. DataPos: LongInt;
  2389. SegName: ansistring;
  2390. SegIsExported: Boolean;
  2391. end;
  2392. DataSegments: array of record
  2393. DataSectionOffset: uint32;
  2394. Active: Boolean;
  2395. MemIdx: uint32;
  2396. Len: uint32;
  2397. Offset: int32;
  2398. DataPos: LongInt;
  2399. SegName: ansistring;
  2400. SegAlignment: uint32;
  2401. SegFlags: uint32;
  2402. end;
  2403. SymbolTable: array of record
  2404. SymFlags: uint32;
  2405. TargetSection: uint32;
  2406. SymIndex: uint32;
  2407. SymOffset: uint32;
  2408. SymSize: uint32;
  2409. SymCustomSectionIndex: uint32;
  2410. SymCustomSectionType: TWasmCustomDebugSectionType;
  2411. SymKind: TWasmSymbolType;
  2412. SymName: ansistring;
  2413. ObjSym: TWasmObjSymbol;
  2414. ObjSec: TWasmObjSection;
  2415. end;
  2416. { meaning of first index: }
  2417. { table 0 is code relocs }
  2418. { table 1 is data relocs }
  2419. { tables 2.. are custom section relocs for debug sections }
  2420. RelocationTable: array of array of record
  2421. RelocType: TWasmRelocationType;
  2422. RelocOffset: uint32;
  2423. RelocIndex: uint32;
  2424. RelocAddend: int32;
  2425. end;
  2426. function FindDebugSectionByIndex(SectionIndex: Integer; out res: TWasmCustomDebugSectionType): Boolean;
  2427. var
  2428. ds: TWasmCustomDebugSectionType;
  2429. begin
  2430. for ds in TWasmCustomDebugSectionType do
  2431. if DebugSectionIndex[ds]=SectionIndex then
  2432. begin
  2433. Res:=ds;
  2434. Result:=True;
  2435. exit;
  2436. end;
  2437. Res:=low(TWasmCustomDebugSectionType);
  2438. Result:=False;
  2439. end;
  2440. function ReadSection: Boolean;
  2441. function read(out b;len:longint):boolean;
  2442. begin
  2443. result:=false;
  2444. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2445. result:=AReader.read(b,len)
  2446. else
  2447. begin
  2448. { trying to read beyond the end of the section }
  2449. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2450. result:=false;
  2451. end;
  2452. end;
  2453. function ReadUleb(out v: uint64): boolean;
  2454. var
  2455. b: byte;
  2456. shift:integer;
  2457. begin
  2458. result:=false;
  2459. b:=0;
  2460. v:=0;
  2461. shift:=0;
  2462. repeat
  2463. if not read(b,1) then
  2464. exit;
  2465. v:=v or (uint64(b and 127) shl shift);
  2466. inc(shift,7);
  2467. until (b and 128)=0;
  2468. result:=true;
  2469. end;
  2470. function ReadUleb32(out v: uint32): boolean;
  2471. var
  2472. vv: uint64;
  2473. begin
  2474. result:=false;
  2475. v:=default(uint32);
  2476. if not ReadUleb(vv) then
  2477. exit;
  2478. if vv>high(uint32) then
  2479. exit;
  2480. v:=vv;
  2481. result:=true;
  2482. end;
  2483. function ReadSleb(out v: int64): boolean;
  2484. var
  2485. b: byte;
  2486. shift:integer;
  2487. begin
  2488. result:=false;
  2489. b:=0;
  2490. v:=0;
  2491. shift:=0;
  2492. repeat
  2493. if not read(b,1) then
  2494. exit;
  2495. v:=v or (uint64(b and 127) shl shift);
  2496. inc(shift,7);
  2497. until (b and 128)=0;
  2498. {$ifopt Q+}
  2499. {$define overflowon}
  2500. {$Q-}
  2501. {$endif}
  2502. {$ifopt R+}
  2503. {$define rangeon}
  2504. {$R-}
  2505. {$endif}
  2506. if (b and 64)<>0 then
  2507. v:=v or (high(uint64) shl shift);
  2508. result:=true;
  2509. end;
  2510. {$ifdef overflowon}
  2511. {$Q+}
  2512. {$undef overflowon}
  2513. {$endif}
  2514. {$ifdef rangeon}
  2515. {$R+}
  2516. {$undef rangeon}
  2517. {$endif}
  2518. function ReadSleb32(out v: int32): boolean;
  2519. var
  2520. vv: int64;
  2521. begin
  2522. result:=false;
  2523. v:=default(int32);
  2524. if not ReadSleb(vv) then
  2525. exit;
  2526. if (vv>high(int32)) or (vv<low(int32)) then
  2527. exit;
  2528. v:=vv;
  2529. result:=true;
  2530. end;
  2531. function ReadName(out v: ansistring): boolean;
  2532. var
  2533. len: uint32;
  2534. begin
  2535. result:=false;
  2536. if not ReadUleb32(len) then
  2537. exit;
  2538. SetLength(v,len);
  2539. if len>0 then
  2540. result:=read(v[1],len)
  2541. else
  2542. result:=true;
  2543. end;
  2544. function ReadCustomSection: Boolean;
  2545. function ReadRelocationSection: Boolean;
  2546. var
  2547. TargetSection, RelocCount: uint32;
  2548. i: Integer;
  2549. RelocTableIndex: Integer;
  2550. ds: TWasmCustomDebugSectionType;
  2551. begin
  2552. Result:=False;
  2553. if not ReadUleb32(TargetSection) then
  2554. begin
  2555. InputError('Error reading the index of the target section of a relocation section');
  2556. exit;
  2557. end;
  2558. if TargetSection=CodeSectionIndex then
  2559. RelocTableIndex:=0
  2560. else if TargetSection=DataSectionIndex then
  2561. RelocTableIndex:=1
  2562. else
  2563. begin
  2564. RelocTableIndex:=-1;
  2565. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  2566. if DebugSectionIndex[ds]=TargetSection then
  2567. begin
  2568. RelocTableIndex:=2+(Ord(ds)-Ord(Low(TWasmCustomDebugSectionType)));
  2569. break;
  2570. end;
  2571. if RelocTableIndex=-1 then
  2572. begin
  2573. InputError('Relocation found for a custom section, that is not supported');
  2574. exit;
  2575. end;
  2576. end;
  2577. if not ReadUleb32(RelocCount) then
  2578. begin
  2579. InputError('Error reading the relocation entries count from a relocation section');
  2580. exit;
  2581. end;
  2582. SetLength(RelocationTable[RelocTableIndex],RelocCount);
  2583. for i:=0 to RelocCount-1 do
  2584. with RelocationTable[RelocTableIndex,i] do
  2585. begin
  2586. if not Read(RelocType,1) then
  2587. begin
  2588. InputError('Error reading the relocation type of a relocation entry');
  2589. exit;
  2590. end;
  2591. if not (RelocType in [R_WASM_FUNCTION_INDEX_LEB,
  2592. R_WASM_MEMORY_ADDR_LEB,
  2593. R_WASM_TABLE_INDEX_SLEB,
  2594. R_WASM_MEMORY_ADDR_SLEB,
  2595. R_WASM_SECTION_OFFSET_I32,
  2596. R_WASM_TABLE_INDEX_I32,
  2597. R_WASM_FUNCTION_OFFSET_I32,
  2598. R_WASM_MEMORY_ADDR_I32,
  2599. R_WASM_TYPE_INDEX_LEB,
  2600. R_WASM_GLOBAL_INDEX_LEB,
  2601. R_WASM_TAG_INDEX_LEB,
  2602. R_WASM_GLOBAL_INDEX_I32]) then
  2603. begin
  2604. InputError('Unsupported relocation type: ' + tostr(Ord(RelocType)));
  2605. exit;
  2606. end;
  2607. if not ReadUleb32(RelocOffset) then
  2608. begin
  2609. InputError('Error reading the relocation offset of a relocation entry');
  2610. exit;
  2611. end;
  2612. if not ReadUleb32(RelocIndex) then
  2613. begin
  2614. InputError('Error reading the relocation index of a relocation entry');
  2615. exit;
  2616. end;
  2617. if RelocType in [R_WASM_FUNCTION_OFFSET_I32,R_WASM_SECTION_OFFSET_I32,R_WASM_MEMORY_ADDR_LEB,R_WASM_MEMORY_ADDR_SLEB,R_WASM_MEMORY_ADDR_I32] then
  2618. begin
  2619. if not ReadSleb32(RelocAddend) then
  2620. begin
  2621. InputError('Error reading the relocation addend of a relocation entry');
  2622. exit;
  2623. end;
  2624. end;
  2625. if (RelocType in [
  2626. R_WASM_SECTION_OFFSET_I32,
  2627. R_WASM_FUNCTION_INDEX_LEB,
  2628. R_WASM_TABLE_INDEX_SLEB,
  2629. R_WASM_TABLE_INDEX_I32,
  2630. R_WASM_MEMORY_ADDR_LEB,
  2631. R_WASM_MEMORY_ADDR_SLEB,
  2632. R_WASM_MEMORY_ADDR_I32,
  2633. R_WASM_FUNCTION_OFFSET_I32,
  2634. R_WASM_GLOBAL_INDEX_LEB,
  2635. R_WASM_GLOBAL_INDEX_I32]) and (RelocIndex>High(SymbolTable)) then
  2636. begin
  2637. InputError('Relocation index outside the bounds of the symbol table');
  2638. exit;
  2639. end;
  2640. if (RelocType=R_WASM_TYPE_INDEX_LEB) and (RelocIndex>High(FFuncTypes)) then
  2641. begin
  2642. InputError('Relocation index of R_WASM_TYPE_INDEX_LEB outside the bounds of the func types, defined in the func section of the module');
  2643. exit;
  2644. end;
  2645. if (RelocType=R_WASM_SECTION_OFFSET_I32) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_SECTION) then
  2646. begin
  2647. InputError('R_WASM_SECTION_OFFSET_I32 must point to a SYMTAB_SECTION symbol');
  2648. exit;
  2649. end;
  2650. if (RelocType in [R_WASM_GLOBAL_INDEX_LEB,R_WASM_GLOBAL_INDEX_I32]) and
  2651. not ((SymbolTable[RelocIndex].SymKind=SYMTAB_GLOBAL) or
  2652. ((ts_wasm_threads in current_settings.targetswitches) and
  2653. (SymbolTable[RelocIndex].SymKind=SYMTAB_DATA) and
  2654. ((SymbolTable[RelocIndex].SymFlags and WASM_SYM_TLS)<>0))) then
  2655. begin
  2656. if ts_wasm_threads in current_settings.targetswitches then
  2657. InputError('Relocation must point to a SYMTAB_GLOBAL symbol or a SYMTAB_DATA symbol with the WASM_SYM_TLS flag set')
  2658. else
  2659. InputError('Relocation must point to a SYMTAB_GLOBAL symbol');
  2660. exit;
  2661. end;
  2662. if (RelocType=R_WASM_TAG_INDEX_LEB) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_EVENT) then
  2663. begin
  2664. InputError('Relocation must point to a SYMTAB_EVENT symbol');
  2665. exit;
  2666. end;
  2667. if (RelocType in [
  2668. R_WASM_FUNCTION_INDEX_LEB,
  2669. R_WASM_TABLE_INDEX_SLEB,
  2670. R_WASM_TABLE_INDEX_I32,
  2671. R_WASM_FUNCTION_OFFSET_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_FUNCTION) then
  2672. begin
  2673. InputError('Relocation must point to a SYMTAB_FUNCTION symbol');
  2674. exit;
  2675. end;
  2676. if (RelocType in [
  2677. R_WASM_MEMORY_ADDR_LEB,
  2678. R_WASM_MEMORY_ADDR_SLEB,
  2679. R_WASM_MEMORY_ADDR_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_DATA) then
  2680. begin
  2681. InputError('Relocation must point to a SYMTAB_DATA symbol');
  2682. exit;
  2683. end;
  2684. end;
  2685. if AReader.Pos<>(SectionStart+SectionSize) then
  2686. begin
  2687. InputError('Unexpected relocation section size');
  2688. exit;
  2689. end;
  2690. Result:=True;
  2691. end;
  2692. function ReadLinkingSection: Boolean;
  2693. function ReadSegmentInfo: Boolean;
  2694. var
  2695. SegmentCount: uint32;
  2696. i: Integer;
  2697. begin
  2698. Result:=False;
  2699. if SegmentInfoSectionRead then
  2700. begin
  2701. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2702. exit;
  2703. end;
  2704. SegmentInfoSectionRead:=True;
  2705. if not ReadUleb32(SegmentCount) then
  2706. begin
  2707. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2708. exit;
  2709. end;
  2710. if SegmentCount<>Length(DataSegments) then
  2711. begin
  2712. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2713. exit;
  2714. end;
  2715. for i:=0 to SegmentCount-1 do
  2716. with DataSegments[i] do
  2717. begin
  2718. if not ReadName(SegName) then
  2719. begin
  2720. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2721. exit;
  2722. end;
  2723. if not ReadUleb32(SegAlignment) then
  2724. begin
  2725. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2726. exit;
  2727. end;
  2728. if not ReadUleb32(SegFlags) then
  2729. begin
  2730. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2731. exit;
  2732. end;
  2733. end;
  2734. if AReader.Pos<>(SectionStart+SectionSize) then
  2735. begin
  2736. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2737. exit;
  2738. end;
  2739. Result:=True;
  2740. end;
  2741. function ReadSymbolTable: Boolean;
  2742. var
  2743. SymCount: uint32;
  2744. i: Integer;
  2745. SymKindName: string;
  2746. SymKindB: Byte;
  2747. begin
  2748. Result:=False;
  2749. if SymbolTableSectionRead then
  2750. begin
  2751. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2752. exit;
  2753. end;
  2754. SymbolTableSectionRead:=True;
  2755. if not ReadUleb32(SymCount) then
  2756. begin
  2757. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2758. exit;
  2759. end;
  2760. SetLength(SymbolTable,SymCount);
  2761. for i:=0 to SymCount-1 do
  2762. with SymbolTable[i] do
  2763. begin
  2764. if not Read(SymKindB,1) then
  2765. begin
  2766. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2767. exit;
  2768. end;
  2769. if SymKindB>Ord(High(TWasmSymbolType)) then
  2770. begin
  2771. InputError('Unsupported symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2772. exit;
  2773. end;
  2774. SymKind:=TWasmSymbolType(SymKindB);
  2775. if not ReadUleb32(SymFlags) then
  2776. begin
  2777. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2778. exit;
  2779. end;
  2780. case SymKind of
  2781. SYMTAB_FUNCTION,
  2782. SYMTAB_GLOBAL,
  2783. SYMTAB_EVENT,
  2784. SYMTAB_TABLE:
  2785. begin
  2786. WriteStr(SymKindName, SymKind);
  2787. if not ReadUleb32(SymIndex) then
  2788. begin
  2789. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2790. exit;
  2791. end;
  2792. if ((SymKind=SYMTAB_FUNCTION) and (SymIndex>high(FuncTypes))) or
  2793. ((SymKind=SYMTAB_EVENT) and (SymIndex>high(TagTypes))) then
  2794. begin
  2795. InputError('Symbol index too high');
  2796. exit;
  2797. end;
  2798. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2799. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2800. begin
  2801. if not ReadName(SymName) then
  2802. begin
  2803. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2804. exit;
  2805. end;
  2806. end;
  2807. end;
  2808. SYMTAB_DATA:
  2809. begin
  2810. if not ReadName(SymName) then
  2811. begin
  2812. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2813. exit;
  2814. end;
  2815. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2816. begin
  2817. if not ReadUleb32(SymIndex) then
  2818. begin
  2819. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2820. exit;
  2821. end;
  2822. if SymIndex>high(DataSegments) then
  2823. begin
  2824. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2825. exit;
  2826. end;
  2827. if not ReadUleb32(SymOffset) then
  2828. begin
  2829. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2830. exit;
  2831. end;
  2832. if not ReadUleb32(SymSize) then
  2833. begin
  2834. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2835. exit;
  2836. end;
  2837. end;
  2838. end;
  2839. SYMTAB_FPC_CUSTOM:
  2840. begin
  2841. if not ReadName(SymName) then
  2842. begin
  2843. InputError('Error reading symbol name of a SYMTAB_FPC_CUSTOM symbol');
  2844. exit;
  2845. end;
  2846. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2847. begin
  2848. if not ReadUleb32(SymCustomSectionIndex) then
  2849. begin
  2850. InputError('Error reading the custom section index of a SYMTAB_FPC_CUSTOM symbol');
  2851. exit;
  2852. end;
  2853. if not FindDebugSectionByIndex(SymCustomSectionIndex,SymCustomSectionType) then
  2854. begin
  2855. InputError('Custom section index of SYMTAB_FPC_CUSTOM symbol not pointing to a debug section');
  2856. exit;
  2857. end;
  2858. if not ReadUleb32(SymOffset) then
  2859. begin
  2860. InputError('Error reading the offset of a SYMTAB_FPC_CUSTOM symbol');
  2861. exit;
  2862. end;
  2863. if not ReadUleb32(SymSize) then
  2864. begin
  2865. InputError('Error reading the size of a SYMTAB_FPC_CUSTOM symbol');
  2866. exit;
  2867. end;
  2868. end;
  2869. end;
  2870. SYMTAB_SECTION:
  2871. begin
  2872. if not ReadUleb32(TargetSection) then
  2873. begin
  2874. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2875. exit;
  2876. end;
  2877. end;
  2878. end;
  2879. end;
  2880. if AReader.Pos<>(SectionStart+SectionSize) then
  2881. begin
  2882. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2883. exit;
  2884. end;
  2885. Result:=True;
  2886. end;
  2887. const
  2888. ExpectedVersion = 2;
  2889. var
  2890. Version, SubsectionSize, SaveSectionSize: uint32;
  2891. SubsectionType: Byte;
  2892. SaveSectionStart: LongInt;
  2893. begin
  2894. Result:=False;
  2895. if not ReadUleb32(Version) then
  2896. begin
  2897. InputError('Error reading the version of the ''linking'' section');
  2898. exit;
  2899. end;
  2900. if Version<>ExpectedVersion then
  2901. begin
  2902. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2903. exit;
  2904. end;
  2905. while AReader.Pos<(SectionStart+SectionSize) do
  2906. begin
  2907. if not read(SubsectionType, 1) then
  2908. begin
  2909. InputError('Error reading subsection type in the ''linking'' section');
  2910. exit;
  2911. end;
  2912. if not ReadUleb32(SubsectionSize) then
  2913. begin
  2914. InputError('Error reading subsection size in the ''linking'' section');
  2915. exit;
  2916. end;
  2917. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2918. begin
  2919. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2920. exit;
  2921. end;
  2922. SaveSectionStart:=SectionStart;
  2923. SaveSectionSize:=SectionSize;
  2924. SectionStart:=AReader.Pos;
  2925. SectionSize:=SubsectionSize;
  2926. case SubsectionType of
  2927. Byte(WASM_SEGMENT_INFO):
  2928. if not ReadSegmentInfo then
  2929. begin
  2930. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2931. exit;
  2932. end;
  2933. Byte(WASM_SYMBOL_TABLE):
  2934. if not ReadSymbolTable then
  2935. begin
  2936. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2937. exit;
  2938. end;
  2939. else
  2940. begin
  2941. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2942. exit;
  2943. end;
  2944. end;
  2945. AReader.Seek(SectionStart+SectionSize);
  2946. SectionStart:=SaveSectionStart;
  2947. SectionSize:=SaveSectionSize;
  2948. end;
  2949. result:=True;
  2950. end;
  2951. function ReadProducersSection: Boolean;
  2952. begin
  2953. Result:=False;
  2954. end;
  2955. function ReadTargetFeaturesSection: Boolean;
  2956. begin
  2957. Result:=False;
  2958. end;
  2959. function ReadDebugSection(const SectionName: string; SectionType: TWasmCustomDebugSectionType): Boolean;
  2960. var
  2961. ObjSec: TObjSection;
  2962. begin
  2963. Result:=False;
  2964. if DebugSectionIndex[SectionType]<>-1 then
  2965. begin
  2966. InputError('Duplicated debug section: ' + SectionName);
  2967. exit;
  2968. end;
  2969. DebugSectionIndex[SectionType]:=SectionIndex;
  2970. ObjSec:=ObjData.createsection(SectionName,1,[oso_Data,oso_debug],false);
  2971. ObjSec.DataPos:=AReader.Pos;
  2972. ObjSec.Size:=SectionStart+SectionSize-AReader.Pos;
  2973. Result:=True;
  2974. end;
  2975. const
  2976. RelocationSectionPrefix = 'reloc.';
  2977. var
  2978. SectionName: ansistring;
  2979. begin
  2980. Result:=False;
  2981. ReadName(SectionName);
  2982. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2983. begin
  2984. if not ReadRelocationSection then
  2985. begin
  2986. InputError('Error reading the relocation section ''' + SectionName + '''');
  2987. exit;
  2988. end;
  2989. end
  2990. else
  2991. case SectionName of
  2992. 'linking':
  2993. if not ReadLinkingSection then
  2994. begin
  2995. InputError('Error reading the ''linking'' section');
  2996. exit;
  2997. end;
  2998. 'producers':
  2999. Result:=ReadProducersSection;
  3000. 'target_features':
  3001. Result:=ReadTargetFeaturesSection;
  3002. '.debug_frame':
  3003. if not ReadDebugSection(SectionName, wcstDebugFrame) then
  3004. begin
  3005. InputError('Error reading section ' + SectionName);
  3006. exit;
  3007. end;
  3008. '.debug_info':
  3009. if not ReadDebugSection(SectionName, wcstDebugInfo) then
  3010. begin
  3011. InputError('Error reading section ' + SectionName);
  3012. exit;
  3013. end;
  3014. '.debug_line':
  3015. if not ReadDebugSection(SectionName, wcstDebugLine) then
  3016. begin
  3017. InputError('Error reading section ' + SectionName);
  3018. exit;
  3019. end;
  3020. '.debug_abbrev':
  3021. if not ReadDebugSection(SectionName, wcstDebugAbbrev) then
  3022. begin
  3023. InputError('Error reading section ' + SectionName);
  3024. exit;
  3025. end;
  3026. '.debug_aranges':
  3027. if not ReadDebugSection(SectionName, wcstDebugAranges) then
  3028. begin
  3029. InputError('Error reading section ' + SectionName);
  3030. exit;
  3031. end;
  3032. '.debug_ranges':
  3033. if not ReadDebugSection(SectionName, wcstDebugRanges) then
  3034. begin
  3035. InputError('Error reading section ' + SectionName);
  3036. exit;
  3037. end;
  3038. '.debug_str':
  3039. if not ReadDebugSection(SectionName, wcstDebugStr) then
  3040. begin
  3041. InputError('Error reading section ' + SectionName);
  3042. exit;
  3043. end;
  3044. else
  3045. InputError('Unsupported custom section: ''' + SectionName + '''');
  3046. end;
  3047. Result:=True;
  3048. end;
  3049. function ReadTypeSection: Boolean;
  3050. var
  3051. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  3052. FuncTypeId, WasmTypeId: Byte;
  3053. i, j: Integer;
  3054. wbt: TWasmBasicType;
  3055. begin
  3056. Result:=False;
  3057. if TypeSectionRead then
  3058. begin
  3059. InputError('Type section is duplicated');
  3060. exit;
  3061. end;
  3062. TypeSectionRead:=True;
  3063. if not ReadUleb32(FuncTypesCount) then
  3064. begin
  3065. InputError('Error reading the func types count');
  3066. exit;
  3067. end;
  3068. SetLength(FFuncTypes,FuncTypesCount);
  3069. for i:=0 to FuncTypesCount - 1 do
  3070. begin
  3071. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  3072. if not AReader.read(FuncTypeId,1) then
  3073. begin
  3074. InputError('Error reading the function type identifier');
  3075. exit;
  3076. end;
  3077. if FuncTypeId<>$60 then
  3078. begin
  3079. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  3080. exit;
  3081. end;
  3082. if not ReadUleb32(ParamsCount) then
  3083. begin
  3084. InputError('Error reading the function parameters count');
  3085. exit;
  3086. end;
  3087. for j:=0 to ParamsCount-1 do
  3088. begin
  3089. if not AReader.read(WasmTypeId,1) then
  3090. begin
  3091. InputError('Error reading a function parameter basic type');
  3092. exit;
  3093. end;
  3094. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  3095. begin
  3096. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  3097. exit;
  3098. end;
  3099. FFuncTypes[i].add_param(wbt);
  3100. end;
  3101. if not ReadUleb32(ResultsCount) then
  3102. begin
  3103. InputError('Error reading the function results count');
  3104. exit;
  3105. end;
  3106. for j:=0 to ResultsCount-1 do
  3107. begin
  3108. if not AReader.read(WasmTypeId,1) then
  3109. begin
  3110. InputError('Error reading a function result basic type');
  3111. exit;
  3112. end;
  3113. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  3114. begin
  3115. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  3116. exit;
  3117. end;
  3118. FFuncTypes[i].add_result(wbt);
  3119. end;
  3120. end;
  3121. if AReader.Pos<>(SectionStart+SectionSize) then
  3122. begin
  3123. InputError('Unexpected type section size');
  3124. exit;
  3125. end;
  3126. Result:=true;
  3127. end;
  3128. function ReadImportSection: Boolean;
  3129. var
  3130. ImportsCount: uint32;
  3131. i: Integer;
  3132. ModName, Name: ansistring;
  3133. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  3134. GlobalType, GlobalMutabilityType: Byte;
  3135. begin
  3136. Result:=False;
  3137. if ImportSectionRead then
  3138. begin
  3139. InputError('Import section is duplicated');
  3140. exit;
  3141. end;
  3142. ImportSectionRead:=True;
  3143. if not ReadUleb32(ImportsCount) then
  3144. begin
  3145. InputError('Error reading the imports count');
  3146. exit;
  3147. end;
  3148. for i:=0 to ImportsCount-1 do
  3149. begin
  3150. if not ReadName(ModName) then
  3151. begin
  3152. InputError('Error reading import module name');
  3153. exit;
  3154. end;
  3155. if not ReadName(Name) then
  3156. begin
  3157. InputError('Error import name');
  3158. exit;
  3159. end;
  3160. if not AReader.Read(ImportType,1) then
  3161. begin
  3162. InputError('Error reading import type');
  3163. exit;
  3164. end;
  3165. case ImportType of
  3166. $00: { func }
  3167. begin
  3168. Inc(FuncTypeImportsCount);
  3169. SetLength(FuncTypes,FuncTypeImportsCount);
  3170. with FuncTypes[FuncTypeImportsCount-1] do
  3171. begin
  3172. IsImport:=True;
  3173. ImportName:=Name;
  3174. ImportModName:=ModName;
  3175. if not ReadUleb32(typidx) then
  3176. begin
  3177. InputError('Error reading type index for func import');
  3178. exit;
  3179. end;
  3180. if typidx>high(FFuncTypes) then
  3181. begin
  3182. InputError('Type index in func import exceeds bounds of the types table');
  3183. exit;
  3184. end;
  3185. end;
  3186. end;
  3187. $01: { table }
  3188. begin
  3189. Inc(TableTypeImportsCount);
  3190. SetLength(TableTypes,TableTypeImportsCount);
  3191. with TableTypes[TableTypeImportsCount-1] do
  3192. begin
  3193. IsImport:=True;
  3194. ImportName:=Name;
  3195. ImportModName:=ModName;
  3196. if not AReader.read(TableElemTyp,1) then
  3197. begin
  3198. InputError('Error reading table element type for table import');
  3199. exit;
  3200. end;
  3201. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  3202. begin
  3203. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  3204. exit;
  3205. end;
  3206. if not (reftype in WasmReferenceTypes) then
  3207. begin
  3208. InputError('Table element type for table import must be a reference type');
  3209. exit;
  3210. end;
  3211. if not AReader.read(TableLimitsKind,1) then
  3212. begin
  3213. InputError('Error reading table limits kind for table import');
  3214. exit;
  3215. end;
  3216. case TableLimitsKind of
  3217. $00:
  3218. begin
  3219. limits.HasMax:=False;
  3220. limits.Max:=high(limits.Max);
  3221. if not ReadUleb32(limits.min) then
  3222. begin
  3223. InputError('Error reading table limits min for table import');
  3224. exit;
  3225. end;
  3226. end;
  3227. $01:
  3228. begin
  3229. limits.HasMax:=True;
  3230. if not ReadUleb32(limits.min) then
  3231. begin
  3232. InputError('Error reading table limits min for table import');
  3233. exit;
  3234. end;
  3235. if not ReadUleb32(limits.max) then
  3236. begin
  3237. InputError('Error reading table limits max for table import');
  3238. exit;
  3239. end;
  3240. if limits.min>limits.max then
  3241. begin
  3242. InputError('Table limits min exceed table limits max in table import');
  3243. exit;
  3244. end;
  3245. end;
  3246. else
  3247. begin
  3248. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  3249. exit;
  3250. end;
  3251. end;
  3252. end;
  3253. end;
  3254. $02: { mem }
  3255. begin
  3256. Inc(MemTypeImportsCount);
  3257. SetLength(MemTypes,MemTypeImportsCount);
  3258. with MemTypes[MemTypeImportsCount-1] do
  3259. begin
  3260. IsImport:=True;
  3261. ImportName:=Name;
  3262. ImportModName:=ModName;
  3263. if not AReader.read(MemoryLimitsKind,1) then
  3264. begin
  3265. InputError('Error reading memory limits kind for memory import');
  3266. exit;
  3267. end;
  3268. case MemoryLimitsKind of
  3269. $00:
  3270. begin
  3271. limits.HasMax:=False;
  3272. limits.Max:=high(limits.Max);
  3273. if not ReadUleb32(limits.min) then
  3274. begin
  3275. InputError('Error reading memory limits min for memory import');
  3276. exit;
  3277. end;
  3278. end;
  3279. $01:
  3280. begin
  3281. limits.HasMax:=True;
  3282. if not ReadUleb32(limits.min) then
  3283. begin
  3284. InputError('Error reading memory limits min for memory import');
  3285. exit;
  3286. end;
  3287. if not ReadUleb32(limits.max) then
  3288. begin
  3289. InputError('Error reading memory limits max for memory import');
  3290. exit;
  3291. end;
  3292. if limits.Min>limits.Max then
  3293. begin
  3294. InputError('Memory limits min exceed memory limits max in memory import');
  3295. exit;
  3296. end;
  3297. end;
  3298. else
  3299. begin
  3300. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  3301. exit;
  3302. end;
  3303. end;
  3304. end;
  3305. end;
  3306. $03: { global }
  3307. begin
  3308. Inc(GlobalTypeImportsCount);
  3309. SetLength(GlobalTypes,GlobalTypeImportsCount);
  3310. with GlobalTypes[GlobalTypeImportsCount-1] do
  3311. begin
  3312. IsImport:=True;
  3313. ImportName:=Name;
  3314. ImportModName:=ModName;
  3315. if not AReader.read(GlobalType,1) then
  3316. begin
  3317. InputError('Error reading global type for global import');
  3318. exit;
  3319. end;
  3320. if not decode_wasm_basic_type(GlobalType,valtype) then
  3321. begin
  3322. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  3323. exit;
  3324. end;
  3325. if not AReader.read(GlobalMutabilityType,1) then
  3326. begin
  3327. InputError('Error reading global mutability flag for global import');
  3328. exit;
  3329. end;
  3330. case GlobalMutabilityType of
  3331. $00:
  3332. IsMutable:=False;
  3333. $01:
  3334. IsMutable:=True;
  3335. else
  3336. begin
  3337. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  3338. exit;
  3339. end;
  3340. end;
  3341. end;
  3342. end;
  3343. $04: { tag }
  3344. begin
  3345. Inc(TagTypeImportsCount);
  3346. SetLength(TagTypes,TagTypeImportsCount);
  3347. with TagTypes[TagTypeImportsCount-1] do
  3348. begin
  3349. IsImport:=True;
  3350. ImportName:=Name;
  3351. ImportModName:=ModName;
  3352. if not Read(TagAttr,1) then
  3353. begin
  3354. InputError('Error reading import tag attribute');
  3355. exit;
  3356. end;
  3357. if not ReadUleb32(TagTypeIdx) then
  3358. begin
  3359. InputError('Error reading import tag type index');
  3360. exit;
  3361. end;
  3362. if TagTypeIdx>high(FFuncTypes) then
  3363. begin
  3364. InputError('Type index in tag import exceeds bounds of the types table');
  3365. exit;
  3366. end;
  3367. end;
  3368. end;
  3369. else
  3370. begin
  3371. InputError('Unknown import type: $' + HexStr(ImportType,2));
  3372. exit;
  3373. end;
  3374. end;
  3375. end;
  3376. if AReader.Pos<>(SectionStart+SectionSize) then
  3377. begin
  3378. InputError('Unexpected import section size');
  3379. exit;
  3380. end;
  3381. Result:=true;
  3382. end;
  3383. function ReadFunctionSection: Boolean;
  3384. var
  3385. FunctionsCount: uint32;
  3386. i: Integer;
  3387. begin
  3388. Result:=False;
  3389. if FunctionSectionRead then
  3390. begin
  3391. InputError('Function section is duplicated');
  3392. exit;
  3393. end;
  3394. FunctionSectionRead:=True;
  3395. if not ReadUleb32(FunctionsCount) then
  3396. begin
  3397. InputError('Error reading the functions count');
  3398. exit;
  3399. end;
  3400. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  3401. for i:=0 to FunctionsCount-1 do
  3402. with FuncTypes[i + FuncTypeImportsCount] do
  3403. begin
  3404. IsImport:=False;
  3405. if not ReadUleb32(typidx) then
  3406. begin
  3407. InputError('Error reading type index for function');
  3408. exit;
  3409. end;
  3410. if typidx>high(FFuncTypes) then
  3411. begin
  3412. InputError('Type index in the function section exceeds bounds of the types table');
  3413. exit;
  3414. end;
  3415. end;
  3416. if AReader.Pos<>(SectionStart+SectionSize) then
  3417. begin
  3418. InputError('Unexpected function section size');
  3419. exit;
  3420. end;
  3421. Result:=true;
  3422. end;
  3423. function ReadGlobalSection: Boolean;
  3424. function ParseExpr(out Init: TGlobalInitializer): Boolean;
  3425. var
  3426. B, B2: Byte;
  3427. tmpU32: UInt32;
  3428. tmpU64: UInt64;
  3429. begin
  3430. Result:=False;
  3431. repeat
  3432. if not Read(B, 1) then
  3433. exit;
  3434. case B of
  3435. $0B: { end }
  3436. ;
  3437. $41: { i32.const }
  3438. begin
  3439. Init.typ:=wbt_i32;
  3440. if not ReadSleb32(Init.init_i32) then
  3441. exit;
  3442. end;
  3443. $42: { i64.const }
  3444. begin
  3445. Init.typ:=wbt_i64;
  3446. if not ReadSleb(Init.init_i64) then
  3447. exit;
  3448. end;
  3449. $43: { f32.const }
  3450. begin
  3451. Init.typ:=wbt_f32;
  3452. if not Read(tmpU32, 4) then
  3453. exit;
  3454. {$ifdef FPC_BIG_ENDIAN}
  3455. tmpU32:=SwapEndian(tmpU32);
  3456. {$endif FPC_BIG_ENDIAN}
  3457. Move(tmpU32,Init.init_f32,4);
  3458. end;
  3459. $44: { f64.const }
  3460. begin
  3461. Init.typ:=wbt_f64;
  3462. if not Read(tmpU64, 8) then
  3463. exit;
  3464. {$ifdef FPC_BIG_ENDIAN}
  3465. tmpU64:=SwapEndian(tmpU64);
  3466. {$endif FPC_BIG_ENDIAN}
  3467. Move(tmpU64,Init.init_f64,8);
  3468. end;
  3469. $D0: { ref.null }
  3470. begin
  3471. if not Read(B2, 1) then
  3472. exit;
  3473. if not decode_wasm_basic_type(B2, Init.typ) then
  3474. exit;
  3475. if not (Init.typ in WasmReferenceTypes) then
  3476. exit;
  3477. end;
  3478. else
  3479. begin
  3480. InputError('Unsupported opcode in global initializer');
  3481. exit;
  3482. end;
  3483. end;
  3484. until b = $0B;
  3485. Result:=True;
  3486. end;
  3487. var
  3488. GlobalsCount: uint32;
  3489. i: Integer;
  3490. vt: Byte;
  3491. mut: Byte;
  3492. begin
  3493. Result:=False;
  3494. if GlobalSectionRead then
  3495. begin
  3496. InputError('Global section is duplicated');
  3497. exit;
  3498. end;
  3499. GlobalSectionRead:=True;
  3500. if not ReadUleb32(GlobalsCount) then
  3501. begin
  3502. InputError('Error reading the globals count from the global section');
  3503. exit;
  3504. end;
  3505. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  3506. for i:=0 to GlobalsCount-1 do
  3507. with GlobalTypes[i + GlobalTypeImportsCount] do
  3508. begin
  3509. if not read(vt,1) then
  3510. begin
  3511. InputError('Error reading the type of a global from the global section');
  3512. exit;
  3513. end;
  3514. if not decode_wasm_basic_type(vt,valtype) then
  3515. begin
  3516. InputError('Unsupported type of global in the global section');
  3517. exit;
  3518. end;
  3519. if not read(mut,1) then
  3520. begin
  3521. InputError('Error reading the mutability flag of a global in the global section');
  3522. exit;
  3523. end;
  3524. case mut of
  3525. $00:
  3526. IsMutable:=False;
  3527. $01:
  3528. IsMutable:=True;
  3529. else
  3530. begin
  3531. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  3532. exit;
  3533. end;
  3534. end;
  3535. if not ParseExpr(GlobalInit) then
  3536. begin
  3537. InputError('Error parsing the global initializer expression in the global section');
  3538. exit;
  3539. end;
  3540. if GlobalInit.typ<>valtype then
  3541. begin
  3542. InputError('Initializer expression for global produces a type, which does not match the type of the global');
  3543. exit;
  3544. end;
  3545. end;
  3546. if AReader.Pos<>(SectionStart+SectionSize) then
  3547. begin
  3548. InputError('Unexpected global section size');
  3549. exit;
  3550. end;
  3551. Result:=True;
  3552. end;
  3553. function ReadExportSection: Boolean;
  3554. var
  3555. ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx, TagIdx: uint32;
  3556. i: Integer;
  3557. Name: ansistring;
  3558. ExportType: Byte;
  3559. begin
  3560. Result:=False;
  3561. if ExportSectionRead then
  3562. begin
  3563. InputError('Export section is duplicated');
  3564. exit;
  3565. end;
  3566. ExportSectionRead:=True;
  3567. if not ReadUleb32(ExportsCount) then
  3568. begin
  3569. InputError('Error reading the exports count from the export section');
  3570. exit;
  3571. end;
  3572. for i:=0 to ExportsCount-1 do
  3573. begin
  3574. if not ReadName(Name) then
  3575. begin
  3576. InputError('Error reading an export name from the export section');
  3577. exit;
  3578. end;
  3579. if not Read(ExportType,1) then
  3580. begin
  3581. InputError('Error reading an export type from the export section');
  3582. exit;
  3583. end;
  3584. case ExportType of
  3585. $00: { func }
  3586. begin
  3587. if not ReadUleb32(FuncIdx) then
  3588. begin
  3589. InputError('Error reading a func index from the export section');
  3590. exit;
  3591. end;
  3592. if FuncIdx>high(FuncTypes) then
  3593. begin
  3594. InputError('Func index too high in the export section');
  3595. exit;
  3596. end;
  3597. with FuncTypes[FuncIdx] do
  3598. begin
  3599. IsExported:=True;
  3600. ExportName:=Name;
  3601. end;
  3602. end;
  3603. $01: { table }
  3604. begin
  3605. if not ReadUleb32(TableIdx) then
  3606. begin
  3607. InputError('Error reading a table index from the export section');
  3608. exit;
  3609. end;
  3610. if TableIdx>high(TableTypes) then
  3611. begin
  3612. InputError('Table index too high in the export section');
  3613. exit;
  3614. end;
  3615. with TableTypes[TableIdx] do
  3616. begin
  3617. IsExported:=True;
  3618. ExportName:=Name;
  3619. end;
  3620. end;
  3621. $02: { mem }
  3622. begin
  3623. if not ReadUleb32(MemIdx) then
  3624. begin
  3625. InputError('Error reading a mem index from the export section');
  3626. exit;
  3627. end;
  3628. if MemIdx>high(MemTypes) then
  3629. begin
  3630. InputError('Mem index too high in the export section');
  3631. exit;
  3632. end;
  3633. with MemTypes[MemIdx] do
  3634. begin
  3635. IsExported:=True;
  3636. ExportName:=Name;
  3637. end;
  3638. end;
  3639. $03: { global }
  3640. begin
  3641. if not ReadUleb32(GlobalIdx) then
  3642. begin
  3643. InputError('Error reading a global index from the export section');
  3644. exit;
  3645. end;
  3646. if GlobalIdx>high(GlobalTypes) then
  3647. begin
  3648. InputError('Global index too high in the export section');
  3649. exit;
  3650. end;
  3651. with GlobalTypes[GlobalIdx] do
  3652. begin
  3653. IsExported:=True;
  3654. ExportName:=Name;
  3655. end;
  3656. end;
  3657. $04: { tag }
  3658. begin
  3659. if not ReadUleb32(TagIdx) then
  3660. begin
  3661. InputError('Error reading a tag index from the export section');
  3662. exit;
  3663. end;
  3664. if TagIdx>high(TagTypes) then
  3665. begin
  3666. InputError('Tag index too high in the export section');
  3667. exit;
  3668. end;
  3669. with TagTypes[TagIdx] do
  3670. begin
  3671. IsExported:=True;
  3672. ExportName:=Name;
  3673. end;
  3674. end;
  3675. else
  3676. begin
  3677. InputError('Unsupported export type in the export section: ' + tostr(ExportType));
  3678. exit;
  3679. end;
  3680. end;
  3681. end;
  3682. if AReader.Pos<>(SectionStart+SectionSize) then
  3683. begin
  3684. InputError('Unexpected export section size');
  3685. exit;
  3686. end;
  3687. Result:=True;
  3688. end;
  3689. function ReadElementSection: Boolean;
  3690. begin
  3691. Result:=False;
  3692. if ElementSectionRead then
  3693. begin
  3694. InputError('Element section is duplicated');
  3695. exit;
  3696. end;
  3697. ElementSectionRead:=True;
  3698. { We skip the element section for now }
  3699. { TODO: implement reading it (and linking of tables) }
  3700. Result:=True;
  3701. end;
  3702. function ReadTagSection: Boolean;
  3703. var
  3704. TagCount: uint32;
  3705. i: Integer;
  3706. begin
  3707. Result:=False;
  3708. if TagSectionRead then
  3709. begin
  3710. InputError('Tag section is duplicated');
  3711. exit;
  3712. end;
  3713. TagSectionRead:=True;
  3714. if not ReadUleb32(TagCount) then
  3715. begin
  3716. InputError('Error reading the tag count from the tag section');
  3717. exit;
  3718. end;
  3719. SetLength(TagTypes,Length(TagTypes)+TagCount);
  3720. for i:=0 to TagCount-1 do
  3721. with TagTypes[i + TagTypeImportsCount] do
  3722. begin
  3723. if not Read(TagAttr,1) then
  3724. begin
  3725. InputError('Error reading tag attribute');
  3726. exit;
  3727. end;
  3728. if not ReadUleb32(TagTypeIdx) then
  3729. begin
  3730. InputError('Error reading tag type index');
  3731. exit;
  3732. end;
  3733. if TagTypeIdx>high(FFuncTypes) then
  3734. begin
  3735. InputError('Type index in tag import exceeds bounds of the types table');
  3736. exit;
  3737. end;
  3738. end;
  3739. if AReader.Pos<>(SectionStart+SectionSize) then
  3740. begin
  3741. InputError('Unexpected tag section size');
  3742. exit;
  3743. end;
  3744. Result:=True;
  3745. end;
  3746. function ReadCodeSection: Boolean;
  3747. var
  3748. CodeEntriesCount: uint32;
  3749. i: Integer;
  3750. begin
  3751. Result:=False;
  3752. if CodeSectionRead then
  3753. begin
  3754. InputError('Code section is duplicated');
  3755. exit;
  3756. end;
  3757. CodeSectionRead:=True;
  3758. CodeSectionIndex:=SectionIndex;
  3759. if not ReadUleb32(CodeEntriesCount) then
  3760. begin
  3761. InputError('Error reading the code entries cound from the code section');
  3762. exit;
  3763. end;
  3764. if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
  3765. begin
  3766. InputError('Code segment count in the code section does not match the function definition count in the function section');
  3767. exit;
  3768. end;
  3769. SetLength(CodeSegments,CodeEntriesCount);
  3770. for i:=0 to CodeEntriesCount-1 do
  3771. with CodeSegments[i] do
  3772. begin
  3773. if not ReadUleb32(CodeSize) then
  3774. begin
  3775. InputError('Error reading the code size of an entry in the code section');
  3776. exit;
  3777. end;
  3778. if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
  3779. begin
  3780. InputError('Code segment exceeds the bounds of the code section');
  3781. exit;
  3782. end;
  3783. DataPos:=AReader.Pos;
  3784. CodeSectionOffset:=AReader.Pos-SectionStart;
  3785. AReader.Seek(AReader.Pos+CodeSize);
  3786. end;
  3787. if AReader.Pos<>(SectionStart+SectionSize) then
  3788. begin
  3789. InputError('Unexpected code section size');
  3790. exit;
  3791. end;
  3792. Result:=true;
  3793. end;
  3794. function ReadDataSection: Boolean;
  3795. function ReadExpr(out ExprV: int32): Boolean;
  3796. var
  3797. b: Byte;
  3798. begin
  3799. Result:=False;
  3800. if not Read(b,1) then
  3801. exit;
  3802. if b<>$41 then
  3803. begin
  3804. InputError('Only i32.const expressions supported');
  3805. exit;
  3806. end;
  3807. if not ReadSleb32(ExprV) then
  3808. exit;
  3809. if not Read(b,1) then
  3810. exit;
  3811. if b<>$0B then
  3812. begin
  3813. InputError('Only single const expressions supported');
  3814. exit;
  3815. end;
  3816. Result:=True;
  3817. end;
  3818. var
  3819. DataCount: uint32;
  3820. DataType: Byte;
  3821. i: Integer;
  3822. begin
  3823. Result:=False;
  3824. if DataSectionRead then
  3825. begin
  3826. InputError('Data section is duplicated');
  3827. exit;
  3828. end;
  3829. DataSectionRead:=True;
  3830. DataSectionIndex:=SectionIndex;
  3831. if not ReadUleb32(DataCount) then
  3832. begin
  3833. InputError('Error reading the data entries count from the data section');
  3834. exit;
  3835. end;
  3836. if DataCountSectionRead then
  3837. begin
  3838. if Length(DataSegments)<>DataCount then
  3839. begin
  3840. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  3841. exit;
  3842. end;
  3843. end
  3844. else
  3845. SetLength(DataSegments,DataCount);
  3846. for i:=0 to DataCount-1 do
  3847. with DataSegments[i] do
  3848. begin
  3849. if not read(DataType, 1) then
  3850. begin
  3851. InputError('Error reading data type of segment from the data section');
  3852. exit;
  3853. end;
  3854. case DataType of
  3855. 0:
  3856. begin
  3857. Active:=True;
  3858. MemIdx:=0;
  3859. if not ReadExpr(Offset) then
  3860. begin
  3861. InputError('Error reading memory offset of segment from the data section');
  3862. exit;
  3863. end;
  3864. end;
  3865. 1:
  3866. Active:=False;
  3867. 2:
  3868. begin
  3869. Active:=True;
  3870. if not ReadUleb32(MemIdx) then
  3871. begin
  3872. InputError('Error reading MemIdx of segment from the data section');
  3873. exit;
  3874. end;
  3875. if not ReadExpr(Offset) then
  3876. begin
  3877. InputError('Error reading memory offset of segment from the data section');
  3878. exit;
  3879. end;
  3880. end;
  3881. else
  3882. begin
  3883. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3884. exit;
  3885. end;
  3886. end;
  3887. if MemIdx<>0 then
  3888. begin
  3889. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3890. exit;
  3891. end;
  3892. if not Active then
  3893. begin
  3894. InputError('Passive memory segments not supported');
  3895. exit;
  3896. end;
  3897. if not ReadUleb32(Len) then
  3898. begin
  3899. InputError('Error reading data segment length');
  3900. exit;
  3901. end;
  3902. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3903. begin
  3904. InputError('Data segment exceeds the bounds of the data section');
  3905. exit;
  3906. end;
  3907. DataPos:=AReader.Pos;
  3908. DataSectionOffset:=AReader.Pos-SectionStart;
  3909. AReader.Seek(AReader.Pos+Len);
  3910. end;
  3911. if AReader.Pos<>(SectionStart+SectionSize) then
  3912. begin
  3913. InputError('Unexpected data section size');
  3914. exit;
  3915. end;
  3916. Result:=true;
  3917. end;
  3918. function ReadDataCountSection: Boolean;
  3919. var
  3920. DataCount: uint32;
  3921. begin
  3922. Result:=False;
  3923. if DataCountSectionRead then
  3924. begin
  3925. InputError('Data count section is duplicated');
  3926. exit;
  3927. end;
  3928. DataCountSectionRead:=True;
  3929. if DataSectionRead then
  3930. begin
  3931. InputError('The data count section must occur before the data section');
  3932. exit;
  3933. end;
  3934. if not ReadUleb32(DataCount) then
  3935. begin
  3936. InputError('Error reading the data count from the data count section');
  3937. exit;
  3938. end;
  3939. if AReader.Pos<>(SectionStart+SectionSize) then
  3940. begin
  3941. InputError('Unexpected data count section size');
  3942. exit;
  3943. end;
  3944. SetLength(DataSegments, DataCount);
  3945. Result:=true;
  3946. end;
  3947. begin
  3948. Result:=False;
  3949. Inc(SectionIndex);
  3950. if not AReader.read(SectionId,1) then
  3951. begin
  3952. InputError('Error reading section ID');
  3953. exit;
  3954. end;
  3955. CheckSectionBounds:=false;
  3956. if not ReadUleb32(SectionSize) then
  3957. begin
  3958. InputError('Error reading section size');
  3959. exit;
  3960. end;
  3961. if (AReader.Pos+SectionSize)>AReader.size then
  3962. begin
  3963. InputError('Section exceeds beyond the end of file');
  3964. exit;
  3965. end;
  3966. SectionStart:=AReader.Pos;
  3967. CheckSectionBounds:=true;
  3968. case SectionId of
  3969. Byte(wsiCustom):
  3970. if not ReadCustomSection then
  3971. begin
  3972. InputError('Error encountered, while reading a custom section');
  3973. exit;
  3974. end;
  3975. Byte(wsiType):
  3976. if not ReadTypeSection then
  3977. begin
  3978. InputError('Error reading the type section');
  3979. exit;
  3980. end;
  3981. Byte(wsiImport):
  3982. if not ReadImportSection then
  3983. begin
  3984. InputError('Error reading the import section');
  3985. exit;
  3986. end;
  3987. Byte(wsiFunction):
  3988. if not ReadFunctionSection then
  3989. begin
  3990. InputError('Error reading the function section');
  3991. exit;
  3992. end;
  3993. Byte(wsiGlobal):
  3994. if not ReadGlobalSection then
  3995. begin
  3996. InputError('Error reading the global section');
  3997. exit;
  3998. end;
  3999. Byte(wsiExport):
  4000. if not ReadExportSection then
  4001. begin
  4002. InputError('Error reading the export section');
  4003. exit;
  4004. end;
  4005. Byte(wsiElement):
  4006. if not ReadElementSection then
  4007. begin
  4008. InputError('Error reading the element section');
  4009. exit;
  4010. end;
  4011. Byte(wsiTag):
  4012. if not ReadTagSection then
  4013. begin
  4014. InputError('Error reading the tag section');
  4015. exit;
  4016. end;
  4017. Byte(wsiCode):
  4018. if not ReadCodeSection then
  4019. begin
  4020. InputError('Error reading the code section');
  4021. exit;
  4022. end;
  4023. Byte(wsiData):
  4024. if not ReadDataSection then
  4025. begin
  4026. InputError('Error reading the data section');
  4027. exit;
  4028. end;
  4029. Byte(wsiDataCount):
  4030. begin
  4031. if not ReadDataCountSection then
  4032. begin
  4033. InputError('Error reading the data count section');
  4034. exit;
  4035. end;
  4036. end
  4037. else
  4038. begin
  4039. InputError('Unknown section: ' + ToStr(SectionId));
  4040. exit;
  4041. end;
  4042. end;
  4043. if SectionSize>0 then
  4044. AReader.seek(SectionStart+SectionSize);
  4045. Result:=True;
  4046. end;
  4047. function FindCodeSegment(Ofs: uint32): Integer;
  4048. var
  4049. L, R, M: Integer;
  4050. begin
  4051. L:=Low(CodeSegments);
  4052. R:=High(CodeSegments);
  4053. while L<=R do
  4054. begin
  4055. M:=(L+R) div 2;
  4056. if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
  4057. L:=M+1
  4058. else if CodeSegments[M].CodeSectionOffset > Ofs then
  4059. R:=M-1
  4060. else
  4061. begin
  4062. Result:=M;
  4063. exit;
  4064. end;
  4065. end;
  4066. Result:=-1;
  4067. end;
  4068. function FindDataSegment(Ofs: uint32): Integer;
  4069. var
  4070. L, R, M: Integer;
  4071. begin
  4072. L:=Low(DataSegments);
  4073. R:=High(DataSegments);
  4074. while L<=R do
  4075. begin
  4076. M:=(L+R) div 2;
  4077. if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
  4078. L:=M+1
  4079. else if DataSegments[M].DataSectionOffset > Ofs then
  4080. R:=M-1
  4081. else
  4082. begin
  4083. Result:=M;
  4084. exit;
  4085. end;
  4086. end;
  4087. Result:=-1;
  4088. end;
  4089. var
  4090. ModuleMagic: array [0..3] of Byte;
  4091. ModuleVersion: array [0..3] of Byte;
  4092. i, j, FirstCodeSegmentIdx, FirstDataSegmentIdx, SegI: Integer;
  4093. CurrSec, ObjSec: TObjSection;
  4094. BaseSectionOffset: UInt32;
  4095. ObjReloc: TWasmObjRelocation;
  4096. ds: TWasmCustomDebugSectionType;
  4097. begin
  4098. FReader:=AReader;
  4099. InputFileName:=AReader.FileName;
  4100. objdata:=CObjData.Create(InputFileName);
  4101. result:=false;
  4102. CodeSegments:=nil;
  4103. DataSegments:=nil;
  4104. SymbolTable:=nil;
  4105. RelocationTable:=nil;
  4106. SetLength(RelocationTable,2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))+1));
  4107. FuncTypes:=nil;
  4108. FuncTypeImportsCount:=0;
  4109. TableTypes:=nil;
  4110. TableTypeImportsCount:=0;
  4111. MemTypes:=nil;
  4112. MemTypeImportsCount:=0;
  4113. GlobalTypes:=nil;
  4114. GlobalTypeImportsCount:=0;
  4115. TagTypes:=nil;
  4116. TagTypeImportsCount:=0;
  4117. if not AReader.read(ModuleMagic,4) then
  4118. exit;
  4119. for i:=0 to 3 do
  4120. if ModuleMagic[i]<>WasmModuleMagic[i] then
  4121. exit;
  4122. if not AReader.read(ModuleVersion,4) then
  4123. exit;
  4124. for i:=0 to 3 do
  4125. if ModuleVersion[i]<>WasmVersion[i] then
  4126. exit;
  4127. while AReader.Pos<AReader.size do
  4128. if not ReadSection then
  4129. exit;
  4130. { fill the code segment names }
  4131. for i:=low(SymbolTable) to high(SymbolTable) do
  4132. with SymbolTable[i] do
  4133. if (SymKind=SYMTAB_FUNCTION) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  4134. begin
  4135. if FuncTypes[SymIndex].IsImport then
  4136. begin
  4137. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  4138. exit;
  4139. end;
  4140. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4141. begin
  4142. with CodeSegments[SymIndex-FuncTypeImportsCount] do
  4143. begin
  4144. SegName:='.text.n_'+SymName;
  4145. SegIsExported:=FuncTypes[SymIndex].IsExported;
  4146. end;
  4147. end;
  4148. end;
  4149. { create segments }
  4150. FirstCodeSegmentIdx:=ObjData.ObjSectionList.Count;
  4151. for i:=low(CodeSegments) to high(CodeSegments) do
  4152. with CodeSegments[i] do
  4153. begin
  4154. if SegName='' then
  4155. begin
  4156. InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
  4157. exit;
  4158. end;
  4159. if SegIsExported or not (cs_link_smart in current_settings.globalswitches) then
  4160. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
  4161. else
  4162. CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
  4163. CurrSec.DataPos:=DataPos;
  4164. CurrSec.Size:=CodeSize;
  4165. end;
  4166. FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
  4167. for i:=low(DataSegments) to high(DataSegments) do
  4168. with DataSegments[i] do
  4169. if Active then
  4170. begin
  4171. if not (cs_link_smart in current_settings.globalswitches) then
  4172. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write,oso_keep],false)
  4173. else
  4174. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  4175. CurrSec.DataPos:=DataPos;
  4176. CurrSec.MemPos:=Offset;
  4177. CurrSec.Size:=Len;
  4178. end;
  4179. ReadSectionContent(ObjData);
  4180. for i:=low(SymbolTable) to high(SymbolTable) do
  4181. with SymbolTable[i] do
  4182. case SymKind of
  4183. SYMTAB_DATA:
  4184. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4185. begin
  4186. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4187. objsym.bind:=AB_EXTERNAL;
  4188. if (SymFlags and WASM_SYM_TLS)<>0 then
  4189. begin
  4190. objsym.typ:=AT_TLS;
  4191. objsym.TlsGlobalSym:=TWasmObjSymbol(ObjData.CreateSymbol('GOT.mem.'+SymName));
  4192. objsym.TlsGlobalSym.TlsDataSym:=objsym;
  4193. objsym.TlsGlobalSym.bind:=AB_EXTERNAL;
  4194. objsym.TlsGlobalSym.typ:=AT_WASM_GLOBAL;
  4195. objsym.TlsGlobalSym.objsection:=nil;
  4196. objsym.TlsGlobalSym.offset:=0;
  4197. objsym.TlsGlobalSym.size:=1;
  4198. objsym.TlsGlobalSym.LinkingData.GlobalType:=wbt_i32;
  4199. objsym.TlsGlobalSym.LinkingData.GlobalIsMutable:=true;
  4200. end
  4201. else
  4202. objsym.typ:=AT_DATA;
  4203. objsym.objsection:=nil;
  4204. objsym.offset:=0;
  4205. objsym.size:=0;
  4206. end
  4207. else
  4208. begin
  4209. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4210. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  4211. objsym.bind:=AB_LOCAL
  4212. else
  4213. objsym.bind:=AB_GLOBAL;
  4214. if (SymFlags and WASM_SYM_TLS)<>0 then
  4215. begin
  4216. objsym.typ:=AT_TLS;
  4217. objsym.TlsGlobalSym:=TWasmObjSymbol(ObjData.CreateSymbol('GOT.mem.'+SymName));
  4218. objsym.TlsGlobalSym.TlsDataSym:=objsym;
  4219. objsym.TlsGlobalSym.bind:=objsym.bind;
  4220. objsym.TlsGlobalSym.typ:=AT_WASM_GLOBAL;
  4221. objsym.TlsGlobalSym.objsection:=ObjData.createsection('.wasm_globals.n_'+objsym.TlsGlobalSym.Name,1,[oso_Data,oso_load],true);
  4222. if objsym.TlsGlobalSym.objsection.Size=0 then
  4223. objsym.TlsGlobalSym.objsection.WriteZeros(1);
  4224. TWasmObjSection(objsym.TlsGlobalSym.objsection).MainFuncSymbol:=objsym.TlsGlobalSym;
  4225. objsym.TlsGlobalSym.offset:=0;
  4226. objsym.TlsGlobalSym.size:=1;
  4227. objsym.TlsGlobalSym.LinkingData.GlobalType:=wbt_i32;
  4228. objsym.TlsGlobalSym.LinkingData.GlobalIsMutable:=true;
  4229. end
  4230. else
  4231. objsym.typ:=AT_DATA;
  4232. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
  4233. objsym.offset:=SymOffset;
  4234. objsym.size:=SymSize;
  4235. end;
  4236. SYMTAB_FPC_CUSTOM:
  4237. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4238. begin
  4239. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4240. objsym.bind:=AB_EXTERNAL;
  4241. if (SymFlags and WASM_SYM_TLS)<>0 then
  4242. internalerror(2024080702);
  4243. objsym.typ:=AT_DATA;
  4244. objsym.objsection:=nil;
  4245. objsym.offset:=0;
  4246. objsym.size:=0;
  4247. end
  4248. else
  4249. begin
  4250. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4251. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  4252. objsym.bind:=AB_LOCAL
  4253. else
  4254. objsym.bind:=AB_GLOBAL;
  4255. if (SymFlags and WASM_SYM_TLS)<>0 then
  4256. internalerror(2024080703);
  4257. objsym.typ:=AT_DATA;
  4258. objsym.objsection:=TObjSection(ObjData.ObjSectionList.Find(WasmCustomSectionName[SymCustomSectionType]));
  4259. objsym.offset:=SymOffset;
  4260. objsym.size:=SymSize;
  4261. end;
  4262. SYMTAB_FUNCTION:
  4263. begin
  4264. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4265. begin
  4266. if not FuncTypes[SymIndex].IsImport then
  4267. begin
  4268. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  4269. exit;
  4270. end;
  4271. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4272. begin
  4273. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4274. objsym.bind:=AB_EXTERNAL;
  4275. objsym.typ:=AT_FUNCTION;
  4276. objsym.objsection:=nil;
  4277. objsym.offset:=0;
  4278. objsym.size:=0;
  4279. objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
  4280. objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
  4281. end
  4282. else
  4283. begin
  4284. if FuncTypes[SymIndex].ImportModName = 'env' then
  4285. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
  4286. else
  4287. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
  4288. objsym.bind:=AB_EXTERNAL;
  4289. objsym.typ:=AT_FUNCTION;
  4290. objsym.objsection:=nil;
  4291. objsym.offset:=0;
  4292. objsym.size:=0;
  4293. end;
  4294. end
  4295. else
  4296. begin
  4297. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4298. objsym.bind:=AB_GLOBAL;
  4299. objsym.typ:=AT_FUNCTION;
  4300. objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]);
  4301. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4302. TWasmObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
  4303. objsym.offset:=0;
  4304. objsym.size:=objsym.objsection.Size;
  4305. end;
  4306. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
  4307. objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
  4308. objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
  4309. end;
  4310. SYMTAB_GLOBAL:
  4311. begin
  4312. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4313. begin
  4314. if not GlobalTypes[SymIndex].IsImport then
  4315. begin
  4316. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
  4317. exit;
  4318. end;
  4319. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4320. begin
  4321. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4322. objsym.bind:=AB_EXTERNAL;
  4323. objsym.typ:=AT_WASM_GLOBAL;
  4324. objsym.objsection:=nil;
  4325. objsym.offset:=0;
  4326. objsym.size:=1;
  4327. objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
  4328. objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
  4329. end
  4330. else
  4331. begin
  4332. if GlobalTypes[SymIndex].ImportModName = 'env' then
  4333. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  4334. else
  4335. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  4336. objsym.bind:=AB_EXTERNAL;
  4337. objsym.typ:=AT_WASM_GLOBAL;
  4338. objsym.objsection:=nil;
  4339. objsym.offset:=0;
  4340. objsym.size:=1;
  4341. end;
  4342. end
  4343. else
  4344. begin
  4345. if GlobalTypes[SymIndex].IsImport then
  4346. begin
  4347. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
  4348. exit;
  4349. end;
  4350. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4351. objsym.bind:=AB_GLOBAL;
  4352. objsym.typ:=AT_WASM_GLOBAL;
  4353. objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
  4354. if objsym.objsection.Size=0 then
  4355. objsym.objsection.WriteZeros(1);
  4356. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4357. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  4358. objsym.offset:=0;
  4359. objsym.size:=1;
  4360. objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
  4361. end;
  4362. objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
  4363. objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
  4364. objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
  4365. objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
  4366. end;
  4367. SYMTAB_SECTION:
  4368. begin
  4369. for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
  4370. if DebugSectionIndex[ds]=TargetSection then
  4371. begin
  4372. ObjSec:=TWasmObjSection(ObjData.findsection(WasmCustomSectionName[ds]));
  4373. break;
  4374. end;
  4375. if ObjSec=nil then
  4376. begin
  4377. InputError('SYMTAB_SECTION entry points to an unsupported section');
  4378. exit;
  4379. end;
  4380. end;
  4381. SYMTAB_EVENT:
  4382. begin
  4383. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  4384. begin
  4385. if not TagTypes[SymIndex].IsImport then
  4386. begin
  4387. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_EVENT symbol, that is not an import');
  4388. exit;
  4389. end;
  4390. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  4391. begin
  4392. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4393. objsym.bind:=AB_EXTERNAL;
  4394. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4395. objsym.objsection:=nil;
  4396. objsym.offset:=0;
  4397. objsym.size:=1;
  4398. objsym.LinkingData.ImportModule:=TagTypes[SymIndex].ImportModName;
  4399. objsym.LinkingData.ImportName:=TagTypes[SymIndex].ImportName;
  4400. end
  4401. else
  4402. begin
  4403. if GlobalTypes[SymIndex].ImportModName = 'env' then
  4404. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
  4405. else
  4406. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
  4407. objsym.bind:=AB_EXTERNAL;
  4408. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4409. objsym.objsection:=nil;
  4410. objsym.offset:=0;
  4411. objsym.size:=1;
  4412. end;
  4413. end
  4414. else
  4415. begin
  4416. if TagTypes[SymIndex].IsImport then
  4417. begin
  4418. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_EVENT symbol, that is an import');
  4419. exit;
  4420. end;
  4421. objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
  4422. if (symflags and WASM_SYM_BINDING_WEAK) <> 0 then
  4423. objsym.bind:=AB_WEAK_EXTERNAL
  4424. else if (symflags and WASM_SYM_BINDING_LOCAL) <> 0 then
  4425. objsym.bind:=AB_LOCAL
  4426. else
  4427. objsym.bind:=AB_GLOBAL;
  4428. objsym.typ:=AT_WASM_EXCEPTION_TAG;
  4429. objsym.objsection:=ObjData.createsection('.wasm_tags.n_'+SymName,1,[oso_Data,oso_load],true);
  4430. if objsym.objsection.Size=0 then
  4431. objsym.objsection.WriteZeros(1);
  4432. if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
  4433. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  4434. objsym.offset:=0;
  4435. objsym.size:=1;
  4436. end;
  4437. objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[TagTypes[SymIndex].TagTypeIdx]);
  4438. objsym.LinkingData.IsExported:=TagTypes[SymIndex].IsExported;
  4439. objsym.LinkingData.ExportName:=TagTypes[SymIndex].ExportName;
  4440. end;
  4441. SYMTAB_TABLE:
  4442. {TODO};
  4443. end;
  4444. for j:=0 to high(RelocationTable) do
  4445. for i:=0 to high(RelocationTable[j]) do
  4446. with RelocationTable[j,i] do
  4447. begin
  4448. case j of
  4449. 0:
  4450. begin
  4451. SegI:=FindCodeSegment(RelocOffset);
  4452. if SegI=-1 then
  4453. begin
  4454. InputError('Relocation offset not found in code segment');
  4455. Exit;
  4456. end;
  4457. BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
  4458. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SegI]);
  4459. end;
  4460. 1:
  4461. begin
  4462. SegI:=FindDataSegment(RelocOffset);
  4463. if SegI=-1 then
  4464. begin
  4465. InputError('Relocation offset not found in data segment');
  4466. Exit;
  4467. end;
  4468. BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
  4469. ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
  4470. end;
  4471. 2..2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))):
  4472. begin
  4473. BaseSectionOffset:=0;
  4474. ObjSec:=ObjData.findsection(WasmCustomSectionName[TWasmCustomSectionType((j-2)+Ord(Low(TWasmCustomDebugSectionType)))]);
  4475. end;
  4476. else
  4477. internalerror(2023122801);
  4478. end;
  4479. case RelocType of
  4480. R_WASM_FUNCTION_INDEX_LEB:
  4481. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB));
  4482. R_WASM_TABLE_INDEX_SLEB:
  4483. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB));
  4484. R_WASM_TABLE_INDEX_I32:
  4485. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE));
  4486. R_WASM_MEMORY_ADDR_LEB:
  4487. begin
  4488. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
  4489. ObjReloc.Addend:=RelocAddend;
  4490. ObjSec.ObjRelocations.Add(ObjReloc);
  4491. end;
  4492. R_WASM_MEMORY_ADDR_SLEB:
  4493. begin
  4494. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
  4495. ObjReloc.Addend:=RelocAddend;
  4496. ObjSec.ObjRelocations.Add(ObjReloc);
  4497. end;
  4498. R_WASM_MEMORY_ADDR_I32:
  4499. begin
  4500. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4501. ObjReloc.Addend:=RelocAddend;
  4502. ObjSec.ObjRelocations.Add(ObjReloc);
  4503. end;
  4504. R_WASM_TYPE_INDEX_LEB:
  4505. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
  4506. R_WASM_FUNCTION_OFFSET_I32:
  4507. begin
  4508. ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
  4509. ObjReloc.Addend:=RelocAddend;
  4510. ObjReloc.IsFunctionOffsetI32:=True;
  4511. ObjSec.ObjRelocations.Add(ObjReloc);
  4512. end;
  4513. R_WASM_SECTION_OFFSET_I32:
  4514. begin
  4515. ObjReloc:=TWasmObjRelocation.CreateSection(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSec,RELOC_ABSOLUTE);
  4516. ObjReloc.Addend:=RelocAddend;
  4517. ObjSec.ObjRelocations.Add(ObjReloc);
  4518. end;
  4519. R_WASM_GLOBAL_INDEX_LEB:
  4520. begin
  4521. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB));
  4522. if Assigned(SymbolTable[RelocIndex].ObjSym.TlsGlobalSym) then
  4523. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym.TlsGlobalSym,RELOC_GLOBAL_INDEX_LEB));
  4524. end;
  4525. R_WASM_GLOBAL_INDEX_I32:
  4526. begin
  4527. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE));
  4528. if Assigned(SymbolTable[RelocIndex].ObjSym.TlsGlobalSym) then
  4529. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym.TlsGlobalSym,RELOC_ABSOLUTE));
  4530. end;
  4531. R_WASM_TAG_INDEX_LEB:
  4532. ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_TAG_INDEX_LEB));
  4533. else
  4534. internalerror(2023122802);
  4535. end;
  4536. end;
  4537. Result:=True;
  4538. end;
  4539. {****************************************************************************
  4540. TWasmExeOutput
  4541. ****************************************************************************}
  4542. procedure TWasmExeOutput.AddToNameMap(var nm: TCustomSectionNameMap; aidx: UInt32; const aname: string);
  4543. begin
  4544. SetLength(nm,Length(nm)+1);
  4545. with nm[High(nm)] do
  4546. begin
  4547. idx:=aidx;
  4548. name:=aname;
  4549. end;
  4550. end;
  4551. procedure TWasmExeOutput.AddToFunctionNameMap(aidx: UInt32; const aname: string);
  4552. begin
  4553. AddToNameMap(FFunctionNameMap,aidx,aname);
  4554. end;
  4555. procedure TWasmExeOutput.AddToGlobalNameMap(aidx: UInt32; const aname: string);
  4556. begin
  4557. AddToNameMap(FGlobalNameMap,aidx,aname);
  4558. end;
  4559. procedure TWasmExeOutput.AddToDataNameMap(aidx: UInt32; const aname: string);
  4560. begin
  4561. AddToNameMap(FDataNameMap,aidx,aname);
  4562. end;
  4563. procedure TWasmExeOutput.AddToTagNameMap(aidx: UInt32; const aname: string);
  4564. begin
  4565. AddToNameMap(FTagNameMap,aidx,aname);
  4566. end;
  4567. procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
  4568. var
  4569. b: byte;
  4570. begin
  4571. b:=ord(wsid);
  4572. Writer.write(b,1);
  4573. WriteUleb(Writer,FWasmSections[wsid].size);
  4574. Writer.writearray(FWasmSections[wsid]);
  4575. end;
  4576. procedure TWasmExeOutput.WriteWasmSectionIfNotEmpty(wsid: TWasmSectionID);
  4577. begin
  4578. if FWasmSections[wsid].size>0 then
  4579. WriteWasmSection(wsid);
  4580. end;
  4581. procedure TWasmExeOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  4582. var
  4583. b: byte;
  4584. begin
  4585. b:=0;
  4586. Writer.write(b,1);
  4587. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  4588. Writer.writearray(FWasmCustomSections[wcst]);
  4589. end;
  4590. function TWasmExeOutput.writeData: boolean;
  4591. procedure WriteImportSection;
  4592. var
  4593. imports_count,
  4594. memory_imports: SizeInt;
  4595. i: Integer;
  4596. begin
  4597. if ts_wasm_threads in current_settings.targetswitches then
  4598. memory_imports:=1
  4599. else
  4600. memory_imports:=0;
  4601. imports_count:=Length(FFunctionImports)+memory_imports;
  4602. WriteUleb(FWasmSections[wsiImport],imports_count);
  4603. if ts_wasm_threads in current_settings.targetswitches then
  4604. begin
  4605. WriteName(FWasmSections[wsiImport],'env');
  4606. WriteName(FWasmSections[wsiImport],'memory');
  4607. WriteByte(FWasmSections[wsiImport],$02); { mem }
  4608. WriteByte(FWasmSections[wsiImport],$03); { shared }
  4609. WriteUleb(FWasmSections[wsiImport],FMinMemoryPages);
  4610. WriteUleb(FWasmSections[wsiImport],Max(FMinMemoryPages,FMaxMemoryPages)); { max pages }
  4611. end;
  4612. for i:=0 to Length(FFunctionImports)-1 do
  4613. with FFunctionImports[i] do
  4614. begin
  4615. WriteName(FWasmSections[wsiImport],ModName);
  4616. WriteName(FWasmSections[wsiImport],Name);
  4617. WriteByte(FWasmSections[wsiImport],$00); { func }
  4618. WriteUleb(FWasmSections[wsiImport],TypeIdx);
  4619. end;
  4620. end;
  4621. procedure WriteCodeSegments;
  4622. var
  4623. i: Integer;
  4624. exesec: TExeSection;
  4625. objsec: TWasmObjSection;
  4626. begin
  4627. exesec:=FindExeSection('.text');
  4628. if not assigned(exesec) then
  4629. internalerror(2023123102);
  4630. if not (oso_Data in exesec.SecOptions) then
  4631. internalerror(2023123103);
  4632. WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
  4633. WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
  4634. for i:=0 to exesec.ObjSectionList.Count-1 do
  4635. begin
  4636. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4637. if not (oso_data in objsec.secoptions) then
  4638. internalerror(2023123104);
  4639. if not assigned(objsec.data) then
  4640. internalerror(2023123105);
  4641. if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
  4642. internalerror(2024010101);
  4643. WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4644. WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
  4645. objsec.Data.seek(0);
  4646. CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
  4647. end;
  4648. end;
  4649. procedure WriteDataSegments;
  4650. procedure WriteExeSection(exesec: TExeSection);
  4651. var
  4652. i: Integer;
  4653. objsec: TObjSection;
  4654. exesecdatapos: LongWord;
  4655. dpos, pad: QWord;
  4656. begin
  4657. AddToDataNameMap(Length(FDataNameMap),exesec.Name);
  4658. if ts_wasm_threads in current_settings.targetswitches then
  4659. WriteByte(FWasmSections[wsiData],1) { mode passive }
  4660. else
  4661. begin
  4662. WriteByte(FWasmSections[wsiData],0); { mode active, memory 0, offset e }
  4663. WriteByte(FWasmSections[wsiData],$41); { i32.const }
  4664. WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
  4665. WriteByte(FWasmSections[wsiData],$0B); { end }
  4666. end;
  4667. WriteUleb(FWasmSections[wsiData],exesec.Size);
  4668. exesecdatapos:=FWasmSections[wsiData].size;
  4669. for i:=0 to exesec.ObjSectionList.Count-1 do
  4670. begin
  4671. objsec:=TObjSection(exesec.ObjSectionList[i]);
  4672. if not (oso_data in objsec.secoptions) then
  4673. internalerror(2024010104);
  4674. if not assigned(objsec.data) then
  4675. internalerror(2024010105);
  4676. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  4677. pad:=dpos-FWasmSections[wsiData].size;
  4678. { objsection must be within SecAlign bytes from the previous one }
  4679. if (dpos<FWasmSections[wsiData].Size) or
  4680. (pad>=max(objsec.SecAlign,1)) then
  4681. internalerror(2024010106);
  4682. writeZeros(FWasmSections[wsiData],pad);
  4683. objsec.data.seek(0);
  4684. CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
  4685. end;
  4686. if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
  4687. internalerror(2024010107);
  4688. end;
  4689. var
  4690. DataCount: Integer;
  4691. DataSecName: string;
  4692. ExeSec: TExeSection;
  4693. begin
  4694. DataCount:=0;
  4695. for DataSecName in DataSections do
  4696. begin
  4697. ExeSec:=FindExeSection(DataSecName);
  4698. if Assigned(ExeSec) and (ExeSec.Size>0) then
  4699. Inc(DataCount);
  4700. end;
  4701. WriteUleb(FWasmSections[wsiDataCount],DataCount);
  4702. WriteUleb(FWasmSections[wsiData],DataCount);
  4703. for DataSecName in DataSections do
  4704. begin
  4705. ExeSec:=FindExeSection(DataSecName);
  4706. if Assigned(ExeSec) and (ExeSec.Size>0) then
  4707. WriteExeSection(ExeSec);
  4708. end;
  4709. end;
  4710. procedure WriteTableAndElemSections;
  4711. const
  4712. TableCount=1;
  4713. var
  4714. i: Integer;
  4715. begin
  4716. { Table section }
  4717. WriteUleb(FWasmSections[wsiTable],TableCount);
  4718. { table 0 }
  4719. { table type }
  4720. WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
  4721. { table limits }
  4722. WriteByte(FWasmSections[wsiTable],$01); { has min & max }
  4723. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
  4724. WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
  4725. { Elem section }
  4726. WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
  4727. { element segment 0 }
  4728. WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
  4729. { e:expr }
  4730. WriteByte(FWasmSections[wsiElement],$41); { i32.const }
  4731. WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
  4732. WriteByte(FWasmSections[wsiElement],$0B); { end }
  4733. { y*:vec(funcidx) }
  4734. WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
  4735. for i:=1 to Length(FIndirectFunctionTable)-1 do
  4736. WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
  4737. end;
  4738. procedure WriteGlobalSection;
  4739. var
  4740. exesec: TExeSection;
  4741. globals_count, i: Integer;
  4742. objsec: TWasmObjSection;
  4743. begin
  4744. exesec:=FindExeSection('.wasm_globals');
  4745. if not assigned(exesec) then
  4746. internalerror(2024010112);
  4747. globals_count:=exesec.ObjSectionList.Count;
  4748. if globals_count<>exesec.Size then
  4749. internalerror(2024010113);
  4750. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  4751. for i:=0 to exesec.ObjSectionList.Count-1 do
  4752. begin
  4753. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4754. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
  4755. if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
  4756. WriteByte(FWasmSections[wsiGlobal],1)
  4757. else
  4758. WriteByte(FWasmSections[wsiGlobal],0);
  4759. { initializer expr }
  4760. with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
  4761. case typ of
  4762. wbt_i32:
  4763. begin
  4764. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  4765. WriteSleb(FWasmSections[wsiGlobal],init_i32);
  4766. end;
  4767. wbt_i64:
  4768. begin
  4769. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  4770. WriteSleb(FWasmSections[wsiGlobal],init_i64);
  4771. end;
  4772. wbt_f32:
  4773. begin
  4774. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  4775. WriteF32LE(FWasmSections[wsiGlobal],init_f32);
  4776. end;
  4777. wbt_f64:
  4778. begin
  4779. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  4780. WriteF64LE(FWasmSections[wsiGlobal],init_f64);
  4781. end;
  4782. wbt_funcref,
  4783. wbt_externref:
  4784. begin
  4785. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
  4786. WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
  4787. end;
  4788. else
  4789. internalerror(2024010114);
  4790. end;
  4791. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  4792. { add entry for the name section }
  4793. AddToGlobalNameMap(i,objsec.MainFuncSymbol.Name);
  4794. end;
  4795. end;
  4796. procedure WriteTagSection;
  4797. var
  4798. exesec: TExeSection;
  4799. tags_count, i: Integer;
  4800. objsec: TWasmObjSection;
  4801. begin
  4802. exesec:=FindExeSection('.wasm_tags');
  4803. if not assigned(exesec) then
  4804. exit;
  4805. tags_count:=exesec.ObjSectionList.Count;
  4806. if tags_count<>exesec.Size then
  4807. internalerror(2024010702);
  4808. if tags_count=0 then
  4809. exit;
  4810. WriteUleb(FWasmSections[wsiTag],tags_count);
  4811. for i:=0 to exesec.ObjSectionList.Count-1 do
  4812. begin
  4813. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  4814. WriteByte(FWasmSections[wsiTag],0);
  4815. WriteUleb(FWasmSections[wsiTag],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
  4816. AddToTagNameMap(i,objsec.MainFuncSymbol.Name);
  4817. end;
  4818. end;
  4819. procedure WriteExportSection;
  4820. const
  4821. MemoryExportsCount=1;
  4822. var
  4823. FunctionExportsCount: Integer;
  4824. ExportsCount: Integer;
  4825. textsec: TExeSection;
  4826. i: Integer;
  4827. objsec: TWasmObjSection;
  4828. begin
  4829. FunctionExportsCount:=0;
  4830. textsec:=FindExeSection('.text');
  4831. if not assigned(textsec) then
  4832. internalerror(2024010115);
  4833. for i:=0 to textsec.ObjSectionList.Count-1 do
  4834. begin
  4835. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4836. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4837. Inc(FunctionExportsCount)
  4838. end;
  4839. ExportsCount:=MemoryExportsCount+FunctionExportsCount;
  4840. WriteUleb(FWasmSections[wsiExport],ExportsCount);
  4841. { export 0 }
  4842. WriteName(FWasmSections[wsiExport],'memory');
  4843. WriteByte(FWasmSections[wsiExport],$02); { mem }
  4844. WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
  4845. for i:=0 to textsec.ObjSectionList.Count-1 do
  4846. begin
  4847. objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
  4848. if objsec.MainFuncSymbol.LinkingData.IsExported then
  4849. begin
  4850. WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
  4851. WriteByte(FWasmSections[wsiExport],$00); { func }
  4852. WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
  4853. end;
  4854. end;
  4855. end;
  4856. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  4857. var
  4858. exesec: TExeSection;
  4859. begin
  4860. exesec:=FindExeSection(WasmCustomSectionName[st]);
  4861. if assigned(exesec) then
  4862. begin
  4863. WriteExeSectionToDynArray(exesec,FWasmCustomSections[st]);
  4864. WriteWasmCustomSection(st);
  4865. end;
  4866. end;
  4867. procedure WriteNameMap(const nm: TCustomSectionNameMap; dest: tdynamicarray);
  4868. var
  4869. i: Integer;
  4870. begin
  4871. WriteUleb(dest,Length(nm));
  4872. for i:=low(nm) to high(nm) do
  4873. with nm[i] do
  4874. begin
  4875. WriteUleb(dest,idx);
  4876. WriteName(dest,name);
  4877. end;
  4878. end;
  4879. procedure WriteNameSubsection(wnst: TWasmNameSubsectionType);
  4880. begin
  4881. if FWasmNameSubsections[wnst].size>0 then
  4882. begin
  4883. WriteByte(FWasmCustomSections[wcstName],Ord(wnst));
  4884. WriteUleb(FWasmCustomSections[wcstName],FWasmNameSubsections[wnst].size);
  4885. FWasmNameSubsections[wnst].seek(0);
  4886. CopyDynamicArray(FWasmNameSubsections[wnst],FWasmCustomSections[wcstName],FWasmNameSubsections[wnst].size);
  4887. end;
  4888. end;
  4889. procedure WriteNameSection;
  4890. begin
  4891. WriteName(FWasmNameSubsections[wnstModuleName],current_module.exefilename);
  4892. WriteNameSubsection(wnstModuleName);
  4893. WriteNameMap(FFunctionNameMap,FWasmNameSubsections[wnstFunctionNames]);
  4894. WriteNameSubsection(wnstFunctionNames);
  4895. WriteNameMap(FGlobalNameMap,FWasmNameSubsections[wnstGlobalNames]);
  4896. WriteNameSubsection(wnstGlobalNames);
  4897. WriteNameMap(FDataNameMap,FWasmNameSubsections[wnstDataNames]);
  4898. WriteNameSubsection(wnstDataNames);
  4899. if Length(FTagNameMap)>0 then
  4900. begin
  4901. WriteNameMap(FTagNameMap,FWasmNameSubsections[wnstTagNames]);
  4902. WriteNameSubsection(wnstTagNames);
  4903. end;
  4904. end;
  4905. var
  4906. cust_sec: TWasmCustomSectionType;
  4907. begin
  4908. result:=false;
  4909. FMaxMemoryPages:=align(maxheapsize,WasmPageSize) div WasmPageSize;
  4910. { each custom sections starts with its name }
  4911. for cust_sec in TWasmCustomSectionType do
  4912. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  4913. SetStackPointer;
  4914. SetTlsSizeAlignAndBase;
  4915. SetThreadVarGlobalsInitValues;
  4916. GenerateCode_InitTls;
  4917. GenerateCode_InitSharedMemory;
  4918. GenerateCode_InvokeHelper;
  4919. FFuncTypes.WriteTo(FWasmSections[wsiType]);
  4920. WriteImportSection;
  4921. WriteCodeSegments;
  4922. WriteDataSegments;
  4923. WriteTableAndElemSections;
  4924. WriteGlobalSection;
  4925. WriteTagSection;
  4926. WriteExportSection;
  4927. if not (ts_wasm_threads in current_settings.targetswitches) then
  4928. begin
  4929. WriteUleb(FWasmSections[wsiMemory],1);
  4930. if FMaxMemoryPages>=FMinMemoryPages then
  4931. begin
  4932. WriteByte(FWasmSections[wsiMemory],1);
  4933. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4934. WriteUleb(FWasmSections[wsiMemory],FMaxMemoryPages);
  4935. end
  4936. else
  4937. begin
  4938. WriteByte(FWasmSections[wsiMemory],0);
  4939. WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
  4940. end;
  4941. end;
  4942. if ts_wasm_threads in current_settings.targetswitches then
  4943. WriteUleb(FWasmSections[wsiStart],FInitSharedMemoryFunctionSym.LinkingData.ExeFunctionIndex);
  4944. WriteNameSection;
  4945. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  4946. Writer.write(WasmVersion,SizeOf(WasmVersion));
  4947. WriteWasmSection(wsiType);
  4948. WriteWasmSection(wsiImport);
  4949. WriteWasmSection(wsiFunction);
  4950. WriteWasmSection(wsiTable);
  4951. if not (ts_wasm_threads in current_settings.targetswitches) then
  4952. WriteWasmSection(wsiMemory);
  4953. WriteWasmSectionIfNotEmpty(wsiTag);
  4954. WriteWasmSection(wsiGlobal);
  4955. WriteWasmSection(wsiExport);
  4956. if ts_wasm_threads in current_settings.targetswitches then
  4957. WriteWasmSection(wsiStart);
  4958. WriteWasmSection(wsiElement);
  4959. WriteWasmSection(wsiDataCount);
  4960. WriteWasmSection(wsiCode);
  4961. WriteWasmSection(wsiData);
  4962. MaybeWriteDebugSection(wcstDebugAbbrev);
  4963. MaybeWriteDebugSection(wcstDebugInfo);
  4964. MaybeWriteDebugSection(wcstDebugStr);
  4965. MaybeWriteDebugSection(wcstDebugLine);
  4966. MaybeWriteDebugSection(wcstDebugFrame);
  4967. MaybeWriteDebugSection(wcstDebugAranges);
  4968. MaybeWriteDebugSection(wcstDebugRanges);
  4969. WriteWasmCustomSection(wcstName);
  4970. result := true;
  4971. end;
  4972. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  4973. procedure writeUInt32LE(v: uint32);
  4974. begin
  4975. {$ifdef FPC_BIG_ENDIAN}
  4976. v:=SwapEndian(v);
  4977. {$endif FPC_BIG_ENDIAN}
  4978. objsec.data.write(v,4);
  4979. end;
  4980. var
  4981. i: Integer;
  4982. objreloc: TWasmObjRelocation;
  4983. objsym: TWasmObjSymbol;
  4984. begin
  4985. for i:=0 to objsec.ObjRelocations.Count-1 do
  4986. begin
  4987. objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
  4988. if assigned(objreloc.symbol) then
  4989. begin
  4990. objsym:=TWasmObjSymbol(objreloc.symbol);
  4991. case objreloc.typ of
  4992. RELOC_FUNCTION_INDEX_LEB:
  4993. begin
  4994. if objsym.LinkingData.ExeFunctionIndex=-1 then
  4995. internalerror(2024010103);
  4996. objsec.Data.seek(objreloc.DataOffset);
  4997. WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
  4998. end;
  4999. RELOC_ABSOLUTE:
  5000. begin
  5001. case objsym.typ of
  5002. AT_FUNCTION:
  5003. begin
  5004. if objreloc.IsFunctionOffsetI32 then
  5005. begin
  5006. { R_WASM_FUNCTION_OFFSET_I32 }
  5007. objsec.Data.seek(objreloc.DataOffset);
  5008. writeUInt32LE(UInt32(objsym.objsection.MemPos+objreloc.Addend));
  5009. end
  5010. else
  5011. begin
  5012. { R_WASM_TABLE_INDEX_I32 }
  5013. if objsym.LinkingData.ExeFunctionIndex=-1 then
  5014. internalerror(2024010103);
  5015. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  5016. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  5017. objsec.Data.seek(objreloc.DataOffset);
  5018. writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  5019. end;
  5020. end;
  5021. AT_DATA:
  5022. begin
  5023. if objreloc.IsFunctionOffsetI32 then
  5024. internalerror(2024010602);
  5025. objsec.Data.seek(objreloc.DataOffset);
  5026. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  5027. end;
  5028. AT_TLS:
  5029. begin
  5030. if objreloc.IsFunctionOffsetI32 then
  5031. internalerror(2024010602);
  5032. objsec.Data.seek(objreloc.DataOffset);
  5033. writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos-objsym.objsection.ExeSection.MemPos)+objreloc.Addend));
  5034. end;
  5035. AT_WASM_GLOBAL:
  5036. begin
  5037. if objreloc.IsFunctionOffsetI32 then
  5038. internalerror(2024010602);
  5039. objsec.Data.seek(objreloc.DataOffset);
  5040. writeUInt32LE(UInt32(objsym.offset+objsym.objsection.MemPos));
  5041. end;
  5042. else
  5043. internalerror(2024010108);
  5044. end;
  5045. end;
  5046. RELOC_MEMORY_ADDR_LEB:
  5047. begin
  5048. if objsym.typ<>AT_DATA then
  5049. internalerror(2024010109);
  5050. objsec.Data.seek(objreloc.DataOffset);
  5051. WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  5052. end;
  5053. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  5054. begin
  5055. case objsym.typ of
  5056. AT_FUNCTION:
  5057. begin
  5058. if objsym.LinkingData.ExeFunctionIndex=-1 then
  5059. internalerror(2024010103);
  5060. if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
  5061. objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
  5062. objsec.Data.seek(objreloc.DataOffset);
  5063. WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
  5064. end;
  5065. AT_DATA:
  5066. begin
  5067. objsec.Data.seek(objreloc.DataOffset);
  5068. WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
  5069. end;
  5070. else
  5071. internalerror(2024010110);
  5072. end;
  5073. end;
  5074. RELOC_GLOBAL_INDEX_LEB:
  5075. if objsym.typ=AT_WASM_GLOBAL then
  5076. begin
  5077. objsec.Data.seek(objreloc.DataOffset);
  5078. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  5079. end
  5080. else if (ts_wasm_threads in current_settings.targetswitches) and
  5081. (objsym.typ=AT_TLS) then
  5082. begin
  5083. { Nothing to do here. A second RELOC_GLOBAL_INDEX_LEB
  5084. relocation, overlaid on top of this one, pointing to
  5085. an AT_WASM_GLOBAL should have already done the job. }
  5086. end
  5087. else
  5088. internalerror(2024010111);
  5089. RELOC_TAG_INDEX_LEB:
  5090. begin
  5091. if objsym.typ<>AT_WASM_EXCEPTION_TAG then
  5092. internalerror(2024010708);
  5093. objsec.Data.seek(objreloc.DataOffset);
  5094. WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
  5095. end;
  5096. else
  5097. internalerror(2024010109);
  5098. end;
  5099. end
  5100. else if assigned(objreloc.objsection) then
  5101. begin
  5102. if objreloc.typ<>RELOC_ABSOLUTE then
  5103. internalerror(2024010601);
  5104. objsec.Data.seek(objreloc.DataOffset);
  5105. writeUInt32LE(UInt32((objreloc.objsection.MemPos)+objreloc.Addend));
  5106. end
  5107. else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
  5108. begin
  5109. objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
  5110. objsec.Data.seek(objreloc.DataOffset);
  5111. WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
  5112. end
  5113. else
  5114. internalerror(2024010110);
  5115. end;
  5116. end;
  5117. constructor TWasmExeOutput.create;
  5118. var
  5119. i: TWasmSectionID;
  5120. j: TWasmCustomSectionType;
  5121. k: TWasmNameSubsectionType;
  5122. begin
  5123. inherited create;
  5124. CObjData:=TWasmObjData;
  5125. SectionMemAlign:=16;
  5126. MaxMemPos:=$FFFFFFFF;
  5127. FFuncTypes:=TWasmFuncTypeTable.Create;
  5128. for i in TWasmSectionID do
  5129. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  5130. for j in TWasmCustomSectionType do
  5131. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  5132. for k:=low(FWasmNameSubsections) to high(FWasmNameSubsections) do
  5133. FWasmNameSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  5134. SetLength(FIndirectFunctionTable,1);
  5135. FIndirectFunctionTable[0].FuncIdx:=-1;
  5136. end;
  5137. destructor TWasmExeOutput.destroy;
  5138. var
  5139. i: TWasmSectionID;
  5140. j: TWasmCustomSectionType;
  5141. k: TWasmNameSubsectionType;
  5142. begin
  5143. for i in TWasmSectionID do
  5144. FWasmSections[i].Free;
  5145. for j in TWasmCustomSectionType do
  5146. FWasmCustomSections[j].Free;
  5147. for k:=low(FWasmNameSubsections) to high(FWasmNameSubsections) do
  5148. FWasmNameSubsections[k].Free;
  5149. FFuncTypes.Free;
  5150. inherited destroy;
  5151. end;
  5152. procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
  5153. var
  5154. i, j: Integer;
  5155. ImportLibrary: TImportLibrary;
  5156. ImportSymbol: TImportSymbol;
  5157. exesym: TExeSymbol;
  5158. begin
  5159. { Here map import symbols to exe symbols and create necessary sections.
  5160. Actual import generation is done after unused sections (and symbols) are removed. }
  5161. FImports:=ImportLibraryList;
  5162. for i:=0 to ImportLibraryList.Count-1 do
  5163. begin
  5164. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  5165. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  5166. begin
  5167. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  5168. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  5169. if assigned(exesym) and
  5170. (exesym.State<>symstate_defined) then
  5171. begin
  5172. ImportSymbol.CachedExeSymbol:=exesym;
  5173. exesym.State:=symstate_defined;
  5174. end;
  5175. end;
  5176. end;
  5177. PackUnresolvedExeSymbols('after module imports');
  5178. end;
  5179. procedure TWasmExeOutput.AfterUnusedSectionRemoval;
  5180. begin
  5181. PrepareImports;
  5182. PrepareFunctions;
  5183. PrepareTags;
  5184. end;
  5185. procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
  5186. const
  5187. DebugPrefix = '.debug_';
  5188. var
  5189. ExeSec: TExeSection;
  5190. i: Integer;
  5191. objsec: TObjSection;
  5192. firstdatasec: string;
  5193. begin
  5194. { WebAssembly is a Harvard architecture.
  5195. Data lives in a separate address space, so start addressing back from 0
  5196. (the LLVM leaves the first 1024 bytes in the data segment empty, so we
  5197. start at 1024). }
  5198. if ts_wasm_threads in current_settings.targetswitches then
  5199. firstdatasec:='.tbss'
  5200. else
  5201. firstdatasec:='.rodata';
  5202. if aname=firstdatasec then
  5203. begin
  5204. CurrMemPos:=1024;
  5205. inherited;
  5206. end
  5207. else if aname='.text' then
  5208. begin
  5209. CurrMemPos:=0;
  5210. ExeSec:=FindExeSection(aname);
  5211. if not assigned(ExeSec) then
  5212. exit;
  5213. exesec.MemPos:=CurrMemPos;
  5214. CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
  5215. { set position of object ObjSections }
  5216. for i:=0 to exesec.ObjSectionList.Count-1 do
  5217. begin
  5218. objsec:=TObjSection(exesec.ObjSectionList[i]);
  5219. CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
  5220. CurrMemPos:=objsec.setmempos(CurrMemPos);
  5221. end;
  5222. { calculate size of the section }
  5223. exesec.Size:=CurrMemPos-exesec.MemPos;
  5224. end
  5225. else if (aname='.wasm_globals') or (aname='.wasm_tags') or
  5226. (Copy(aname,1,Length(DebugPrefix))=DebugPrefix) then
  5227. begin
  5228. CurrMemPos:=0;
  5229. inherited;
  5230. end
  5231. else
  5232. inherited;
  5233. end;
  5234. procedure TWasmExeOutput.Load_Symbol(const aname: string);
  5235. begin
  5236. if aname=StackPointerSymStr then
  5237. begin
  5238. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5239. FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5240. FStackPointerSym.size:=1;
  5241. FStackPointerSym.ObjSection.WriteZeros(1);
  5242. TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
  5243. FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
  5244. FStackPointerSym.LinkingData.GlobalIsMutable:=True;
  5245. FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5246. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
  5247. end
  5248. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_base') then
  5249. begin
  5250. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5251. FTlsBaseSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5252. FTlsBaseSym.size:=1;
  5253. FTlsBaseSym.ObjSection.WriteZeros(1);
  5254. TWasmObjSection(FTlsBaseSym.ObjSection).MainFuncSymbol:=FTlsBaseSym;
  5255. FTlsBaseSym.LinkingData.GlobalType:=wbt_i32;
  5256. FTlsBaseSym.LinkingData.GlobalIsMutable:=True;
  5257. FTlsBaseSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5258. FTlsBaseSym.LinkingData.GlobalInitializer.init_i32:=0;
  5259. end
  5260. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_size') then
  5261. begin
  5262. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5263. FTlsSizeSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5264. FTlsSizeSym.size:=1;
  5265. FTlsSizeSym.ObjSection.WriteZeros(1);
  5266. TWasmObjSection(FTlsSizeSym.ObjSection).MainFuncSymbol:=FTlsSizeSym;
  5267. FTlsSizeSym.LinkingData.GlobalType:=wbt_i32;
  5268. FTlsSizeSym.LinkingData.GlobalIsMutable:=False;
  5269. FTlsSizeSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5270. FTlsSizeSym.LinkingData.GlobalInitializer.init_i32:=0;
  5271. end
  5272. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__tls_align') then
  5273. begin
  5274. internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
  5275. FTlsAlignSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
  5276. FTlsAlignSym.size:=1;
  5277. FTlsAlignSym.ObjSection.WriteZeros(1);
  5278. TWasmObjSection(FTlsAlignSym.ObjSection).MainFuncSymbol:=FTlsAlignSym;
  5279. FTlsAlignSym.LinkingData.GlobalType:=wbt_i32;
  5280. FTlsAlignSym.LinkingData.GlobalIsMutable:=False;
  5281. FTlsAlignSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5282. FTlsAlignSym.LinkingData.GlobalInitializer.init_i32:=0;
  5283. end
  5284. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__wasm_init_tls') then
  5285. begin
  5286. internalObjData.createsection('*'+aname,0,[]);
  5287. FInitTlsFunctionSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION));
  5288. TWasmObjSection(FInitTlsFunctionSym.ObjSection).MainFuncSymbol:=FInitTlsFunctionSym;
  5289. FInitTlsFunctionSym.LinkingData.FuncType:=TWasmFuncType.Create([wbt_i32],[]);
  5290. end
  5291. else if (ts_wasm_threads in current_settings.targetswitches) and (aname='__fpc_wasm_init_shared_memory') then
  5292. begin
  5293. internalObjData.createsection('*'+aname,0,[]);
  5294. FInitSharedMemoryFunctionSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION));
  5295. TWasmObjSection(FInitSharedMemoryFunctionSym.ObjSection).MainFuncSymbol:=FInitSharedMemoryFunctionSym;
  5296. FInitSharedMemoryFunctionSym.ObjSection.SecOptions:=FInitSharedMemoryFunctionSym.ObjSection.SecOptions+[oso_keep];
  5297. FInitSharedMemoryFunctionSym.LinkingData.FuncType:=TWasmFuncType.Create([],[]);
  5298. end
  5299. else
  5300. inherited;
  5301. end;
  5302. procedure TWasmExeOutput.PrepareImports;
  5303. function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
  5304. begin
  5305. SetLength(FFunctionImports,Length(FFunctionImports)+1);
  5306. Result:=High(FFunctionImports);
  5307. if assigned(exemap) then
  5308. exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
  5309. with FFunctionImports[Result] do
  5310. begin
  5311. ModName:=libname;
  5312. Name:=symname;
  5313. TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
  5314. end;
  5315. end;
  5316. var
  5317. i, j: Integer;
  5318. ImportLibrary: TImportLibrary;
  5319. ImportSymbol: TImportSymbol;
  5320. exesym: TExeSymbol;
  5321. newdll: Boolean;
  5322. fsym: TWasmObjSymbol;
  5323. objdata: TObjData;
  5324. begin
  5325. for i:=0 to FImports.Count-1 do
  5326. begin
  5327. ImportLibrary:=TImportLibrary(FImports[i]);
  5328. newdll:=False;
  5329. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  5330. begin
  5331. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  5332. exesym:=ImportSymbol.CachedExeSymbol;
  5333. if assigned(exesym) and
  5334. exesym.Used then
  5335. begin
  5336. if (not newdll) and assigned(exemap) then
  5337. begin
  5338. exemap.Add('');
  5339. exemap.Add('Importing from module '+ImportLibrary.Name);
  5340. end;
  5341. newdll:=True;
  5342. TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
  5343. AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
  5344. AddToFunctionNameMap(TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex,ImportSymbol.MangledName);
  5345. end;
  5346. end;
  5347. end;
  5348. { set ExeFunctionIndex to the alias symbols as well }
  5349. for i:=0 to ObjDataList.Count-1 do
  5350. begin
  5351. objdata:=TObjData(ObjDataList[i]);
  5352. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5353. begin
  5354. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5355. if (fsym.LinkingData.ExeFunctionIndex=-1) and assigned(fsym.exesymbol) and (TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex<>-1) then
  5356. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex;
  5357. end;
  5358. end;
  5359. end;
  5360. procedure TWasmExeOutput.PrepareFunctions;
  5361. var
  5362. i, j: Integer;
  5363. exesec: TExeSection;
  5364. objsec: TWasmObjSection;
  5365. fsym: TWasmObjSymbol;
  5366. objdata: TObjData;
  5367. begin
  5368. if assigned(exemap) then
  5369. begin
  5370. exemap.Add('');
  5371. exemap.Add('Functions, defined in this module:');
  5372. end;
  5373. exesec:=FindExeSection('.text');
  5374. if not assigned(exesec) then
  5375. internalerror(2023123106);
  5376. for i:=0 to exesec.ObjSectionList.Count-1 do
  5377. begin
  5378. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5379. fsym:=objsec.MainFuncSymbol;
  5380. if not assigned(fsym) then
  5381. internalerror(2023123107);
  5382. if not assigned(fsym.LinkingData.FuncType) then
  5383. internalerror(2023123108);
  5384. if fsym.LinkingData.ExeFunctionIndex<>-1 then
  5385. internalerror(2023123109);
  5386. if fsym.LinkingData.ExeTypeIndex<>-1 then
  5387. internalerror(2023123109);
  5388. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  5389. fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
  5390. if assigned(exemap) then
  5391. begin
  5392. exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  5393. end;
  5394. AddToFunctionNameMap(fsym.LinkingData.ExeFunctionIndex,fsym.Name);
  5395. end;
  5396. { set ExeFunctionIndex to the alias symbols as well }
  5397. for i:=0 to ObjDataList.Count-1 do
  5398. begin
  5399. objdata:=TObjData(ObjDataList[i]);
  5400. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5401. begin
  5402. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5403. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
  5404. begin
  5405. fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
  5406. if fsym.LinkingData.ExeFunctionIndex=-1 then
  5407. internalerror(2024010102);
  5408. end;
  5409. end;
  5410. end;
  5411. end;
  5412. procedure TWasmExeOutput.PrepareTags;
  5413. var
  5414. exesec: TExeSection;
  5415. i, j: Integer;
  5416. objsec: TWasmObjSection;
  5417. fsym: TWasmObjSymbol;
  5418. objdata: TObjData;
  5419. begin
  5420. exesec:=FindExeSection('.wasm_tags');
  5421. if not assigned(exesec) then
  5422. exit;
  5423. if assigned(exemap) then
  5424. begin
  5425. exemap.Add('');
  5426. exemap.Add('Tags, defined in this module:');
  5427. end;
  5428. for i:=0 to exesec.ObjSectionList.Count-1 do
  5429. begin
  5430. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5431. fsym:=objsec.MainFuncSymbol;
  5432. if not assigned(fsym) then
  5433. internalerror(2024010703);
  5434. if not assigned(fsym.LinkingData.FuncType) then
  5435. internalerror(2024010704);
  5436. if fsym.LinkingData.ExeTagIndex<>-1 then
  5437. internalerror(2024010705);
  5438. if fsym.LinkingData.ExeTypeIndex<>-1 then
  5439. internalerror(2024010706);
  5440. fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
  5441. fsym.LinkingData.ExeTagIndex:=i+Length(FTagImports);
  5442. if assigned(exemap) then
  5443. begin
  5444. exemap.Add(' Tag[' + tostr(fsym.LinkingData.ExeTagIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
  5445. end;
  5446. end;
  5447. { set ExeTagIndex to the alias symbols as well }
  5448. for i:=0 to ObjDataList.Count-1 do
  5449. begin
  5450. objdata:=TObjData(ObjDataList[i]);
  5451. for j:=0 to objdata.ObjSymbolList.Count-1 do
  5452. begin
  5453. fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
  5454. if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_WASM_EXCEPTION_TAG) and (fsym.LinkingData.ExeTagIndex=-1) then
  5455. begin
  5456. fsym.LinkingData.ExeTagIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeTagIndex;
  5457. if fsym.LinkingData.ExeTagIndex=-1 then
  5458. internalerror(2024010707);
  5459. end;
  5460. end;
  5461. end;
  5462. end;
  5463. function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
  5464. var
  5465. i: Integer;
  5466. begin
  5467. for i:=1 to length(FIndirectFunctionTable)-1 do
  5468. if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
  5469. begin
  5470. Result:=i;
  5471. exit;
  5472. end;
  5473. SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
  5474. Result:=High(FIndirectFunctionTable);
  5475. FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
  5476. end;
  5477. procedure TWasmExeOutput.SetStackPointer;
  5478. var
  5479. BssSec: TExeSection;
  5480. StackStart, InitialStackPtrAddr: QWord;
  5481. begin
  5482. BssSec:=FindExeSection('.bss');
  5483. InitialStackPtrAddr := (BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15);
  5484. FMinMemoryPages := Max(
  5485. QWord(Align(QWord(InitialStackPtrAddr),QWord(WasmPageSize)) div WasmPageSize),
  5486. QWord(Align(QWord(heapsize),QWord(WasmPageSize)) div WasmPageSize));
  5487. FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32(InitialStackPtrAddr);
  5488. end;
  5489. procedure TWasmExeOutput.SetTlsSizeAlignAndBase;
  5490. var
  5491. TBssSec: TExeSection;
  5492. begin
  5493. if not (ts_wasm_threads in current_settings.targetswitches) then
  5494. exit;
  5495. TBssSec:=FindExeSection('.tbss');
  5496. FTlsSizeSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.Size);
  5497. FTlsAlignSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.SecAlign);
  5498. FTlsBaseSym.LinkingData.GlobalInitializer.init_i32:=Int32(TBssSec.MemPos);
  5499. end;
  5500. procedure TWasmExeOutput.SetThreadVarGlobalsInitValues;
  5501. var
  5502. exesec: TExeSection;
  5503. i: Integer;
  5504. objsec: TWasmObjSection;
  5505. objsym: TWasmObjSymbol;
  5506. begin
  5507. if not (ts_wasm_threads in current_settings.targetswitches) then
  5508. exit;
  5509. exesec:=FindExeSection('.wasm_globals');
  5510. if not assigned(exesec) then
  5511. internalerror(2024010112);
  5512. for i:=0 to exesec.ObjSectionList.Count-1 do
  5513. begin
  5514. objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
  5515. objsym:=objsec.MainFuncSymbol;
  5516. if Assigned(objsym.TlsDataSym) then
  5517. begin
  5518. objsym.LinkingData.GlobalInitializer.typ:=wbt_i32;
  5519. objsym.LinkingData.GlobalInitializer.init_i32:=objsym.TlsDataSym.offset+objsym.TlsDataSym.objsection.MemPos;
  5520. end;
  5521. end;
  5522. end;
  5523. procedure TWasmExeOutput.GenerateCode_InitTls;
  5524. var
  5525. Sec: TObjSection;
  5526. globalexesec: TExeSection;
  5527. i: Integer;
  5528. globalobjsec: TWasmObjSection;
  5529. globalobjsym: TWasmObjSymbol;
  5530. OffsetInTls: QWord;
  5531. begin
  5532. if not (ts_wasm_threads in current_settings.targetswitches) then
  5533. exit;
  5534. globalexesec:=FindExeSection('.wasm_globals');
  5535. if not assigned(globalexesec) then
  5536. internalerror(2024010112);
  5537. Sec:=FInitTlsFunctionSym.objsection;
  5538. Sec.SecOptions:=Sec.SecOptions+[oso_Data];
  5539. { locals }
  5540. Sec.writeUInt8($00);
  5541. { local.get 0 }
  5542. Sec.writeUInt16BE($2000);
  5543. { global.set $__tls_base }
  5544. Sec.writeUInt8($24);
  5545. WriteUleb(sec,FTlsBaseSym.offset+FTlsBaseSym.objsection.MemPos);
  5546. for i:=0 to globalexesec.ObjSectionList.Count-1 do
  5547. begin
  5548. globalobjsec:=TWasmObjSection(globalexesec.ObjSectionList[i]);
  5549. globalobjsym:=globalobjsec.MainFuncSymbol;
  5550. if Assigned(globalobjsym.TlsDataSym) then
  5551. begin
  5552. OffsetInTls:=globalobjsym.TlsDataSym.offset+globalobjsym.TlsDataSym.objsection.MemPos-globalobjsym.TlsDataSym.objsection.ExeSection.MemPos;
  5553. { local.get 0 }
  5554. Sec.writeUInt16BE($2000);
  5555. if OffsetInTls<>0 then
  5556. begin
  5557. { i32.const $OffsetInTls }
  5558. Sec.writeUInt8($41);
  5559. WriteSleb(Sec,Int32(OffsetInTls));
  5560. { i32.add }
  5561. Sec.writeUInt8($6A);
  5562. end;
  5563. { global.set y }
  5564. Sec.writeUInt8($24);
  5565. WriteUleb(sec,globalobjsym.offset+globalobjsym.objsection.MemPos);
  5566. end;
  5567. end;
  5568. Sec.writeUInt8($0B); { end }
  5569. end;
  5570. procedure TWasmExeOutput.GenerateCode_InitSharedMemory;
  5571. const
  5572. InitFlagOfs=256;
  5573. var
  5574. Sec: TObjSection;
  5575. DataSecName: string;
  5576. DataSecIdx: Integer;
  5577. ExeSec: TExeSection;
  5578. begin
  5579. if not (ts_wasm_threads in current_settings.targetswitches) then
  5580. exit;
  5581. Sec:=FInitSharedMemoryFunctionSym.objsection;
  5582. Sec.SecOptions:=Sec.SecOptions+[oso_Data];
  5583. { locals }
  5584. Sec.writeUInt8($00);
  5585. { block }
  5586. Sec.writeUInt16BE($0240);
  5587. { block }
  5588. Sec.writeUInt16BE($0240);
  5589. { block }
  5590. Sec.writeUInt16BE($0240);
  5591. { i32.const $InitFlag }
  5592. Sec.writeUInt8($41);
  5593. WriteSleb(sec,InitFlagOfs);
  5594. { i32.const 0 }
  5595. Sec.writeUInt16BE($4100);
  5596. { i32.const 1 }
  5597. Sec.writeUInt16BE($4101);
  5598. { i32.atomic.rmw.cmpxchg 2 0 }
  5599. Sec.writeUInt32BE($fe480200);
  5600. { br_table 0 1 2 }
  5601. Sec.writebytes(#$0e#$02#$00#$01#$02);
  5602. { end }
  5603. Sec.writeUInt8($0B);
  5604. DataSecIdx:=-1;
  5605. for DataSecName in DataSections do
  5606. begin
  5607. ExeSec:=FindExeSection(DataSecName);
  5608. if Assigned(ExeSec) and (ExeSec.Size>0) then
  5609. begin
  5610. Inc(DataSecIdx);
  5611. { i32.const $memPos }
  5612. Sec.writeUInt8($41);
  5613. WriteSleb(sec,Int32(ExeSec.MemPos));
  5614. { i32.const 0 }
  5615. Sec.writeUInt16BE($4100);
  5616. { i32.const size }
  5617. Sec.writeUInt8($41);
  5618. WriteSleb(sec,Int32(ExeSec.Size));
  5619. { memory.init $DataSecIdx 0 }
  5620. Sec.writeUInt16BE($fc08);
  5621. WriteUleb(sec,DataSecIdx);
  5622. Sec.writeUInt8(0);
  5623. end;
  5624. end;
  5625. { i32.const $InitFlag }
  5626. Sec.writeUInt8($41);
  5627. WriteSleb(sec,InitFlagOfs);
  5628. { i32.const 2 }
  5629. Sec.writeUInt16BE($4102);
  5630. { i32.atomic.store 2 0 }
  5631. Sec.writeUInt32BE($fe170200);
  5632. { i32.const $InitFlag }
  5633. Sec.writeUInt8($41);
  5634. WriteSleb(sec,InitFlagOfs);
  5635. { i32.const 4294967295 }
  5636. Sec.writeUInt16BE($417f);
  5637. { memory.atomic.notify 2 0 }
  5638. Sec.writeUInt32BE($fe000200);
  5639. { drop }
  5640. Sec.writeUInt8($1A);
  5641. { br 1 }
  5642. Sec.writeUInt16BE($0C01);
  5643. { end }
  5644. Sec.writeUInt8($0B);
  5645. { i32.const $InitFlag }
  5646. Sec.writeUInt8($41);
  5647. WriteSleb(sec,InitFlagOfs);
  5648. { i32.const 1 }
  5649. Sec.writeUInt16BE($4101);
  5650. { i64.const -1 }
  5651. Sec.writeUInt16BE($427f);
  5652. { memory.atomic.wait32 2 0 }
  5653. Sec.writeUInt32BE($fe010200);
  5654. { drop }
  5655. Sec.writeUInt8($1A);
  5656. { end }
  5657. Sec.writeUInt8($0B);
  5658. DataSecIdx:=-1;
  5659. for DataSecName in DataSections do
  5660. begin
  5661. ExeSec:=FindExeSection(DataSecName);
  5662. if Assigned(ExeSec) and (ExeSec.Size>0) then
  5663. begin
  5664. Inc(DataSecIdx);
  5665. { data.drop $DataSecIdx }
  5666. Sec.writeUInt16BE($fc09);
  5667. WriteUleb(sec,DataSecIdx);
  5668. end;
  5669. end;
  5670. { end }
  5671. Sec.writeUInt8($0B);
  5672. end;
  5673. procedure TWasmExeOutput.GenerateCode_InvokeHelper;
  5674. var
  5675. Sec: TObjSection;
  5676. IndirectFunctionTableMap: array of Integer;
  5677. procedure InvokeFuncType(typidx: Integer; islast: Boolean);
  5678. var
  5679. ft: TWasmFuncType;
  5680. i, nextofs: Integer;
  5681. begin
  5682. ft:=FFuncTypes[typidx];
  5683. for i:=0 to Length(ft.results)-1 do
  5684. { local.get 2 }
  5685. Sec.writeUInt16BE($2002);
  5686. nextofs:=0;
  5687. for i:=0 to Length(ft.params)-1 do
  5688. begin
  5689. { local.get 1 }
  5690. Sec.writeUInt16BE($2001);
  5691. case ft.params[i] of
  5692. wbt_i32:
  5693. begin
  5694. { i32.load nextofs }
  5695. Sec.writeUInt16BE($2802);
  5696. WriteUleb(Sec, nextofs);
  5697. Inc(nextofs,4);
  5698. end;
  5699. wbt_i64:
  5700. begin
  5701. { i64.load nextofs }
  5702. Sec.writeUInt16BE($2902);
  5703. WriteUleb(Sec, nextofs);
  5704. Inc(nextofs,8);
  5705. end;
  5706. wbt_f32:
  5707. begin
  5708. { f32.load nextofs }
  5709. Sec.writeUInt16BE($2A02);
  5710. WriteUleb(Sec, nextofs);
  5711. Inc(nextofs,4);
  5712. end;
  5713. wbt_f64:
  5714. begin
  5715. { f64.load nextofs }
  5716. Sec.writeUInt16BE($2B02);
  5717. WriteUleb(Sec, nextofs);
  5718. Inc(nextofs,8);
  5719. end;
  5720. wbt_v128:
  5721. begin
  5722. { v128.load nextofs }
  5723. Sec.writeUInt16BE($FD00);
  5724. Sec.writeUInt8($02); { align: 4 bytes }
  5725. WriteUleb(Sec, nextofs);
  5726. Inc(nextofs,16);
  5727. end;
  5728. wbt_externref,
  5729. wbt_funcref:
  5730. begin
  5731. { unreachable }
  5732. Sec.writeUInt8($00);
  5733. end;
  5734. else
  5735. internalerror(2025012501);
  5736. end;
  5737. end;
  5738. { local.get 0 }
  5739. Sec.writeUInt16BE($2000);
  5740. { call_indirect }
  5741. Sec.writeUInt8($11);
  5742. WriteUleb(Sec,typidx);
  5743. Sec.writeUInt8($0); { table index 0 }
  5744. nextofs:=0;
  5745. for i:=0 to Length(ft.results)-1 do
  5746. begin
  5747. case ft.results[i] of
  5748. wbt_i32:
  5749. begin
  5750. { i32.store nextofs }
  5751. Sec.writeUInt16BE($3602);
  5752. WriteUleb(Sec, nextofs);
  5753. Inc(nextofs,4);
  5754. end;
  5755. wbt_i64:
  5756. begin
  5757. { i64.store nextofs }
  5758. Sec.writeUInt16BE($3702);
  5759. WriteUleb(Sec, nextofs);
  5760. Inc(nextofs,8);
  5761. end;
  5762. wbt_f32:
  5763. begin
  5764. { f32.store nextofs }
  5765. Sec.writeUInt16BE($3802);
  5766. WriteUleb(Sec, nextofs);
  5767. Inc(nextofs,4);
  5768. end;
  5769. wbt_f64:
  5770. begin
  5771. { f64.store nextofs }
  5772. Sec.writeUInt16BE($3902);
  5773. WriteUleb(Sec, nextofs);
  5774. Inc(nextofs,8);
  5775. end;
  5776. wbt_v128:
  5777. begin
  5778. { v128.store nextofs }
  5779. Sec.writeUInt16BE($FD0B);
  5780. Sec.writeUInt8($02); { align: 4 bytes }
  5781. WriteUleb(Sec, nextofs);
  5782. Inc(nextofs,16);
  5783. end;
  5784. wbt_externref,
  5785. wbt_funcref:
  5786. begin
  5787. { unreachable }
  5788. Sec.writeUInt8($00);
  5789. end;
  5790. else
  5791. internalerror(2025012501);
  5792. end;
  5793. end;
  5794. if not islast then
  5795. { return }
  5796. Sec.writeUInt8($0F);
  5797. end;
  5798. function FuncIdx2TypeIdx(fi: Integer): Integer;
  5799. var
  5800. exesec: TExeSection;
  5801. objsec: TWasmObjSection;
  5802. fsym: TWasmObjSymbol;
  5803. begin
  5804. if fi<Length(FFunctionImports) then
  5805. Result:=FFunctionImports[fi].TypeIdx
  5806. else
  5807. begin
  5808. exesec:=FindExeSection('.text');
  5809. if not assigned(exesec) then
  5810. internalerror(2023123106);
  5811. objsec:=TWasmObjSection(exesec.ObjSectionList[fi-Length(FFunctionImports)]);
  5812. fsym:=objsec.MainFuncSymbol;
  5813. Result:=fsym.LinkingData.ExeTypeIndex;
  5814. end;
  5815. end;
  5816. procedure WriteBrTable(l,h: Integer; addend: Integer=0);
  5817. const
  5818. { max len of br_table instruction }
  5819. MaxLen=1000;
  5820. var
  5821. i, len, m: Integer;
  5822. begin
  5823. { local.get 0 }
  5824. Sec.writeUInt16BE($2000);
  5825. len:=h-l+1;
  5826. if len<=MaxLen then
  5827. begin
  5828. if l>0 then
  5829. begin
  5830. { i32.const l }
  5831. Sec.writeUInt8($41);
  5832. WriteSleb(sec,l);
  5833. { i32.sub }
  5834. Sec.writeUInt8($6B);
  5835. end;
  5836. { br_table }
  5837. Sec.writeUInt8($0E);
  5838. if h=high(IndirectFunctionTableMap) then
  5839. begin
  5840. WriteUleb(Sec,len);
  5841. for i:=l to h do
  5842. WriteUleb(Sec,IndirectFunctionTableMap[i]+addend);
  5843. WriteUleb(Sec,addend);
  5844. end
  5845. else
  5846. begin
  5847. WriteUleb(Sec,len-1);
  5848. for i:=l to h do
  5849. WriteUleb(Sec,IndirectFunctionTableMap[i]+addend);
  5850. end;
  5851. end
  5852. else
  5853. begin
  5854. m:=(l+h) div 2;
  5855. { i32.const m }
  5856. Sec.writeUInt8($41);
  5857. WriteSleb(sec,m);
  5858. { i32.lt_u }
  5859. Sec.writeUInt8($49);
  5860. { if }
  5861. Sec.writeUInt16BE($0440);
  5862. WriteBrTable(l,m-1,addend+1);
  5863. { else }
  5864. Sec.writeUInt8($05);
  5865. WriteBrTable(m,h,addend+1);
  5866. { end }
  5867. Sec.writeUInt8($0B);
  5868. end;
  5869. end;
  5870. var
  5871. exesym: TExeSymbol;
  5872. objsym: TObjSymbol;
  5873. i, j, TypIdx: Integer;
  5874. InvokableTypeIndices: array of Integer;
  5875. begin
  5876. exesym:=TExeSymbol(ExeSymbolList.Find('fpc_wasm_invoke_helper'));
  5877. if not Assigned(exesym) then
  5878. exit;
  5879. SetLength(IndirectFunctionTableMap, Length(FIndirectFunctionTable));
  5880. SetLength(InvokableTypeIndices, 1);
  5881. InvokableTypeIndices[0] := -1;
  5882. for i:=1 to Length(FIndirectFunctionTable)-1 do
  5883. begin
  5884. IndirectFunctionTableMap[i]:=0;
  5885. TypIdx := FuncIdx2TypeIdx(FIndirectFunctionTable[i].FuncIdx);
  5886. for j := 1 to Length(InvokableTypeIndices)-1 do
  5887. if InvokableTypeIndices[j]=TypIdx then
  5888. begin
  5889. IndirectFunctionTableMap[i]:=j;
  5890. break;
  5891. end;
  5892. if IndirectFunctionTableMap[i]=0 then
  5893. begin
  5894. SetLength(InvokableTypeIndices,Length(InvokableTypeIndices)+1);
  5895. InvokableTypeIndices[High(InvokableTypeIndices)]:=TypIdx;
  5896. IndirectFunctionTableMap[i]:=High(InvokableTypeIndices);
  5897. end;
  5898. end;
  5899. objsym:=exesym.ObjSymbol;
  5900. Sec:=objsym.objsection;
  5901. Sec.Size:=0;
  5902. Sec.Data.reset;
  5903. { locals }
  5904. Sec.writeUInt8($00);
  5905. for i:=1 to Length(InvokableTypeIndices)-1 do
  5906. { block }
  5907. Sec.writeUInt16BE($0240);
  5908. { block }
  5909. Sec.writeUInt16BE($0240);
  5910. { local.get 0 + br_table }
  5911. WriteBrTable(low(IndirectFunctionTableMap),high(IndirectFunctionTableMap));
  5912. { end }
  5913. Sec.writeUInt8($0B);
  5914. { unreachable }
  5915. Sec.writeUInt8($00);
  5916. for i:=1 to Length(InvokableTypeIndices)-1 do
  5917. begin
  5918. { end }
  5919. Sec.writeUInt8($0B);
  5920. InvokeFuncType(InvokableTypeIndices[i],i=(Length(InvokableTypeIndices)-1));
  5921. end;
  5922. { end }
  5923. Sec.writeUInt8($0B);
  5924. end;
  5925. procedure TWasmExeOutput.WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
  5926. var
  5927. exesecdatapos: LongWord;
  5928. i: Integer;
  5929. objsec: TObjSection;
  5930. dpos, pad: QWord;
  5931. begin
  5932. exesecdatapos:=dynarr.size;
  5933. for i:=0 to exesec.ObjSectionList.Count-1 do
  5934. begin
  5935. objsec:=TObjSection(exesec.ObjSectionList[i]);
  5936. if not (oso_data in objsec.secoptions) then
  5937. internalerror(2024010104);
  5938. if not assigned(objsec.data) then
  5939. internalerror(2024010105);
  5940. dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
  5941. pad:=dpos-dynarr.size;
  5942. { objsection must be within SecAlign bytes from the previous one }
  5943. if (dpos<dynarr.Size) or
  5944. (pad>=max(objsec.SecAlign,1)) then
  5945. internalerror(2024010106);
  5946. writeZeros(dynarr,pad);
  5947. objsec.data.seek(0);
  5948. CopyDynamicArray(objsec.data,dynarr,objsec.data.size);
  5949. end;
  5950. if (dynarr.size-exesecdatapos)<>exesec.Size then
  5951. internalerror(2024010107);
  5952. end;
  5953. {****************************************************************************
  5954. TWasmAssembler
  5955. ****************************************************************************}
  5956. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  5957. begin
  5958. inherited;
  5959. CObjOutput:=TWasmObjOutput;
  5960. end;
  5961. {*****************************************************************************
  5962. Initialize
  5963. *****************************************************************************}
  5964. {$ifdef wasm32}
  5965. const
  5966. as_wasm32_wasm_info : tasminfo =
  5967. (
  5968. id : as_wasm32_wasm;
  5969. idtxt : 'WASM';
  5970. asmbin : '';
  5971. asmcmd : '';
  5972. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  5973. flags : [af_outputbinary,af_smartlink_sections];
  5974. labelprefix : '..@';
  5975. labelmaxlen : -1;
  5976. comment : '; ';
  5977. dollarsign: '$';
  5978. );
  5979. {$endif wasm32}
  5980. initialization
  5981. {$ifdef wasm32}
  5982. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  5983. {$endif wasm32}
  5984. end.