ogwasm.pas 236 KB

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