ogwasm.pas 236 KB

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