ogwasm.pas 238 KB

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