ogwasm.pas 237 KB

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