ogwasm.pas 232 KB

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