123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376 |
- {
- Copyright (c) 2021 by Nikolay Nikolov
- Contains the WebAssembly binary module format reader and writer
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- ****************************************************************************
- }
- unit ogwasm;
- {$i fpcdefs.inc}
- interface
- uses
- { common }
- cclasses,globtype,
- { target }
- systems,cpubase,
- { assembler }
- aasmbase,assemble,aasmcpu,
- { WebAssembly module format definitions }
- wasmbase,
- { output }
- ogbase,
- owbase;
- type
- TWasmObjSymbolExtraData = class;
- TGlobalInitializer = record
- case typ:TWasmBasicType of
- wbt_i32: (init_i32: Int32);
- wbt_i64: (init_i64: Int64);
- wbt_f32: (init_f32: Single);
- wbt_f64: (init_f64: Double);
- end;
- { TWasmObjSymbolLinkingData }
- TWasmObjSymbolLinkingData = class
- public
- ImportModule: string;
- ImportName: string;
- FuncType: TWasmFuncType;
- ExeFunctionIndex: Integer;
- ExeIndirectFunctionTableIndex: Integer;
- ExeTypeIndex: Integer;
- ExeTagIndex: Integer;
- GlobalType: TWasmBasicType;
- GlobalIsMutable: Boolean;
- GlobalInitializer: TGlobalInitializer;
- IsExported: Boolean;
- ExportName: ansistring;
- constructor Create;
- destructor Destroy;override;
- end;
- { TWasmObjSymbol }
- TWasmObjSymbol = class(TObjSymbol)
- FuncIndex: Integer;
- SymbolIndex: Integer;
- GlobalIndex: Integer;
- TagIndex: Integer;
- AliasOf: string;
- ExtraData: TWasmObjSymbolExtraData;
- LinkingData: TWasmObjSymbolLinkingData;
- constructor create(AList:TFPHashObjectList;const AName:string);override;
- destructor Destroy;override;
- function IsAlias: Boolean;
- end;
- { TWasmObjRelocation }
- TWasmObjRelocation = class(TObjRelocation)
- public
- TypeIndex: Integer;
- Addend: LongInt;
- { used during linking }
- FuncType: TWasmFuncType;
- ExeTypeIndex: Integer;
- IsFunctionOffsetI32: Boolean;
- constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
- constructor CreateFuncType(ADataOffset:TObjSectionOfs; AFuncType: TWasmFuncType);
- destructor Destroy;override;
- end;
- { TWasmObjSymbolExtraData }
- TWasmObjSymbolExtraData = class(TFPHashObject)
- TypeIdx: Integer;
- ExceptionTagTypeIdx: Integer;
- ImportModule: string;
- ImportName: string;
- ExportName: string;
- GlobalType: TWasmBasicType;
- GlobalIsImmutable: Boolean;
- Locals: array of TWasmBasicType;
- constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
- procedure AddLocal(bastyp: TWasmBasicType);
- end;
- { TWasmObjSection }
- TWasmObjSection = class(TObjSection)
- public
- SegIdx: Integer;
- SegSymIdx: Integer;
- SegOfs: qword;
- FileSectionOfs: qword;
- MainFuncSymbol: TWasmObjSymbol;
- constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
- function IsCode: Boolean;
- function IsData: Boolean;
- function IsDebug: Boolean;
- end;
- { TWasmFuncTypeTable }
- TWasmFuncTypeTable = class
- private
- FFuncTypes: array of TWasmFuncType;
- function GetCount: Integer;
- function GetItem(Index: Integer): TWasmFuncType;
- public
- destructor Destroy; override;
- function AddOrGetFuncType(wft: TWasmFuncType): integer;
- procedure WriteTo(d: tdynamicarray);
- property Count: Integer read GetCount;
- property Items[Index: Integer]: TWasmFuncType read GetItem; default;
- end;
- { TWasmObjData }
- TWasmObjData = class(TObjData)
- private
- FFuncTypes: TWasmFuncTypeTable;
- FObjSymbolsExtraDataList: TFPHashObjectList;
- FLastFuncName: string;
- function is_smart_section(atype:TAsmSectiontype):boolean;
- function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
- public
- constructor create(const n:string);override;
- destructor destroy; override;
- function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
- procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
- function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
- function globalref(asmsym:TAsmSymbol):TObjSymbol;
- function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
- procedure DeclareGlobalType(gt: tai_globaltype);
- procedure DeclareFuncType(ft: tai_functype);
- procedure DeclareTagType(tt: tai_tagtype);
- procedure DeclareExportName(en: tai_export_name);
- procedure DeclareImportModule(aim: tai_import_module);
- procedure DeclareImportName(ain: tai_import_name);
- procedure DeclareLocal(al: tai_local);
- procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
- property FuncTypes: TWasmFuncTypeTable read FFuncTypes;
- end;
- { TWasmObjOutput }
- TWasmObjOutput = class(tObjOutput)
- private
- FData: TWasmObjData;
- FWasmRelocationCodeTable: tdynamicarray;
- FWasmRelocationCodeTableEntriesCount: Integer;
- FWasmRelocationDataTable: tdynamicarray;
- FWasmRelocationDataTableEntriesCount: Integer;
- FWasmRelocationDebugFrameTable: tdynamicarray;
- FWasmRelocationDebugFrameTableEntriesCount: Integer;
- FWasmRelocationDebugInfoTable: tdynamicarray;
- FWasmRelocationDebugInfoTableEntriesCount: Integer;
- FWasmRelocationDebugLineTable: tdynamicarray;
- FWasmRelocationDebugLineTableEntriesCount: Integer;
- FWasmRelocationDebugAbbrevTable: tdynamicarray;
- FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
- FWasmRelocationDebugArangesTable: tdynamicarray;
- FWasmRelocationDebugArangesTableEntriesCount: Integer;
- FWasmRelocationDebugRangesTable: tdynamicarray;
- FWasmRelocationDebugRangesTableEntriesCount: Integer;
- FWasmRelocationDebugStrTable: tdynamicarray;
- FWasmRelocationDebugStrTableEntriesCount: Integer;
- FWasmSymbolTable: tdynamicarray;
- FWasmSymbolTableEntriesCount: Integer;
- FWasmSections: array [TWasmSectionID] of tdynamicarray;
- FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
- FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
- procedure WriteWasmSection(wsid: TWasmSectionID);
- procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
- function IsExternalFunction(sym: TObjSymbol): Boolean;
- function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
- procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
- procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
- procedure WriteSymbolTable;
- procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
- procedure WriteRelocationDataTable(DataSectionIndex: Integer);
- procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
- procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
- procedure DoRelocations;
- procedure WriteRelocations;
- function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
- protected
- function writeData(Data:TObjData):boolean;override;
- public
- constructor create(AWriter:TObjectWriter);override;
- destructor destroy;override;
- end;
- { TWasmObjInput }
- TWasmObjInput = class(TObjInput)
- private
- FFuncTypes: array of TWasmFuncType;
- public
- constructor create;override;
- destructor Destroy;override;
- class function CanReadObjData(AReader:TObjectreader):boolean;override;
- function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
- end;
- { TWasmExeOutput }
- TWasmExeOutput = class(TExeOutput)
- private
- FImports: TFPHashObjectList;
- FFuncTypes: TWasmFuncTypeTable;
- FFunctionImports: array of record
- ModName: ansistring;
- Name: ansistring;
- TypeIdx: uint32;
- end;
- FTagImports: array of record
- end;
- FIndirectFunctionTable: array of record
- FuncIdx: Integer;
- end;
- FWasmSections: array [TWasmSectionID] of tdynamicarray;
- FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
- FStackPointerSym: TWasmObjSymbol;
- FMinMemoryPages: Integer;
- procedure WriteWasmSection(wsid: TWasmSectionID);
- procedure WriteWasmSectionIfNotEmpty(wsid: TWasmSectionID);
- procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
- procedure PrepareImports;
- procedure PrepareFunctions;
- procedure PrepareTags;
- function AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
- procedure SetStackPointer;
- procedure WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
- protected
- function writeData:boolean;override;
- procedure DoRelocationFixup(objsec:TObjSection);override;
- public
- constructor create;override;
- destructor destroy;override;
- procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
- procedure AfterUnusedSectionRemoval;override;
- procedure MemPos_ExeSection(const aname:string);override;
- procedure Load_Symbol(const aname: string);override;
- end;
- { TWasmAssembler }
- TWasmAssembler = class(tinternalassembler)
- constructor create(info: pasminfo; smart:boolean);override;
- end;
- implementation
- uses
- cutils,verbose,version,globals,ogmap;
- const
- StackPointerSymStr='__stack_pointer';
- procedure WriteUleb5(d: tdynamicarray; v: uint64);
- var
- b: byte;
- i: Integer;
- begin
- for i:=1 to 5 do
- begin
- b:=byte(v) and 127;
- v:=v shr 7;
- if i<>5 then
- b:=b or 128;
- d.write(b,1);
- end;
- end;
- procedure WriteUleb5(d: tobjsection; v: uint64);
- var
- b: byte;
- i: Integer;
- begin
- for i:=1 to 5 do
- begin
- b:=byte(v) and 127;
- v:=v shr 7;
- if i<>5 then
- b:=b or 128;
- d.write(b,1);
- end;
- end;
- procedure WriteSleb5(d: tdynamicarray; v: int64);
- var
- b: byte;
- i: Integer;
- begin
- for i:=1 to 5 do
- begin
- b:=byte(v) and 127;
- v:=SarInt64(v,7);
- if i<>5 then
- b:=b or 128;
- d.write(b,1);
- end;
- end;
- procedure WriteSleb5(d: tobjsection; v: int64);
- var
- b: byte;
- i: Integer;
- begin
- for i:=1 to 5 do
- begin
- b:=byte(v) and 127;
- v:=SarInt64(v,7);
- if i<>5 then
- b:=b or 128;
- d.write(b,1);
- end;
- end;
- procedure WriteUleb(d: tdynamicarray; v: uint64);
- var
- b: byte;
- begin
- repeat
- b:=byte(v) and 127;
- v:=v shr 7;
- if v<>0 then
- b:=b or 128;
- d.write(b,1);
- until v=0;
- end;
- procedure WriteUleb(w: TObjectWriter; v: uint64);
- var
- b: byte;
- begin
- repeat
- b:=byte(v) and 127;
- v:=v shr 7;
- if v<>0 then
- b:=b or 128;
- w.write(b,1);
- until v=0;
- end;
- procedure WriteSleb(d: tdynamicarray; v: int64);
- var
- b: byte;
- Done: Boolean=false;
- begin
- repeat
- b:=byte(v) and 127;
- v:=SarInt64(v,7);
- if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
- Done:=true
- else
- b:=b or 128;
- d.write(b,1);
- until Done;
- end;
- function UlebEncodingSize(v: uint64): Integer;
- var
- b: byte;
- begin
- Result:=0;
- repeat
- b:=byte(v) and 127;
- v:=v shr 7;
- if v<>0 then
- b:=b or 128;
- Inc(Result);
- until v=0;
- end;
- {$ifdef FPC_LITTLE_ENDIAN}
- procedure WriteF32LE(d: tdynamicarray; v: Single);
- begin
- d.write(v,4);
- end;
- procedure WriteF64LE(d: tdynamicarray; v: Double);
- begin
- d.write(v,8);
- end;
- {$else FPC_LITTLE_ENDIAN}
- procedure WriteF32LE(d: tdynamicarray; v: Single);
- var
- tmpI: UInt32;
- begin
- Move(v,tmpI,4);
- tmpI:=SwapEndian(tmpI);
- d.write(tmpI,4);
- end;
- procedure WriteF64LE(d: tdynamicarray; v: Double);
- var
- tmpI: UInt64;
- begin
- Move(v,tmpI,8);
- tmpI:=SwapEndian(tmpI);
- d.write(tmpI,8);
- end;
- {$endif FPC_LITTLE_ENDIAN}
- procedure WriteByte(d: tdynamicarray; b: byte);
- begin
- d.write(b,1);
- end;
- procedure WriteName(d: tdynamicarray; const s: string);
- begin
- WriteUleb(d,Length(s));
- d.writestr(s);
- end;
- procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
- begin
- WriteByte(dest,encode_wasm_basic_type(wbt));
- end;
- procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
- var
- i: Integer;
- begin
- WriteUleb(dest,Length(wrt));
- for i:=low(wrt) to high(wrt) do
- WriteWasmBasicType(dest,wrt[i]);
- end;
- function ReadUleb(d: tdynamicarray): uint64;
- var
- b: byte;
- shift:integer;
- begin
- b:=0;
- result:=0;
- shift:=0;
- repeat
- d.read(b,1);
- result:=result or (uint64(b and 127) shl shift);
- inc(shift,7);
- until (b and 128)=0;
- end;
- function ReadSleb(d: tdynamicarray): int64;
- var
- b: byte;
- shift:integer;
- begin
- b:=0;
- result:=0;
- shift:=0;
- repeat
- d.read(b,1);
- result:=result or (uint64(b and 127) shl shift);
- inc(shift,7);
- until (b and 128)=0;
- {$ifopt Q+}
- {$define overflowon}
- {$Q-}
- {$endif}
- {$ifopt R+}
- {$define rangeon}
- {$R-}
- {$endif}
- if (b and 64)<>0 then
- result:=result or (high(uint64) shl shift);
- end;
- {$ifdef overflowon}
- {$Q+}
- {$undef overflowon}
- {$endif}
- {$ifdef rangeon}
- {$R+}
- {$undef rangeon}
- {$endif}
- procedure AddSleb5(d: tdynamicarray; v: int64);
- var
- q: Int64;
- p: LongWord;
- begin
- p:=d.Pos;
- q:=ReadSleb(d);
- q:=q+v;
- d.seek(p);
- WriteSleb5(d,q);
- end;
- procedure AddUleb5(d: tdynamicarray; v: int64);
- var
- q: UInt64;
- p: LongWord;
- begin
- p:=d.Pos;
- q:=ReadUleb(d);
- q:=q+v;
- d.seek(p);
- WriteUleb5(d,q);
- end;
- procedure AddInt32(d: tdynamicarray; v: int32);
- var
- q: int32;
- p: LongWord;
- begin
- p:=d.Pos;
- d.read(q,4);
- {$ifdef FPC_BIG_ENDIAN}
- q:=SwapEndian(q);
- {$endif FPC_BIG_ENDIAN}
- q:=q+v;
- {$ifdef FPC_BIG_ENDIAN}
- q:=SwapEndian(q);
- {$endif FPC_BIG_ENDIAN}
- d.seek(p);
- d.write(q,4);
- end;
- procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
- var
- buf: array [0..4095] of byte;
- bs: Integer;
- begin
- while size>0 do
- begin
- if size<SizeOf(buf) then
- bs:=Integer(size)
- else
- bs:=SizeOf(buf);
- src.read(buf,bs);
- dest.write(buf,bs);
- dec(size,bs);
- end;
- end;
- procedure WriteZeros(dest: tdynamicarray; size: QWord);
- var
- buf : array[0..1023] of byte;
- bs: Integer;
- begin
- fillchar(buf,sizeof(buf),0);
- while size>0 do
- begin
- if size<SizeOf(buf) then
- bs:=Integer(size)
- else
- bs:=SizeOf(buf);
- dest.write(buf,bs);
- dec(size,bs);
- end;
- end;
- {****************************************************************************
- TWasmObjSymbolLinkingData
- ****************************************************************************}
- constructor TWasmObjSymbolLinkingData.Create;
- begin
- ExeFunctionIndex:=-1;
- ExeIndirectFunctionTableIndex:=-1;
- ExeTypeIndex:=-1;
- ExeTagIndex:=-1;
- end;
- destructor TWasmObjSymbolLinkingData.Destroy;
- begin
- FuncType.Free;
- inherited Destroy;
- end;
- {****************************************************************************
- TWasmObjRelocation
- ****************************************************************************}
- constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
- begin
- DataOffset:=ADataOffset;
- Symbol:=nil;
- OrgSize:=0;
- Group:=nil;
- ObjSection:=nil;
- ftype:=ord(RELOC_TYPE_INDEX_LEB);
- TypeIndex:=ATypeIndex;
- FuncType:=nil;
- ExeTypeIndex:=-1;
- end;
- constructor TWasmObjRelocation.CreateFuncType(ADataOffset: TObjSectionOfs; AFuncType: TWasmFuncType);
- begin
- DataOffset:=ADataOffset;
- Symbol:=nil;
- OrgSize:=0;
- Group:=nil;
- ObjSection:=nil;
- ftype:=ord(RELOC_TYPE_INDEX_LEB);
- TypeIndex:=-1;
- ExeTypeIndex:=-1;
- FuncType:=TWasmFuncType.Create(AFuncType);
- end;
- destructor TWasmObjRelocation.Destroy;
- begin
- FuncType.Free;
- inherited Destroy;
- end;
- {****************************************************************************
- TWasmObjSymbol
- ****************************************************************************}
- constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
- begin
- inherited create(AList,AName);
- FuncIndex:=-1;
- SymbolIndex:=-1;
- GlobalIndex:=-1;
- TagIndex:=-1;
- AliasOf:='';
- ExtraData:=nil;
- LinkingData:=TWasmObjSymbolLinkingData.Create;
- end;
- destructor TWasmObjSymbol.Destroy;
- begin
- LinkingData.Free;
- inherited Destroy;
- end;
- function TWasmObjSymbol.IsAlias: Boolean;
- begin
- result:=AliasOf<>'';
- end;
- {****************************************************************************
- TWasmObjSymbolExtraData
- ****************************************************************************}
- constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
- begin
- inherited Create(HashObjectList,s);
- TypeIdx:=-1;
- ExceptionTagTypeIdx:=-1;
- end;
- procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
- begin
- SetLength(Locals,Length(Locals)+1);
- Locals[High(Locals)]:=bastyp;
- end;
- {****************************************************************************
- TWasmObjSection
- ****************************************************************************}
- constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
- begin
- inherited create(AList, Aname, Aalign, Aoptions);
- SegIdx:=-1;
- SegSymIdx:=-1;
- MainFuncSymbol:=nil;
- end;
- function TWasmObjSection.IsCode: Boolean;
- const
- CodePrefix = '.text';
- begin
- result:=(Length(Name)>=Length(CodePrefix)) and
- (Copy(Name,1,Length(CodePrefix))=CodePrefix);
- end;
- function TWasmObjSection.IsData: Boolean;
- begin
- result:=not (IsCode or IsDebug);
- end;
- function TWasmObjSection.IsDebug: Boolean;
- const
- DebugPrefix = '.debug';
- begin
- result:=(Length(Name)>=Length(DebugPrefix)) and
- (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
- end;
- {****************************************************************************
- TWasmFuncTypeTable
- ****************************************************************************}
- function TWasmFuncTypeTable.GetCount: Integer;
- begin
- Result:=Length(FFuncTypes);
- end;
- function TWasmFuncTypeTable.GetItem(Index: Integer): TWasmFuncType;
- begin
- if (Index<Low(FFuncTypes)) or (Index>High(FFuncTypes)) then
- internalerror(2023123101);
- Result:=FFuncTypes[Index];
- end;
- destructor TWasmFuncTypeTable.Destroy;
- var
- i: Integer;
- begin
- for i:=low(FFuncTypes) to high(FFuncTypes) do
- begin
- FFuncTypes[i].free;
- FFuncTypes[i]:=nil;
- end;
- end;
- function TWasmFuncTypeTable.AddOrGetFuncType(wft: TWasmFuncType): integer;
- var
- i: Integer;
- begin
- for i:=low(FFuncTypes) to high(FFuncTypes) do
- if wft.Equals(FFuncTypes[i]) then
- exit(i);
- result:=Length(FFuncTypes);
- SetLength(FFuncTypes,result+1);
- FFuncTypes[result]:=TWasmFuncType.Create(wft);
- end;
- procedure TWasmFuncTypeTable.WriteTo(d: tdynamicarray);
- var
- types_count, i: Integer;
- begin
- types_count:=Count;
- WriteUleb(d,types_count);
- for i:=0 to types_count-1 do
- with Items[i] do
- begin
- WriteByte(d,$60);
- WriteWasmResultType(d,params);
- WriteWasmResultType(d,results);
- end;
- end;
- {****************************************************************************
- TWasmObjData
- ****************************************************************************}
- function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
- begin
- { For bss we need to set some flags that are target dependent,
- it is easier to disable it for smartlinking. It doesn't take up
- filespace }
- result:=not(target_info.system in systems_darwin) and
- create_smartlink_sections and
- (atype<>sec_toc) and
- (atype<>sec_user) and
- { on embedded systems every byte counts, so smartlink bss too }
- ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
- end;
- function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
- const aname: string; aorder: TAsmSectionOrder): string;
- const
- secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
- '.text',
- '.data',
- { why doesn't .rodata work? (FK) }
- { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
- { vtables (and anything else containing relocations), otherwise those are }
- { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
- { vtable for a class called Window: }
- { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
- { TODO: .data.ro not yet working}
- {$if defined(arm) or defined(riscv64) or defined(powerpc)}
- '.rodata',
- {$else defined(arm) or defined(riscv64) or defined(powerpc)}
- '.data',
- {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
- '.rodata',
- '.bss',
- '.tbss',
- '.pdata',
- '', { stubs }
- '__DATA,__nl_symbol_ptr',
- '__DATA,__la_symbol_ptr',
- '__DATA,__mod_init_func',
- '__DATA,__mod_term_func',
- '.stab',
- '.stabstr',
- '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
- '.eh_frame',
- '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges','.debug_loc','.debug_loclists',
- '.fpc',
- '.toc',
- '.init',
- '.fini',
- '.objc_class',
- '.objc_meta_class',
- '.objc_cat_cls_meth',
- '.objc_cat_inst_meth',
- '.objc_protocol',
- '.objc_string_object',
- '.objc_cls_meth',
- '.objc_inst_meth',
- '.objc_cls_refs',
- '.objc_message_refs',
- '.objc_symbols',
- '.objc_category',
- '.objc_class_vars',
- '.objc_instance_vars',
- '.objc_module_info',
- '.objc_class_names',
- '.objc_meth_var_types',
- '.objc_meth_var_names',
- '.objc_selector_strs',
- '.objc_protocol_ext',
- '.objc_class_ext',
- '.objc_property',
- '.objc_image_info',
- '.objc_cstring_object',
- '.objc_sel_fixup',
- '__DATA,__objc_data',
- '__DATA,__objc_const',
- '.objc_superrefs',
- '__DATA, __datacoal_nt,coalesced',
- '.objc_classlist',
- '.objc_nlclasslist',
- '.objc_catlist',
- '.obcj_nlcatlist',
- '.objc_protolist',
- '.stack',
- '.heap',
- '.gcc_except_table',
- '.ARM.attributes'
- );
- var
- sep : string[3];
- secname : string;
- begin
- secname:=secnames[atype];
- if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
- begin
- result:=secname+'.'+aname;
- exit;
- end;
- { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
- Thus, data which normally goes into .rodata and .rodata_norel sections must
- end up in .data section }
- if (atype in [sec_rodata,sec_rodata_norel]) and
- (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
- secname:='.data';
- { Windows correctly handles reallocations in readonly sections }
- if (atype=sec_rodata) and
- (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
- secname:='.rodata';
- { section type user gives the user full controll on the section name }
- if atype=sec_user then
- secname:=aname;
- if is_smart_section(atype) and (aname<>'') then
- begin
- case aorder of
- secorder_begin :
- sep:='.b_';
- secorder_end :
- sep:='.z_';
- else
- sep:='.n_';
- end;
- result:=secname+sep+aname
- end
- else
- result:=secname;
- end;
- constructor TWasmObjData.create(const n: string);
- begin
- inherited;
- CObjSection:=TWasmObjSection;
- CObjSymbol:=TWasmObjSymbol;
- FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
- FFuncTypes:=TWasmFuncTypeTable.Create;
- end;
- destructor TWasmObjData.destroy;
- var
- i: Integer;
- begin
- FObjSymbolsExtraDataList.Free;
- FFuncTypes.Free;
- inherited destroy;
- end;
- function TWasmObjData.sectionname(atype: TAsmSectiontype;
- const aname: string; aorder: TAsmSectionOrder): string;
- begin
- if (atype=sec_fpc) or
- ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
- atype:=sec_data;
- Result:=sectionname_gas(atype, aname, aorder);
- end;
- procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
- p: TObjSymbol; Reloctype: TObjRelocationType);
- const
- leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
- var
- objreloc: TWasmObjRelocation;
- begin
- if CurrObjSec=nil then
- internalerror(200403072);
- { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
- todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
- if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
- Reloctype:=RELOC_ABSOLUTE;
- objreloc:=nil;
- case Reloctype of
- RELOC_FUNCTION_INDEX_LEB:
- begin
- if Data<>0 then
- internalerror(2021092502);
- if len<>5 then
- internalerror(2021092503);
- if not assigned(p) then
- internalerror(2021092504);
- objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
- CurrObjSec.ObjRelocations.Add(objreloc);
- writebytes(leb_zero,5);
- end;
- RELOC_MEMORY_ADDR_LEB,
- RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
- begin
- if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
- internalerror(2021092602);
- if len<>5 then
- internalerror(2021092503);
- if not assigned(p) then
- internalerror(2021092504);
- objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
- objreloc.Addend:=Data;
- CurrObjSec.ObjRelocations.Add(objreloc);
- if RelocType=RELOC_MEMORY_ADDR_LEB then
- WriteUleb5(CurrObjSec,Data)
- else
- WriteSleb5(CurrObjSec,Data);
- end;
- RELOC_ABSOLUTE:
- begin
- if len<>4 then
- internalerror(2021092607);
- if not assigned(p) then
- internalerror(2021092608);
- if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
- (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
- begin
- objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
- objreloc.Addend:=Data+p.Address;
- CurrObjSec.ObjRelocations.Add(objreloc);
- {inc(data,p.address);}
- data:=0;
- Data:=NtoLE(Data);
- writebytes(Data,4);
- end
- else
- begin
- objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
- objreloc.Addend:=Data;
- CurrObjSec.ObjRelocations.Add(objreloc);
- Data:=NtoLE(Data);
- writebytes(Data,4);
- end;
- end;
- RELOC_TYPE_INDEX_LEB:
- begin
- if len<>5 then
- internalerror(2021092612);
- if assigned(p) then
- internalerror(2021092613);
- objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
- CurrObjSec.ObjRelocations.Add(objreloc);
- WriteUleb5(CurrObjSec,Data);
- end;
- RELOC_GLOBAL_INDEX_LEB:
- begin
- if len<>5 then
- internalerror(2021092701);
- if Data<>0 then
- internalerror(2021092702);
- if not assigned(p) then
- internalerror(2021092703);
- objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
- CurrObjSec.ObjRelocations.Add(objreloc);
- WriteUleb5(CurrObjSec,0);
- end;
- RELOC_TAG_INDEX_LEB:
- begin
- if len<>5 then
- internalerror(2021092712);
- if Data<>0 then
- internalerror(2021092713);
- if not assigned(p) then
- internalerror(2021092714);
- objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
- CurrObjSec.ObjRelocations.Add(objreloc);
- WriteSleb5(CurrObjSec,0);
- end;
- else
- internalerror(2021092501);
- end;
- end;
- function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
- begin
- result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
- if not assigned(result) then
- result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
- end;
- function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
- begin
- if assigned(asmsym) then
- begin
- if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
- internalerror(2021092706);
- result:=symbolref(asmsym);
- result.typ:=asmsym.typ;
- end
- else
- result:=nil;
- end;
- function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
- begin
- if assigned(asmsym) then
- begin
- if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
- internalerror(2021092707);
- result:=symbolref(asmsym);
- result.typ:=AT_WASM_EXCEPTION_TAG;
- end
- else
- result:=nil;
- end;
- procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- ObjSym: TObjSymbol;
- begin
- if not gt.is_external then
- begin
- ObjSym:=symboldefine(gt.sym);
- ObjSym.typ:=AT_WASM_GLOBAL;
- end;
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
- ObjSymExtraData.GlobalType:=gt.gtype;
- ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
- end;
- procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
- var
- i: Integer;
- ObjSymExtraData: TWasmObjSymbolExtraData;
- begin
- FLastFuncName:=ft.funcname;
- i:=FFuncTypes.AddOrGetFuncType(ft.functype);
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
- ObjSymExtraData.TypeIdx:=i;
- end;
- procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- ft: TWasmFuncType;
- i: Integer;
- begin
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
- ft:=TWasmFuncType.Create([],tt.params);
- i:=FFuncTypes.AddOrGetFuncType(ft);
- ft.free;
- ObjSymExtraData.ExceptionTagTypeIdx:=i;
- end;
- procedure TWasmObjData.DeclareExportName(en: tai_export_name);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- begin
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
- ObjSymExtraData.ExportName:=en.extname;
- end;
- procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- begin
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
- ObjSymExtraData.ImportModule:=aim.importmodule;
- end;
- procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- begin
- ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
- ObjSymExtraData.ImportName:=ain.importname;
- end;
- procedure TWasmObjData.DeclareLocal(al: tai_local);
- var
- ObjSymExtraData: TWasmObjSymbolExtraData;
- begin
- ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
- ObjSymExtraData.AddLocal(al.bastyp);
- end;
- procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
- var
- valsym: TObjSymbol;
- aliassym: TWasmObjSymbol;
- begin
- valsym:=CreateSymbol(avalue);
- aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
- aliassym.AliasOf:=valsym.Name;
- end;
- {****************************************************************************
- TWasmObjOutput
- ****************************************************************************}
- procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
- var
- b: byte;
- begin
- b:=ord(wsid);
- Writer.write(b,1);
- WriteUleb(Writer,FWasmSections[wsid].size);
- Writer.writearray(FWasmSections[wsid]);
- end;
- procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
- var
- b: byte;
- begin
- b:=0;
- Writer.write(b,1);
- WriteUleb(Writer,FWasmCustomSections[wcst].size);
- Writer.writearray(FWasmCustomSections[wcst]);
- end;
- function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
- var
- ExtraData: TWasmObjSymbolExtraData;
- begin
- if sym.bind=AB_EXTERNAL then
- begin
- ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
- result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
- end
- else
- result:=false;
- end;
- function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
- var
- ExtraData: TWasmObjSymbolExtraData;
- begin
- if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
- begin
- ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
- result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
- end
- else
- result:=false;
- end;
- procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
- var
- i,
- rle_entries,
- cnt: Integer;
- lasttype: TWasmBasicType;
- begin
- if Length(ed.Locals)=0 then
- begin
- WriteUleb(dest,0);
- exit;
- end;
- rle_entries:=1;
- for i:=low(ed.Locals)+1 to high(ed.Locals) do
- if ed.Locals[i]<>ed.Locals[i-1] then
- inc(rle_entries);
- WriteUleb(dest,rle_entries);
- lasttype:=ed.Locals[Low(ed.Locals)];
- cnt:=1;
- for i:=low(ed.Locals)+1 to high(ed.Locals) do
- if ed.Locals[i]=ed.Locals[i-1] then
- inc(cnt)
- else
- begin
- WriteUleb(dest,cnt);
- WriteWasmBasicType(dest,lasttype);
- lasttype:=ed.Locals[i];
- cnt:=1;
- end;
- WriteUleb(dest,cnt);
- WriteWasmBasicType(dest,lasttype);
- end;
- procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
- var
- encoded_locals: tdynamicarray;
- ObjSymExtraData: TWasmObjSymbolExtraData;
- codelen: LongWord;
- ObjSection: TWasmObjSection;
- codeexprlen: QWord;
- begin
- ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- ObjSection:=TWasmObjSection(objsym.objsection);
- ObjSection.Data.seek(objsym.address);
- codeexprlen:=objsym.size;
- encoded_locals:=tdynamicarray.Create(64);
- WriteFunctionLocals(encoded_locals,ObjSymExtraData);
- codelen:=encoded_locals.size+codeexprlen+1;
- WriteUleb(dest,codelen);
- encoded_locals.seek(0);
- CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
- ObjSection.FileSectionOfs:=dest.size-objsym.offset;
- CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
- WriteByte(dest,$0B);
- encoded_locals.Free;
- end;
- procedure TWasmObjOutput.WriteSymbolTable;
- begin
- WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
- FWasmSymbolTable.seek(0);
- CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
- end;
- procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
- begin
- WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
- WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
- FWasmRelocationCodeTable.seek(0);
- CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
- end;
- procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
- begin
- WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
- WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
- FWasmRelocationDataTable.seek(0);
- CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
- end;
- procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
- begin
- if EntriesCount>0 then
- begin
- WriteUleb(FWasmCustomSections[cst],SectionIndex);
- WriteUleb(FWasmCustomSections[cst],EntriesCount);
- Table.seek(0);
- CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
- WriteWasmCustomSection(cst);
- end;
- end;
- procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
- begin
- if FWasmLinkingSubsections[wlst].size>0 then
- begin
- WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
- WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
- FWasmLinkingSubsections[wlst].seek(0);
- CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
- end;
- end;
- procedure TWasmObjOutput.DoRelocations;
- var
- si, ri: Integer;
- objsec: TWasmObjSection;
- objrel: TWasmObjRelocation;
- begin
- for si:=0 to FData.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(FData.ObjSectionList[si]);
- for ri:=0 to objsec.ObjRelocations.Count-1 do
- begin
- objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
- case objrel.typ of
- RELOC_FUNCTION_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092509);
- objsec.Data.seek(objrel.DataOffset);
- if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
- message1(asmw_e_illegal_unset_index,objrel.symbol.name)
- else
- WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
- end;
- RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092605);
- if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
- begin
- objsec.Data.seek(objrel.DataOffset);
- AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
- end;
- end;
- RELOC_MEMORY_ADDR_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092606);
- if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
- internalerror(2021092628);
- if objrel.symbol.bind<>AB_EXTERNAL then
- begin
- objsec.Data.seek(objrel.DataOffset);
- AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
- end;
- end;
- RELOC_ABSOLUTE:
- begin
- if assigned(objrel.ObjSection) then
- begin
- { todo: should we do something here? }
- //Writeln('todo: section relocation');
- end
- else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
- begin
- objsec.Data.seek(objrel.DataOffset);
- AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
- end;
- end;
- RELOC_TYPE_INDEX_LEB:
- ;
- RELOC_GLOBAL_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092509);
- objsec.Data.seek(objrel.DataOffset);
- if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
- message1(asmw_e_illegal_unset_index,objrel.symbol.name)
- else
- WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
- end;
- RELOC_TAG_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092716);
- objsec.Data.seek(objrel.DataOffset);
- if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
- message1(asmw_e_illegal_unset_index,objrel.symbol.name)
- else
- WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
- end;
- else
- internalerror(2021092510);
- end;
- end;
- end;
- end;
- procedure TWasmObjOutput.WriteRelocations;
- var
- si, ri: Integer;
- objsec: TWasmObjSection;
- objrel: TWasmObjRelocation;
- relout: tdynamicarray;
- relcount: PInteger;
- FuncSym: TWasmObjSymbol;
- begin
- for si:=0 to FData.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(FData.ObjSectionList[si]);
- if objsec.IsCode then
- begin
- relout:=FWasmRelocationCodeTable;
- relcount:=@FWasmRelocationCodeTableEntriesCount;
- end
- else if objsec.IsData then
- begin
- relout:=FWasmRelocationDataTable;
- relcount:=@FWasmRelocationDataTableEntriesCount;
- end
- else if objsec.IsDebug then
- begin
- case objsec.Name of
- '.debug_frame':
- begin
- relout:=FWasmRelocationDebugFrameTable;
- relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
- end;
- '.debug_info':
- begin
- relout:=FWasmRelocationDebugInfoTable;
- relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
- end;
- '.debug_line':
- begin
- relout:=FWasmRelocationDebugLineTable;
- relcount:=@FWasmRelocationDebugLineTableEntriesCount;
- end;
- '.debug_abbrev':
- begin
- relout:=FWasmRelocationDebugAbbrevTable;
- relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
- end;
- '.debug_aranges':
- begin
- relout:=FWasmRelocationDebugArangesTable;
- relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
- end;
- '.debug_ranges':
- begin
- relout:=FWasmRelocationDebugRangesTable;
- relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
- end;
- '.debug_str':
- begin
- relout:=FWasmRelocationDebugStrTable;
- relcount:=@FWasmRelocationDebugStrTableEntriesCount;
- end;
- else
- internalerror(2022071601);
- end;
- end
- else
- continue;
- for ri:=0 to objsec.ObjRelocations.Count-1 do
- begin
- objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
- case objrel.typ of
- RELOC_FUNCTION_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092508);
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- end;
- RELOC_MEMORY_ADDR_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092603);
- Inc(relcount^);
- if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
- internalerror(2021092628);
- WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- WriteSleb(relout,objrel.Addend); { addend to add to the address }
- end;
- RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092604);
- Inc(relcount^);
- if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
- begin
- WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- end
- else
- begin
- WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- WriteSleb(relout,objrel.Addend); { addend to add to the address }
- end;
- end;
- RELOC_ABSOLUTE:
- begin
- // todo: figure this out, why do these exist?
- //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
- // Writeln('!!! ', objrel.symbol.name);
- if assigned(objrel.objsection) then
- begin
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
- message1(asmw_e_illegal_unset_index,objrel.objsection.name)
- else
- WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
- WriteSleb(relout,objrel.Addend); { addend to add to the address }
- end
- else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
- begin
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- end
- else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
- begin
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
- if FuncSym.SymbolIndex<0 then
- message1(asmw_e_illegal_unset_index,FuncSym.Name)
- else
- WriteUleb(relout,FuncSym.SymbolIndex);
- WriteSleb(relout,objrel.Addend+objrel.symbol.address); { addend to add to the address }
- end
- else
- begin
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
- begin
- Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
- message1(asmw_e_illegal_unset_index,objrel.symbol.name);
- end
- else
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- WriteSleb(relout,objrel.Addend); { addend to add to the address }
- end;
- end;
- RELOC_TYPE_INDEX_LEB:
- begin
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- WriteUleb(relout,objrel.TypeIndex);
- end;
- RELOC_GLOBAL_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092704);
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
- message1(asmw_e_illegal_unset_index,objrel.symbol.name)
- else
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- end;
- RELOC_TAG_INDEX_LEB:
- begin
- if not assigned(objrel.symbol) then
- internalerror(2021092717);
- Inc(relcount^);
- WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
- WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
- if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
- message1(asmw_e_illegal_unset_index,objrel.symbol.name)
- else
- WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
- end;
- else
- internalerror(2021092507);
- end;
- end;
- end;
- end;
- function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
- begin
- Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
- end;
- function TWasmObjOutput.writeData(Data:TObjData):boolean;
- var
- section_nr: Integer;
- procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
- var
- objsec: TWasmObjSection;
- begin
- objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
- if Assigned(objsec) then
- begin
- debug_section_nr:=section_nr;
- Inc(section_nr);
- objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
- WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
- WriteUleb(FWasmSymbolTable,debug_section_nr);
- end;
- end;
- procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
- var
- objsec: TWasmObjSection;
- begin
- objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
- if Assigned(objsec) then
- begin
- if oso_Data in objsec.SecOptions then
- begin
- objsec.Data.seek(0);
- CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
- end
- else
- WriteZeros(FWasmCustomSections[st],objsec.Size);
- WriteWasmCustomSection(st);
- end;
- end;
- var
- i: Integer;
- objsec: TWasmObjSection;
- segment_count: Integer = 0;
- cur_seg_ofs: qword = 0;
- imports_count, NextImportFunctionIndex, NextFunctionIndex,
- code_section_nr, data_section_nr,
- debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
- debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
- debug_ranges_section_nr,
- NextGlobalIndex, NextTagIndex: Integer;
- import_globals_count: Integer = 0;
- globals_count: Integer = 0;
- import_functions_count: Integer = 0;
- export_functions_count: Integer = 0;
- functions_count: Integer = 0;
- import_exception_tags_count: Integer = 0;
- exception_tags_count: Integer = 0;
- objsym, ObjSymAlias: TWasmObjSymbol;
- cust_sec: TWasmCustomSectionType;
- SegmentFlags, SymbolFlags: UInt64;
- begin
- FData:=TWasmObjData(Data);
- { each custom sections starts with its name }
- for cust_sec in TWasmCustomSectionType do
- WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
- WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if objsym.typ=AT_WASM_EXCEPTION_TAG then
- if objsym.bind=AB_EXTERNAL then
- Inc(import_exception_tags_count)
- else
- Inc(exception_tags_count);
- if objsym.typ=AT_WASM_GLOBAL then
- if objsym.bind=AB_EXTERNAL then
- Inc(import_globals_count)
- else
- Inc(globals_count);
- if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
- Inc(import_globals_count);
- if IsExternalFunction(objsym) then
- Inc(import_functions_count);
- if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
- begin
- TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
- Inc(functions_count);
- end;
- if IsExportedFunction(objsym) then
- Inc(export_functions_count);
- end;
- FData.FFuncTypes.WriteTo(FWasmSections[wsiType]);
- for i:=0 to Data.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(Data.ObjSectionList[i]);
- if objsec.IsCode then
- objsec.SegIdx:=-1
- else if objsec.IsData then
- begin
- objsec.SegIdx:=segment_count;
- objsec.SegOfs:=cur_seg_ofs;
- Inc(segment_count);
- Inc(cur_seg_ofs,objsec.Size);
- end;
- end;
- imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
- WriteUleb(FWasmSections[wsiImport],imports_count);
- { import memories }
- WriteName(FWasmSections[wsiImport],'env');
- WriteName(FWasmSections[wsiImport],'__linear_memory');
- WriteByte(FWasmSections[wsiImport],$02); { mem }
- WriteByte(FWasmSections[wsiImport],$00); { min }
- WriteUleb(FWasmSections[wsiImport],1); { 1 page }
- { import globals }
- NextGlobalIndex:=0;
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
- begin
- objsym.GlobalIndex:=NextGlobalIndex;
- Inc(NextGlobalIndex);
- objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- if objsym.ExtraData.ImportModule<>'' then
- WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
- else
- WriteName(FWasmSections[wsiImport],'env');
- WriteName(FWasmSections[wsiImport],objsym.Name);
- WriteByte(FWasmSections[wsiImport],$03); { global }
- WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
- if objsym.ExtraData.GlobalIsImmutable then
- WriteByte(FWasmSections[wsiImport],$00) { const }
- else
- WriteByte(FWasmSections[wsiImport],$01); { var }
- end
- else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
- begin
- objsym.GlobalIndex:=NextGlobalIndex;
- Inc(NextGlobalIndex);
- objsym.ExtraData:=nil;
- WriteName(FWasmSections[wsiImport],'GOT.mem');
- WriteName(FWasmSections[wsiImport],objsym.Name);
- WriteByte(FWasmSections[wsiImport],$03); { global }
- WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
- WriteByte(FWasmSections[wsiImport],$01); { var }
- end;
- end;
- { import functions }
- NextImportFunctionIndex:=0;
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if IsExternalFunction(objsym) then
- begin
- objsym.FuncIndex:=NextImportFunctionIndex;
- Inc(NextImportFunctionIndex);
- objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- if objsym.ExtraData.ImportModule<>'' then
- WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
- else
- WriteName(FWasmSections[wsiImport],'env');
- WriteName(FWasmSections[wsiImport],objsym.Name);
- WriteByte(FWasmSections[wsiImport],$00); { func }
- WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
- end;
- end;
- { import tables }
- WriteName(FWasmSections[wsiImport],'env');
- WriteName(FWasmSections[wsiImport],'__indirect_function_table');
- WriteByte(FWasmSections[wsiImport],$01); { table }
- WriteByte(FWasmSections[wsiImport],$70); { funcref }
- WriteByte(FWasmSections[wsiImport],$00); { min }
- WriteUleb(FWasmSections[wsiImport],1); { 1 }
- { import tags }
- NextTagIndex:=0;
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
- begin
- objsym.TagIndex:=NextTagIndex;
- Inc(NextTagIndex);
- objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- if objsym.ExtraData.ImportModule<>'' then
- WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
- else
- WriteName(FWasmSections[wsiImport],'env');
- WriteName(FWasmSections[wsiImport],objsym.Name);
- WriteByte(FWasmSections[wsiImport],$04); { tag }
- WriteByte(FWasmSections[wsiImport],$00); { exception }
- WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
- end;
- end;
- WriteUleb(FWasmSections[wsiFunction],functions_count);
- NextFunctionIndex:=NextImportFunctionIndex;
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
- begin
- objsym.FuncIndex:=NextFunctionIndex;
- Inc(NextFunctionIndex);
- WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
- end;
- end;
- if exception_tags_count>0 then
- begin
- WriteUleb(FWasmSections[wsiTag],exception_tags_count);
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
- begin
- objsym.TagIndex:=NextTagIndex;
- Inc(NextTagIndex);
- objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- WriteByte(FWasmSections[wsiTag],$00); { exception }
- WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
- end;
- end;
- end;
- if globals_count>0 then
- begin
- WriteUleb(FWasmSections[wsiGlobal],globals_count);
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
- begin
- objsym.GlobalIndex:=NextGlobalIndex;
- Inc(NextGlobalIndex);
- objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
- WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
- if objsym.ExtraData.GlobalIsImmutable then
- WriteByte(FWasmSections[wsiGlobal],$00) { const }
- else
- WriteByte(FWasmSections[wsiGlobal],$01); { var }
- { init expr }
- case objsym.ExtraData.GlobalType of
- wbt_i32:
- begin
- WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
- WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- wbt_i64:
- begin
- WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
- WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- wbt_f32:
- begin
- WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
- WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- wbt_f64:
- begin
- WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
- WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$00);
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- wbt_externref:
- begin
- WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
- WriteByte(FWasmSections[wsiGlobal],$6F);
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- wbt_funcref:
- begin
- WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
- WriteByte(FWasmSections[wsiGlobal],$70);
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- else
- internalerror(2022052801);
- end;
- end;
- end;
- end;
- if export_functions_count>0 then
- begin
- WriteUleb(FWasmSections[wsiExport],export_functions_count);
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if IsExportedFunction(objsym) then
- begin
- WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
- WriteByte(FWasmSections[wsiExport],0); { func }
- if (objsym.FuncIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
- end;
- end;
- end;
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if objsym.typ=AT_WASM_EXCEPTION_TAG then
- begin
- objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
- if objsym.bind=AB_GLOBAL then
- WriteUleb(FWasmSymbolTable,0)
- else if objsym.bind=AB_LOCAL then
- WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
- else if objsym.bind=AB_EXTERNAL then
- WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
- else if objsym.bind=AB_WEAK then
- WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
- else
- internalerror(2021092715);
- if (objsym.TagIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.TagIndex);
- if objsym.bind<>AB_EXTERNAL then
- WriteName(FWasmSymbolTable,objsym.Name);
- end
- else if objsym.typ=AT_WASM_GLOBAL then
- begin
- objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
- if objsym.bind=AB_EXTERNAL then
- begin
- WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
- if (objsym.GlobalIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
- end
- else
- begin
- WriteUleb(FWasmSymbolTable,0);
- if (objsym.GlobalIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
- WriteName(FWasmSymbolTable,objsym.Name);
- end;
- end
- else if IsExternalFunction(objsym) then
- begin
- objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
- if objsym.ExtraData.ImportModule<>'' then
- begin
- WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
- if (objsym.FuncIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
- WriteName(FWasmSymbolTable,objsym.Name);
- end
- else
- begin
- WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
- if (objsym.FuncIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
- end;
- end
- else if objsym.typ=AT_FUNCTION then
- begin
- objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
- if objsym.IsAlias then
- begin
- ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
- ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
- WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
- WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
- end
- else
- begin
- if IsExportedFunction(objsym) then
- WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
- else
- WriteUleb(FWasmSymbolTable,0);
- if (objsym.FuncIndex<0) then
- message1(asmw_e_illegal_unset_index,objsym.name)
- else
- WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
- end;
- WriteName(FWasmSymbolTable,objsym.Name);
- end
- else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
- begin
- if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
- begin
- {todo: debug symbols}
- end
- else
- begin
- objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
- Inc(FWasmSymbolTableEntriesCount);
- WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
- if objsym.bind=AB_GLOBAL then
- SymbolFlags:=0
- else if objsym.bind=AB_LOCAL then
- SymbolFlags:=WASM_SYM_BINDING_LOCAL
- else if objsym.bind=AB_EXTERNAL then
- SymbolFlags:=WASM_SYM_UNDEFINED
- else
- internalerror(2021092506);
- if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
- SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
- WriteUleb(FWasmSymbolTable,SymbolFlags);
- WriteName(FWasmSymbolTable,objsym.Name);
- if objsym.bind<>AB_EXTERNAL then
- begin
- WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
- WriteUleb(FWasmSymbolTable,objsym.offset);
- WriteUleb(FWasmSymbolTable,objsym.size);
- end;
- end;
- end;
- end;
- Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
- Writer.write(WasmVersion,SizeOf(WasmVersion));
- if ts_wasm_threads in current_settings.targetswitches then
- begin
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
- end
- else
- begin
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
- WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
- WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
- end;
- { Write the producers section:
- https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
- WriteUleb(FWasmCustomSections[wcstProducers],2);
- WriteName(FWasmCustomSections[wcstProducers],'language');
- WriteUleb(FWasmCustomSections[wcstProducers],1);
- WriteName(FWasmCustomSections[wcstProducers],'Pascal');
- WriteName(FWasmCustomSections[wcstProducers],'');
- WriteName(FWasmCustomSections[wcstProducers],'processed-by');
- WriteUleb(FWasmCustomSections[wcstProducers],1);
- WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
- WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
- code_section_nr:=-1;
- data_section_nr:=-1;
- debug_abbrev_section_nr:=-1;
- debug_info_section_nr:=-1;
- debug_str_section_nr:=-1;
- debug_line_section_nr:=-1;
- debug_frame_section_nr:=-1;
- debug_aranges_section_nr:=-1;
- debug_ranges_section_nr:=-1;
- section_nr:=0;
- WriteWasmSection(wsiType);
- Inc(section_nr);
- WriteWasmSection(wsiImport);
- Inc(section_nr);
- WriteWasmSection(wsiFunction);
- Inc(section_nr);
- if exception_tags_count>0 then
- begin
- WriteWasmSection(wsiTag);
- Inc(section_nr);
- end;
- if globals_count>0 then
- begin
- WriteWasmSection(wsiGlobal);
- Inc(section_nr);
- end;
- if export_functions_count>0 then
- begin
- WriteWasmSection(wsiExport);
- Inc(section_nr);
- end;
- { determine the section numbers for the datacount, code, data and debug sections ahead of time }
- if segment_count>0 then
- Inc(section_nr); { the DataCount section }
- code_section_nr:=section_nr; { the Code section }
- Inc(section_nr);
- if segment_count>0 then
- begin
- data_section_nr:=section_nr; { the Data section }
- Inc(section_nr);
- end;
- { the debug sections }
- MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
- MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
- DoRelocations;
- if segment_count>0 then
- begin
- WriteUleb(FWasmSections[wsiData],segment_count);
- WriteUleb(FWasmSections[wsiDataCount],segment_count);
- WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
- for i:=0 to Data.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(Data.ObjSectionList[i]);
- if objsec.IsData then
- begin
- WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
- WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
- SegmentFlags:=0;
- if (ts_wasm_threads in current_settings.targetswitches) and
- (oso_threadvar in objsec.SecOptions) then
- SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
- WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
- WriteByte(FWasmSections[wsiData],0);
- WriteByte(FWasmSections[wsiData],$41);
- WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
- WriteByte(FWasmSections[wsiData],$0b);
- WriteUleb(FWasmSections[wsiData],objsec.Size);
- objsec.FileSectionOfs:=FWasmSections[wsiData].size;
- if oso_Data in objsec.SecOptions then
- begin
- objsec.Data.seek(0);
- CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
- end
- else
- begin
- WriteZeros(FWasmSections[wsiData],objsec.Size);
- end;
- end;
- end;
- end;
- WriteUleb(FWasmSections[wsiCode],functions_count);
- for i:=0 to Data.ObjSymbolList.Count-1 do
- begin
- objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
- if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
- WriteFunctionCode(FWasmSections[wsiCode],objsym);
- end;
- if segment_count>0 then
- WriteWasmSection(wsiDataCount);
- WriteWasmSection(wsiCode);
- if segment_count>0 then
- WriteWasmSection(wsiData);
- MaybeWriteDebugSection(wcstDebugAbbrev);
- MaybeWriteDebugSection(wcstDebugInfo);
- MaybeWriteDebugSection(wcstDebugStr);
- MaybeWriteDebugSection(wcstDebugLine);
- MaybeWriteDebugSection(wcstDebugFrame);
- MaybeWriteDebugSection(wcstDebugAranges);
- MaybeWriteDebugSection(wcstDebugRanges);
- WriteRelocations;
- WriteSymbolTable;
- WriteLinkingSubsection(WASM_SYMBOL_TABLE);
- if segment_count>0 then
- WriteLinkingSubsection(WASM_SEGMENT_INFO);
- WriteRelocationCodeTable(code_section_nr);
- if segment_count>0 then
- WriteRelocationDataTable(data_section_nr);
- WriteWasmCustomSection(wcstLinking);
- Inc(section_nr);
- WriteWasmCustomSection(wcstRelocCode);
- Inc(section_nr);
- if segment_count>0 then
- begin
- WriteWasmCustomSection(wcstRelocData);
- Inc(section_nr);
- end;
- MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
- MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
- WriteWasmCustomSection(wcstProducers);
- Inc(section_nr);
- WriteWasmCustomSection(wcstTargetFeatures);
- Inc(section_nr);
- result:=true;
- end;
- constructor TWasmObjOutput.create(AWriter: TObjectWriter);
- var
- i: TWasmSectionID;
- j: TWasmCustomSectionType;
- k: TWasmLinkingSubsectionType;
- begin
- inherited;
- cobjdata:=TWasmObjData;
- for i in TWasmSectionID do
- FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
- for j in TWasmCustomSectionType do
- FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
- for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
- FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
- FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmSymbolTableEntriesCount:=0;
- FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationCodeTableEntriesCount:=0;
- FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDataTableEntriesCount:=0;
- FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugFrameTableEntriesCount:=0;
- FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugInfoTableEntriesCount:=0;
- FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugLineTableEntriesCount:=0;
- FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugAbbrevTableEntriesCount:=0;
- FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugArangesTableEntriesCount:=0;
- FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugRangesTableEntriesCount:=0;
- FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
- FWasmRelocationDebugStrTableEntriesCount:=0;
- end;
- destructor TWasmObjOutput.destroy;
- var
- i: TWasmSectionID;
- j: TWasmCustomSectionType;
- k: TWasmLinkingSubsectionType;
- begin
- for i in TWasmSectionID do
- FWasmSections[i].Free;
- for j in TWasmCustomSectionType do
- FWasmCustomSections[j].Free;
- for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
- FWasmLinkingSubsections[k].Free;
- FWasmSymbolTable.Free;
- FWasmRelocationCodeTable.Free;
- FWasmRelocationDataTable.Free;
- FWasmRelocationDebugFrameTable.Free;
- FWasmRelocationDebugInfoTable.Free;
- FWasmRelocationDebugLineTable.Free;
- FWasmRelocationDebugAbbrevTable.Free;
- FWasmRelocationDebugArangesTable.Free;
- FWasmRelocationDebugRangesTable.Free;
- FWasmRelocationDebugStrTable.Free;
- inherited destroy;
- end;
- {****************************************************************************
- TWasmObjInput
- ****************************************************************************}
- constructor TWasmObjInput.create;
- begin
- inherited create;
- cobjdata:=TWasmObjData;
- end;
- destructor TWasmObjInput.Destroy;
- var
- i: Integer;
- begin
- for i:=low(FFuncTypes) to high(FFuncTypes) do
- begin
- FFuncTypes[i].free;
- FFuncTypes[i]:=nil;
- end;
- inherited Destroy;
- end;
- class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
- var
- ModuleMagic: array [0..3] of Byte;
- ModuleVersion: array [0..3] of Byte;
- i: Integer;
- begin
- result:=false;
- if not AReader.read(ModuleMagic,4) then
- exit;
- for i:=0 to 3 do
- if ModuleMagic[i]<>WasmModuleMagic[i] then
- exit;
- if not AReader.read(ModuleVersion,4) then
- exit;
- for i:=0 to 3 do
- if ModuleVersion[i]<>WasmVersion[i] then
- exit;
- result:=true;
- end;
- function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
- type
- TLimits = record
- Min, Max: uint32;
- HasMax: Boolean;
- end;
- var
- SectionIndex: Integer = -1;
- SectionId: Byte;
- SectionSize: uint32;
- SectionStart: LongInt;
- CheckSectionBounds: Boolean;
- TypeSectionRead: Boolean = false;
- ImportSectionRead: Boolean = false;
- FunctionSectionRead: Boolean = false;
- GlobalSectionRead: Boolean = false;
- ExportSectionRead: Boolean = false;
- ElementSectionRead: Boolean = false;
- TagSectionRead: Boolean = false;
- CodeSectionRead: Boolean = false;
- DataSectionRead: Boolean = false;
- DataCountSectionRead: Boolean = false;
- SegmentInfoSectionRead: Boolean = false;
- SymbolTableSectionRead: Boolean = false;
- CodeSectionIndex: Integer = -1;
- DataSectionIndex: Integer = -1;
- DebugSectionIndex: array [TWasmCustomDebugSectionType] of Integer = (-1,-1,-1,-1,-1,-1,-1);
- FuncTypes: array of record
- IsImport: Boolean;
- ImportName: ansistring;
- ImportModName: ansistring;
- typidx: uint32;
- IsExported: Boolean;
- ExportName: ansistring;
- end;
- FuncTypeImportsCount: uint32;
- TableTypes: array of record
- IsImport: Boolean;
- ImportName: ansistring;
- ImportModName: ansistring;
- reftype: TWasmBAsicType;
- limits: TLimits;
- IsExported: Boolean;
- ExportName: ansistring;
- end;
- TableTypeImportsCount: uint32;
- MemTypes: array of record
- IsImport: Boolean;
- ImportName: ansistring;
- ImportModName: ansistring;
- limits: TLimits;
- IsExported: Boolean;
- ExportName: ansistring;
- end;
- MemTypeImportsCount: uint32;
- GlobalTypes: array of record
- IsImport: Boolean;
- ImportName: ansistring;
- ImportModName: ansistring;
- valtype: TWasmBasicType;
- IsMutable: Boolean;
- IsExported: Boolean;
- ExportName: ansistring;
- GlobalInit: TGlobalInitializer;
- end;
- GlobalTypeImportsCount: uint32;
- TagTypes: array of record
- IsImport: Boolean;
- ImportName: ansistring;
- ImportModName: ansistring;
- TagAttr: Byte;
- TagTypeIdx: uint32;
- IsExported: Boolean;
- ExportName: ansistring;
- end;
- TagTypeImportsCount: uint32;
- CodeSegments: array of record
- CodeSectionOffset: uint32;
- CodeSize: uint32;
- DataPos: LongInt;
- SegName: ansistring;
- SegIsExported: Boolean;
- end;
- DataSegments: array of record
- DataSectionOffset: uint32;
- Active: Boolean;
- MemIdx: uint32;
- Len: uint32;
- Offset: int32;
- DataPos: LongInt;
- SegName: ansistring;
- SegAlignment: uint32;
- SegFlags: uint32;
- end;
- SymbolTable: array of record
- SymFlags: uint32;
- TargetSection: uint32;
- SymIndex: uint32;
- SymOffset: uint32;
- SymSize: uint32;
- SymKind: TWasmSymbolType;
- SymName: ansistring;
- ObjSym: TWasmObjSymbol;
- ObjSec: TWasmObjSection;
- end;
- { meaning of first index: }
- { table 0 is code relocs }
- { table 1 is data relocs }
- { tables 2.. are custom section relocs for debug sections }
- RelocationTable: array of array of record
- RelocType: TWasmRelocationType;
- RelocOffset: uint32;
- RelocIndex: uint32;
- RelocAddend: int32;
- end;
- function ReadSection: Boolean;
- function read(out b;len:longint):boolean;
- begin
- result:=false;
- if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
- result:=AReader.read(b,len)
- else
- begin
- { trying to read beyond the end of the section }
- AReader.read(b,SectionStart+SectionSize-AReader.Pos);
- result:=false;
- end;
- end;
- function ReadUleb(out v: uint64): boolean;
- var
- b: byte;
- shift:integer;
- begin
- result:=false;
- b:=0;
- v:=0;
- shift:=0;
- repeat
- if not read(b,1) then
- exit;
- v:=v or (uint64(b and 127) shl shift);
- inc(shift,7);
- until (b and 128)=0;
- result:=true;
- end;
- function ReadUleb32(out v: uint32): boolean;
- var
- vv: uint64;
- begin
- result:=false;
- v:=default(uint32);
- if not ReadUleb(vv) then
- exit;
- if vv>high(uint32) then
- exit;
- v:=vv;
- result:=true;
- end;
- function ReadSleb(out v: int64): boolean;
- var
- b: byte;
- shift:integer;
- begin
- result:=false;
- b:=0;
- v:=0;
- shift:=0;
- repeat
- if not read(b,1) then
- exit;
- v:=v or (uint64(b and 127) shl shift);
- inc(shift,7);
- until (b and 128)=0;
- {$ifopt Q+}
- {$define overflowon}
- {$Q-}
- {$endif}
- {$ifopt R+}
- {$define rangeon}
- {$R-}
- {$endif}
- if (b and 64)<>0 then
- v:=v or (high(uint64) shl shift);
- result:=true;
- end;
- {$ifdef overflowon}
- {$Q+}
- {$undef overflowon}
- {$endif}
- {$ifdef rangeon}
- {$R+}
- {$undef rangeon}
- {$endif}
- function ReadSleb32(out v: int32): boolean;
- var
- vv: int64;
- begin
- result:=false;
- v:=default(int32);
- if not ReadSleb(vv) then
- exit;
- if (vv>high(int32)) or (vv<low(int32)) then
- exit;
- v:=vv;
- result:=true;
- end;
- function ReadName(out v: ansistring): boolean;
- var
- len: uint32;
- begin
- result:=false;
- if not ReadUleb32(len) then
- exit;
- SetLength(v,len);
- if len>0 then
- result:=read(v[1],len)
- else
- result:=true;
- end;
- function ReadCustomSection: Boolean;
- function ReadRelocationSection: Boolean;
- var
- TargetSection, RelocCount: uint32;
- i: Integer;
- RelocTableIndex: Integer;
- ds: TWasmCustomDebugSectionType;
- begin
- Result:=False;
- if not ReadUleb32(TargetSection) then
- begin
- InputError('Error reading the index of the target section of a relocation section');
- exit;
- end;
- if TargetSection=CodeSectionIndex then
- RelocTableIndex:=0
- else if TargetSection=DataSectionIndex then
- RelocTableIndex:=1
- else
- begin
- RelocTableIndex:=-1;
- for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
- if DebugSectionIndex[ds]=TargetSection then
- begin
- RelocTableIndex:=2+(Ord(ds)-Ord(Low(TWasmCustomDebugSectionType)));
- break;
- end;
- if RelocTableIndex=-1 then
- begin
- InputError('Relocation found for a custom section, that is not supported');
- exit;
- end;
- end;
- if not ReadUleb32(RelocCount) then
- begin
- InputError('Error reading the relocation entries count from a relocation section');
- exit;
- end;
- SetLength(RelocationTable[RelocTableIndex],RelocCount);
- for i:=0 to RelocCount-1 do
- with RelocationTable[RelocTableIndex,i] do
- begin
- if not Read(RelocType,1) then
- begin
- InputError('Error reading the relocation type of a relocation entry');
- exit;
- end;
- if not (RelocType in [R_WASM_FUNCTION_INDEX_LEB,
- R_WASM_MEMORY_ADDR_LEB,
- R_WASM_TABLE_INDEX_SLEB,
- R_WASM_MEMORY_ADDR_SLEB,
- R_WASM_SECTION_OFFSET_I32,
- R_WASM_TABLE_INDEX_I32,
- R_WASM_FUNCTION_OFFSET_I32,
- R_WASM_MEMORY_ADDR_I32,
- R_WASM_TYPE_INDEX_LEB,
- R_WASM_GLOBAL_INDEX_LEB,
- R_WASM_TAG_INDEX_LEB]) then
- begin
- InputError('Unsupported relocation type: ' + tostr(Ord(RelocType)));
- exit;
- end;
- if not ReadUleb32(RelocOffset) then
- begin
- InputError('Error reading the relocation offset of a relocation entry');
- exit;
- end;
- if not ReadUleb32(RelocIndex) then
- begin
- InputError('Error reading the relocation index of a relocation entry');
- exit;
- end;
- 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
- begin
- if not ReadSleb32(RelocAddend) then
- begin
- InputError('Error reading the relocation addend of a relocation entry');
- exit;
- end;
- end;
- if (RelocType in [
- R_WASM_SECTION_OFFSET_I32,
- R_WASM_FUNCTION_INDEX_LEB,
- R_WASM_TABLE_INDEX_SLEB,
- R_WASM_TABLE_INDEX_I32,
- R_WASM_MEMORY_ADDR_LEB,
- R_WASM_MEMORY_ADDR_SLEB,
- R_WASM_MEMORY_ADDR_I32,
- R_WASM_FUNCTION_OFFSET_I32,
- R_WASM_GLOBAL_INDEX_LEB]) and (RelocIndex>High(SymbolTable)) then
- begin
- InputError('Relocation index outside the bounds of the symbol table');
- exit;
- end;
- if (RelocType=R_WASM_TYPE_INDEX_LEB) and (RelocIndex>High(FFuncTypes)) then
- begin
- InputError('Relocation index of R_WASM_TYPE_INDEX_LEB outside the bounds of the func types, defined in the func section of the module');
- exit;
- end;
- if (RelocType=R_WASM_SECTION_OFFSET_I32) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_SECTION) then
- begin
- InputError('R_WASM_SECTION_OFFSET_I32 must point to a SYMTAB_SECTION symbol');
- exit;
- end;
- if (RelocType=R_WASM_GLOBAL_INDEX_LEB) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_GLOBAL) then
- begin
- InputError('Relocation must point to a SYMTAB_GLOBAL symbol');
- exit;
- end;
- if (RelocType=R_WASM_TAG_INDEX_LEB) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_EVENT) then
- begin
- InputError('Relocation must point to a SYMTAB_EVENT symbol');
- exit;
- end;
- if (RelocType in [
- R_WASM_FUNCTION_INDEX_LEB,
- R_WASM_TABLE_INDEX_SLEB,
- R_WASM_TABLE_INDEX_I32,
- R_WASM_FUNCTION_OFFSET_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_FUNCTION) then
- begin
- InputError('Relocation must point to a SYMTAB_FUNCTION symbol');
- exit;
- end;
- if (RelocType in [
- R_WASM_MEMORY_ADDR_LEB,
- R_WASM_MEMORY_ADDR_SLEB,
- R_WASM_MEMORY_ADDR_I32]) and (SymbolTable[RelocIndex].SymKind<>SYMTAB_DATA) then
- begin
- InputError('Relocation must point to a SYMTAB_DATA symbol');
- exit;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected relocation section size');
- exit;
- end;
- Result:=True;
- end;
- function ReadLinkingSection: Boolean;
- function ReadSegmentInfo: Boolean;
- var
- SegmentCount: uint32;
- i: Integer;
- begin
- Result:=False;
- if SegmentInfoSectionRead then
- begin
- InputError('The WASM_SEGMENT_INFO subsection is duplicated');
- exit;
- end;
- SegmentInfoSectionRead:=True;
- if not ReadUleb32(SegmentCount) then
- begin
- InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
- exit;
- end;
- if SegmentCount<>Length(DataSegments) then
- begin
- InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
- exit;
- end;
- for i:=0 to SegmentCount-1 do
- with DataSegments[i] do
- begin
- if not ReadName(SegName) then
- begin
- InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
- exit;
- end;
- if not ReadUleb32(SegAlignment) then
- begin
- InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
- exit;
- end;
- if not ReadUleb32(SegFlags) then
- begin
- InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
- exit;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected WASM_SEGMENT_INFO section size');
- exit;
- end;
- Result:=True;
- end;
- function ReadSymbolTable: Boolean;
- var
- SymCount: uint32;
- i: Integer;
- SymKindName: string;
- SymKindB: Byte;
- begin
- Result:=False;
- if SymbolTableSectionRead then
- begin
- InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
- exit;
- end;
- SymbolTableSectionRead:=True;
- if not ReadUleb32(SymCount) then
- begin
- InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
- exit;
- end;
- SetLength(SymbolTable,SymCount);
- for i:=0 to SymCount-1 do
- with SymbolTable[i] do
- begin
- if not Read(SymKindB,1) then
- begin
- InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
- exit;
- end;
- if SymKindB>Ord(High(TWasmSymbolType)) then
- begin
- InputError('Unsupported symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
- exit;
- end;
- SymKind:=TWasmSymbolType(SymKindB);
- if not ReadUleb32(SymFlags) then
- begin
- InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
- exit;
- end;
- case SymKind of
- SYMTAB_FUNCTION,
- SYMTAB_GLOBAL,
- SYMTAB_EVENT,
- SYMTAB_TABLE:
- begin
- WriteStr(SymKindName, SymKind);
- if not ReadUleb32(SymIndex) then
- begin
- InputError('Error reading the index of a ' + SymKindName + ' symbol');
- exit;
- end;
- if ((SymKind=SYMTAB_FUNCTION) and (SymIndex>high(FuncTypes))) or
- ((SymKind=SYMTAB_EVENT) and (SymIndex>high(TagTypes))) then
- begin
- InputError('Symbol index too high');
- exit;
- end;
- if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
- ((SymFlags and WASM_SYM_UNDEFINED)=0) then
- begin
- if not ReadName(SymName) then
- begin
- InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
- exit;
- end;
- end;
- end;
- SYMTAB_DATA:
- begin
- if not ReadName(SymName) then
- begin
- InputError('Error reading symbol name of a SYMTAB_DATA symbol');
- exit;
- end;
- if (SymFlags and WASM_SYM_UNDEFINED)=0 then
- begin
- if not ReadUleb32(SymIndex) then
- begin
- InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
- exit;
- end;
- if SymIndex>high(DataSegments) then
- begin
- InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
- exit;
- end;
- if not ReadUleb32(SymOffset) then
- begin
- InputError('Error reading the offset of a SYMTAB_DATA symbol');
- exit;
- end;
- if not ReadUleb32(SymSize) then
- begin
- InputError('Error reading the size of a SYMTAB_DATA symbol');
- exit;
- end;
- end;
- end;
- SYMTAB_SECTION:
- begin
- if not ReadUleb32(TargetSection) then
- begin
- InputError('Error reading the target section of a SYMTAB_SECTION symbol');
- exit;
- end;
- end;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected WASM_SYMBOL_TABLE section size');
- exit;
- end;
- Result:=True;
- end;
- const
- ExpectedVersion = 2;
- var
- Version, SubsectionSize, SaveSectionSize: uint32;
- SubsectionType: Byte;
- SaveSectionStart: LongInt;
- begin
- Result:=False;
- if not ReadUleb32(Version) then
- begin
- InputError('Error reading the version of the ''linking'' section');
- exit;
- end;
- if Version<>ExpectedVersion then
- begin
- InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
- exit;
- end;
- while AReader.Pos<(SectionStart+SectionSize) do
- begin
- if not read(SubsectionType, 1) then
- begin
- InputError('Error reading subsection type in the ''linking'' section');
- exit;
- end;
- if not ReadUleb32(SubsectionSize) then
- begin
- InputError('Error reading subsection size in the ''linking'' section');
- exit;
- end;
- if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
- begin
- InputError('Subsection size exceeds bounds of its parent ''linking'' section');
- exit;
- end;
- SaveSectionStart:=SectionStart;
- SaveSectionSize:=SectionSize;
- SectionStart:=AReader.Pos;
- SectionSize:=SubsectionSize;
- case SubsectionType of
- Byte(WASM_SEGMENT_INFO):
- if not ReadSegmentInfo then
- begin
- InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
- exit;
- end;
- Byte(WASM_SYMBOL_TABLE):
- if not ReadSymbolTable then
- begin
- InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
- exit;
- end;
- else
- begin
- InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
- exit;
- end;
- end;
- AReader.Seek(SectionStart+SectionSize);
- SectionStart:=SaveSectionStart;
- SectionSize:=SaveSectionSize;
- end;
- result:=True;
- end;
- function ReadProducersSection: Boolean;
- begin
- Result:=False;
- end;
- function ReadTargetFeaturesSection: Boolean;
- begin
- Result:=False;
- end;
- function ReadDebugSection(const SectionName: string; SectionType: TWasmCustomDebugSectionType): Boolean;
- var
- ObjSec: TObjSection;
- begin
- Result:=False;
- if DebugSectionIndex[SectionType]<>-1 then
- begin
- InputError('Duplicated debug section: ' + SectionName);
- exit;
- end;
- DebugSectionIndex[SectionType]:=SectionIndex;
- ObjSec:=ObjData.createsection(SectionName,1,[oso_Data,oso_debug],false);
- ObjSec.DataPos:=AReader.Pos;
- ObjSec.Size:=SectionStart+SectionSize-AReader.Pos;
- Result:=True;
- end;
- const
- RelocationSectionPrefix = 'reloc.';
- var
- SectionName: ansistring;
- begin
- Result:=False;
- ReadName(SectionName);
- if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
- begin
- if not ReadRelocationSection then
- begin
- InputError('Error reading the relocation section ''' + SectionName + '''');
- exit;
- end;
- end
- else
- case SectionName of
- 'linking':
- if not ReadLinkingSection then
- begin
- InputError('Error reading the ''linking'' section');
- exit;
- end;
- 'producers':
- Result:=ReadProducersSection;
- 'target_features':
- Result:=ReadTargetFeaturesSection;
- '.debug_frame':
- if not ReadDebugSection(SectionName, wcstDebugFrame) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_info':
- if not ReadDebugSection(SectionName, wcstDebugInfo) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_line':
- if not ReadDebugSection(SectionName, wcstDebugLine) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_abbrev':
- if not ReadDebugSection(SectionName, wcstDebugAbbrev) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_aranges':
- if not ReadDebugSection(SectionName, wcstDebugAranges) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_ranges':
- if not ReadDebugSection(SectionName, wcstDebugRanges) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- '.debug_str':
- if not ReadDebugSection(SectionName, wcstDebugStr) then
- begin
- InputError('Error reading section ' + SectionName);
- exit;
- end;
- else
- InputError('Unsupported custom section: ''' + SectionName + '''');
- end;
- Result:=True;
- end;
- function ReadTypeSection: Boolean;
- var
- FuncTypesCount, ParamsCount, ResultsCount: uint32;
- FuncTypeId, WasmTypeId: Byte;
- i, j: Integer;
- wbt: TWasmBasicType;
- begin
- Result:=False;
- if TypeSectionRead then
- begin
- InputError('Type section is duplicated');
- exit;
- end;
- TypeSectionRead:=True;
- if not ReadUleb32(FuncTypesCount) then
- begin
- InputError('Error reading the func types count');
- exit;
- end;
- SetLength(FFuncTypes,FuncTypesCount);
- for i:=0 to FuncTypesCount - 1 do
- begin
- FFuncTypes[i]:=TWasmFuncType.Create([],[]);
- if not AReader.read(FuncTypeId,1) then
- begin
- InputError('Error reading the function type identifier');
- exit;
- end;
- if FuncTypeId<>$60 then
- begin
- InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
- exit;
- end;
- if not ReadUleb32(ParamsCount) then
- begin
- InputError('Error reading the function parameters count');
- exit;
- end;
- for j:=0 to ParamsCount-1 do
- begin
- if not AReader.read(WasmTypeId,1) then
- begin
- InputError('Error reading a function parameter basic type');
- exit;
- end;
- if not decode_wasm_basic_type(WasmTypeId,wbt) then
- begin
- InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
- exit;
- end;
- FFuncTypes[i].add_param(wbt);
- end;
- if not ReadUleb32(ResultsCount) then
- begin
- InputError('Error reading the function results count');
- exit;
- end;
- for j:=0 to ResultsCount-1 do
- begin
- if not AReader.read(WasmTypeId,1) then
- begin
- InputError('Error reading a function result basic type');
- exit;
- end;
- if not decode_wasm_basic_type(WasmTypeId,wbt) then
- begin
- InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
- exit;
- end;
- FFuncTypes[i].add_result(wbt);
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected type section size');
- exit;
- end;
- Result:=true;
- end;
- function ReadImportSection: Boolean;
- var
- ImportsCount: uint32;
- i: Integer;
- ModName, Name: ansistring;
- ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
- GlobalType, GlobalMutabilityType: Byte;
- begin
- Result:=False;
- if ImportSectionRead then
- begin
- InputError('Import section is duplicated');
- exit;
- end;
- ImportSectionRead:=True;
- if not ReadUleb32(ImportsCount) then
- begin
- InputError('Error reading the imports count');
- exit;
- end;
- for i:=0 to ImportsCount-1 do
- begin
- if not ReadName(ModName) then
- begin
- InputError('Error reading import module name');
- exit;
- end;
- if not ReadName(Name) then
- begin
- InputError('Error import name');
- exit;
- end;
- if not AReader.Read(ImportType,1) then
- begin
- InputError('Error reading import type');
- exit;
- end;
- case ImportType of
- $00: { func }
- begin
- Inc(FuncTypeImportsCount);
- SetLength(FuncTypes,FuncTypeImportsCount);
- with FuncTypes[FuncTypeImportsCount-1] do
- begin
- IsImport:=True;
- ImportName:=Name;
- ImportModName:=ModName;
- if not ReadUleb32(typidx) then
- begin
- InputError('Error reading type index for func import');
- exit;
- end;
- if typidx>high(FFuncTypes) then
- begin
- InputError('Type index in func import exceeds bounds of the types table');
- exit;
- end;
- end;
- end;
- $01: { table }
- begin
- Inc(TableTypeImportsCount);
- SetLength(TableTypes,TableTypeImportsCount);
- with TableTypes[TableTypeImportsCount-1] do
- begin
- IsImport:=True;
- ImportName:=Name;
- ImportModName:=ModName;
- if not AReader.read(TableElemTyp,1) then
- begin
- InputError('Error reading table element type for table import');
- exit;
- end;
- if not decode_wasm_basic_type(TableElemTyp,reftype) then
- begin
- InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
- exit;
- end;
- if not (reftype in WasmReferenceTypes) then
- begin
- InputError('Table element type for table import must be a reference type');
- exit;
- end;
- if not AReader.read(TableLimitsKind,1) then
- begin
- InputError('Error reading table limits kind for table import');
- exit;
- end;
- case TableLimitsKind of
- $00:
- begin
- limits.HasMax:=False;
- limits.Max:=high(limits.Max);
- if not ReadUleb32(limits.min) then
- begin
- InputError('Error reading table limits min for table import');
- exit;
- end;
- end;
- $01:
- begin
- limits.HasMax:=True;
- if not ReadUleb32(limits.min) then
- begin
- InputError('Error reading table limits min for table import');
- exit;
- end;
- if not ReadUleb32(limits.max) then
- begin
- InputError('Error reading table limits max for table import');
- exit;
- end;
- if limits.min>limits.max then
- begin
- InputError('Table limits min exceed table limits max in table import');
- exit;
- end;
- end;
- else
- begin
- InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
- exit;
- end;
- end;
- end;
- end;
- $02: { mem }
- begin
- Inc(MemTypeImportsCount);
- SetLength(MemTypes,MemTypeImportsCount);
- with MemTypes[MemTypeImportsCount-1] do
- begin
- IsImport:=True;
- ImportName:=Name;
- ImportModName:=ModName;
- if not AReader.read(MemoryLimitsKind,1) then
- begin
- InputError('Error reading memory limits kind for memory import');
- exit;
- end;
- case MemoryLimitsKind of
- $00:
- begin
- limits.HasMax:=False;
- limits.Max:=high(limits.Max);
- if not ReadUleb32(limits.min) then
- begin
- InputError('Error reading memory limits min for memory import');
- exit;
- end;
- end;
- $01:
- begin
- limits.HasMax:=True;
- if not ReadUleb32(limits.min) then
- begin
- InputError('Error reading memory limits min for memory import');
- exit;
- end;
- if not ReadUleb32(limits.max) then
- begin
- InputError('Error reading memory limits max for memory import');
- exit;
- end;
- if limits.Min>limits.Max then
- begin
- InputError('Memory limits min exceed memory limits max in memory import');
- exit;
- end;
- end;
- else
- begin
- InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
- exit;
- end;
- end;
- end;
- end;
- $03: { global }
- begin
- Inc(GlobalTypeImportsCount);
- SetLength(GlobalTypes,GlobalTypeImportsCount);
- with GlobalTypes[GlobalTypeImportsCount-1] do
- begin
- IsImport:=True;
- ImportName:=Name;
- ImportModName:=ModName;
- if not AReader.read(GlobalType,1) then
- begin
- InputError('Error reading global type for global import');
- exit;
- end;
- if not decode_wasm_basic_type(GlobalType,valtype) then
- begin
- InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
- exit;
- end;
- if not AReader.read(GlobalMutabilityType,1) then
- begin
- InputError('Error reading global mutability flag for global import');
- exit;
- end;
- case GlobalMutabilityType of
- $00:
- IsMutable:=False;
- $01:
- IsMutable:=True;
- else
- begin
- InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
- exit;
- end;
- end;
- end;
- end;
- $04: { tag }
- begin
- Inc(TagTypeImportsCount);
- SetLength(TagTypes,TagTypeImportsCount);
- with TagTypes[TagTypeImportsCount-1] do
- begin
- IsImport:=True;
- ImportName:=Name;
- ImportModName:=ModName;
- if not Read(TagAttr,1) then
- begin
- InputError('Error reading import tag attribute');
- exit;
- end;
- if not ReadUleb32(TagTypeIdx) then
- begin
- InputError('Error reading import tag type index');
- exit;
- end;
- if TagTypeIdx>high(FFuncTypes) then
- begin
- InputError('Type index in tag import exceeds bounds of the types table');
- exit;
- end;
- end;
- end;
- else
- begin
- InputError('Unknown import type: $' + HexStr(ImportType,2));
- exit;
- end;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected import section size');
- exit;
- end;
- Result:=true;
- end;
- function ReadFunctionSection: Boolean;
- var
- FunctionsCount: uint32;
- i: Integer;
- begin
- Result:=False;
- if FunctionSectionRead then
- begin
- InputError('Function section is duplicated');
- exit;
- end;
- FunctionSectionRead:=True;
- if not ReadUleb32(FunctionsCount) then
- begin
- InputError('Error reading the functions count');
- exit;
- end;
- SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
- for i:=0 to FunctionsCount-1 do
- with FuncTypes[i + FuncTypeImportsCount] do
- begin
- IsImport:=False;
- if not ReadUleb32(typidx) then
- begin
- InputError('Error reading type index for function');
- exit;
- end;
- if typidx>high(FFuncTypes) then
- begin
- InputError('Type index in the function section exceeds bounds of the types table');
- exit;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected function section size');
- exit;
- end;
- Result:=true;
- end;
- function ReadGlobalSection: Boolean;
- function ParseExpr(out Init: TGlobalInitializer): Boolean;
- var
- B, B2: Byte;
- tmpU32: UInt32;
- tmpU64: UInt64;
- begin
- Result:=False;
- repeat
- if not Read(B, 1) then
- exit;
- case B of
- $0B: { end }
- ;
- $41: { i32.const }
- begin
- Init.typ:=wbt_i32;
- if not ReadSleb32(Init.init_i32) then
- exit;
- end;
- $42: { i64.const }
- begin
- Init.typ:=wbt_i64;
- if not ReadSleb(Init.init_i64) then
- exit;
- end;
- $43: { f32.const }
- begin
- Init.typ:=wbt_f32;
- if not Read(tmpU32, 4) then
- exit;
- {$ifdef FPC_BIG_ENDIAN}
- tmpU32:=SwapEndian(tmpU32);
- {$endif FPC_BIG_ENDIAN}
- Move(tmpU32,Init.init_f32,4);
- end;
- $44: { f64.const }
- begin
- Init.typ:=wbt_f64;
- if not Read(tmpU64, 8) then
- exit;
- {$ifdef FPC_BIG_ENDIAN}
- tmpU64:=SwapEndian(tmpU64);
- {$endif FPC_BIG_ENDIAN}
- Move(tmpU64,Init.init_f64,8);
- end;
- $D0: { ref.null }
- begin
- if not Read(B2, 1) then
- exit;
- if not decode_wasm_basic_type(B2, Init.typ) then
- exit;
- if not (Init.typ in WasmReferenceTypes) then
- exit;
- end;
- else
- begin
- InputError('Unsupported opcode in global initializer');
- exit;
- end;
- end;
- until b = $0B;
- Result:=True;
- end;
- var
- GlobalsCount: uint32;
- i: Integer;
- vt: Byte;
- mut: Byte;
- begin
- Result:=False;
- if GlobalSectionRead then
- begin
- InputError('Global section is duplicated');
- exit;
- end;
- GlobalSectionRead:=True;
- if not ReadUleb32(GlobalsCount) then
- begin
- InputError('Error reading the globals count from the global section');
- exit;
- end;
- SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
- for i:=0 to GlobalsCount-1 do
- with GlobalTypes[i + GlobalTypeImportsCount] do
- begin
- if not read(vt,1) then
- begin
- InputError('Error reading the type of a global from the global section');
- exit;
- end;
- if not decode_wasm_basic_type(vt,valtype) then
- begin
- InputError('Unsupported type of global in the global section');
- exit;
- end;
- if not read(mut,1) then
- begin
- InputError('Error reading the mutability flag of a global in the global section');
- exit;
- end;
- case mut of
- $00:
- IsMutable:=False;
- $01:
- IsMutable:=True;
- else
- begin
- InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
- exit;
- end;
- end;
- if not ParseExpr(GlobalInit) then
- begin
- InputError('Error parsing the global initializer expression in the global section');
- exit;
- end;
- if GlobalInit.typ<>valtype then
- begin
- InputError('Initializer expression for global produces a type, which does not match the type of the global');
- exit;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected global section size');
- exit;
- end;
- Result:=True;
- end;
- function ReadExportSection: Boolean;
- var
- ExportsCount, FuncIdx, TableIdx, MemIdx, GlobalIdx, TagIdx: uint32;
- i: Integer;
- Name: ansistring;
- ExportType: Byte;
- begin
- Result:=False;
- if ExportSectionRead then
- begin
- InputError('Export section is duplicated');
- exit;
- end;
- ExportSectionRead:=True;
- if not ReadUleb32(ExportsCount) then
- begin
- InputError('Error reading the exports count from the export section');
- exit;
- end;
- for i:=0 to ExportsCount-1 do
- begin
- if not ReadName(Name) then
- begin
- InputError('Error reading an export name from the export section');
- exit;
- end;
- if not Read(ExportType,1) then
- begin
- InputError('Error reading an export type from the export section');
- exit;
- end;
- case ExportType of
- $00: { func }
- begin
- if not ReadUleb32(FuncIdx) then
- begin
- InputError('Error reading a func index from the export section');
- exit;
- end;
- if FuncIdx>high(FuncTypes) then
- begin
- InputError('Func index too high in the export section');
- exit;
- end;
- with FuncTypes[FuncIdx] do
- begin
- IsExported:=True;
- ExportName:=Name;
- end;
- end;
- $01: { table }
- begin
- if not ReadUleb32(TableIdx) then
- begin
- InputError('Error reading a table index from the export section');
- exit;
- end;
- if TableIdx>high(TableTypes) then
- begin
- InputError('Table index too high in the export section');
- exit;
- end;
- with TableTypes[TableIdx] do
- begin
- IsExported:=True;
- ExportName:=Name;
- end;
- end;
- $02: { mem }
- begin
- if not ReadUleb32(MemIdx) then
- begin
- InputError('Error reading a mem index from the export section');
- exit;
- end;
- if MemIdx>high(MemTypes) then
- begin
- InputError('Mem index too high in the export section');
- exit;
- end;
- with MemTypes[MemIdx] do
- begin
- IsExported:=True;
- ExportName:=Name;
- end;
- end;
- $03: { global }
- begin
- if not ReadUleb32(GlobalIdx) then
- begin
- InputError('Error reading a global index from the export section');
- exit;
- end;
- if GlobalIdx>high(GlobalTypes) then
- begin
- InputError('Global index too high in the export section');
- exit;
- end;
- with GlobalTypes[GlobalIdx] do
- begin
- IsExported:=True;
- ExportName:=Name;
- end;
- end;
- $04: { tag }
- begin
- if not ReadUleb32(TagIdx) then
- begin
- InputError('Error reading a tag index from the export section');
- exit;
- end;
- if TagIdx>high(TagTypes) then
- begin
- InputError('Tag index too high in the export section');
- exit;
- end;
- with TagTypes[TagIdx] do
- begin
- IsExported:=True;
- ExportName:=Name;
- end;
- end;
- else
- begin
- InputError('Unsupported export type in the export section: ' + tostr(ExportType));
- exit;
- end;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected export section size');
- exit;
- end;
- Result:=True;
- end;
- function ReadElementSection: Boolean;
- begin
- Result:=False;
- if ElementSectionRead then
- begin
- InputError('Element section is duplicated');
- exit;
- end;
- ElementSectionRead:=True;
- { We skip the element section for now }
- { TODO: implement reading it (and linking of tables) }
- Result:=True;
- end;
- function ReadTagSection: Boolean;
- var
- TagCount: uint32;
- i: Integer;
- begin
- Result:=False;
- if TagSectionRead then
- begin
- InputError('Tag section is duplicated');
- exit;
- end;
- TagSectionRead:=True;
- if not ReadUleb32(TagCount) then
- begin
- InputError('Error reading the tag count from the tag section');
- exit;
- end;
- SetLength(TagTypes,Length(TagTypes)+TagCount);
- for i:=0 to TagCount-1 do
- with TagTypes[i + TagTypeImportsCount] do
- begin
- if not Read(TagAttr,1) then
- begin
- InputError('Error reading tag attribute');
- exit;
- end;
- if not ReadUleb32(TagTypeIdx) then
- begin
- InputError('Error reading tag type index');
- exit;
- end;
- if TagTypeIdx>high(FFuncTypes) then
- begin
- InputError('Type index in tag import exceeds bounds of the types table');
- exit;
- end;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected tag section size');
- exit;
- end;
- Result:=True;
- end;
- function ReadCodeSection: Boolean;
- var
- CodeEntriesCount: uint32;
- i: Integer;
- begin
- Result:=False;
- if CodeSectionRead then
- begin
- InputError('Code section is duplicated');
- exit;
- end;
- CodeSectionRead:=True;
- CodeSectionIndex:=SectionIndex;
- if not ReadUleb32(CodeEntriesCount) then
- begin
- InputError('Error reading the code entries cound from the code section');
- exit;
- end;
- if CodeEntriesCount <> (Length(FuncTypes) - FuncTypeImportsCount) then
- begin
- InputError('Code segment count in the code section does not match the function definition count in the function section');
- exit;
- end;
- SetLength(CodeSegments,CodeEntriesCount);
- for i:=0 to CodeEntriesCount-1 do
- with CodeSegments[i] do
- begin
- if not ReadUleb32(CodeSize) then
- begin
- InputError('Error reading the code size of an entry in the code section');
- exit;
- end;
- if (AReader.Pos+CodeSize)>(SectionStart+SectionSize) then
- begin
- InputError('Code segment exceeds the bounds of the code section');
- exit;
- end;
- DataPos:=AReader.Pos;
- CodeSectionOffset:=AReader.Pos-SectionStart;
- AReader.Seek(AReader.Pos+CodeSize);
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected code section size');
- exit;
- end;
- Result:=true;
- end;
- function ReadDataSection: Boolean;
- function ReadExpr(out ExprV: int32): Boolean;
- var
- b: Byte;
- begin
- Result:=False;
- if not Read(b,1) then
- exit;
- if b<>$41 then
- begin
- InputError('Only i32.const expressions supported');
- exit;
- end;
- if not ReadSleb32(ExprV) then
- exit;
- if not Read(b,1) then
- exit;
- if b<>$0B then
- begin
- InputError('Only single const expressions supported');
- exit;
- end;
- Result:=True;
- end;
- var
- DataCount: uint32;
- DataType: Byte;
- i: Integer;
- begin
- Result:=False;
- if DataSectionRead then
- begin
- InputError('Data section is duplicated');
- exit;
- end;
- DataSectionRead:=True;
- DataSectionIndex:=SectionIndex;
- if not ReadUleb32(DataCount) then
- begin
- InputError('Error reading the data entries count from the data section');
- exit;
- end;
- if DataCountSectionRead then
- begin
- if Length(DataSegments)<>DataCount then
- begin
- InputError('Data entries count in the data section do not match the number, specified in the data count section');
- exit;
- end;
- end
- else
- SetLength(DataSegments,DataCount);
- for i:=0 to DataCount-1 do
- with DataSegments[i] do
- begin
- if not read(DataType, 1) then
- begin
- InputError('Error reading data type of segment from the data section');
- exit;
- end;
- case DataType of
- 0:
- begin
- Active:=True;
- MemIdx:=0;
- if not ReadExpr(Offset) then
- begin
- InputError('Error reading memory offset of segment from the data section');
- exit;
- end;
- end;
- 1:
- Active:=False;
- 2:
- begin
- Active:=True;
- if not ReadUleb32(MemIdx) then
- begin
- InputError('Error reading MemIdx of segment from the data section');
- exit;
- end;
- if not ReadExpr(Offset) then
- begin
- InputError('Error reading memory offset of segment from the data section');
- exit;
- end;
- end;
- else
- begin
- InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
- exit;
- end;
- end;
- if MemIdx<>0 then
- begin
- InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
- exit;
- end;
- if not Active then
- begin
- InputError('Passive memory segments not supported');
- exit;
- end;
- if not ReadUleb32(Len) then
- begin
- InputError('Error reading data segment length');
- exit;
- end;
- if (AReader.Pos+Len)>(SectionStart+SectionSize) then
- begin
- InputError('Data segment exceeds the bounds of the data section');
- exit;
- end;
- DataPos:=AReader.Pos;
- DataSectionOffset:=AReader.Pos-SectionStart;
- AReader.Seek(AReader.Pos+Len);
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected data section size');
- exit;
- end;
- Result:=true;
- end;
- function ReadDataCountSection: Boolean;
- var
- DataCount: uint32;
- begin
- Result:=False;
- if DataCountSectionRead then
- begin
- InputError('Data count section is duplicated');
- exit;
- end;
- DataCountSectionRead:=True;
- if DataSectionRead then
- begin
- InputError('The data count section must occur before the data section');
- exit;
- end;
- if not ReadUleb32(DataCount) then
- begin
- InputError('Error reading the data count from the data count section');
- exit;
- end;
- if AReader.Pos<>(SectionStart+SectionSize) then
- begin
- InputError('Unexpected data count section size');
- exit;
- end;
- SetLength(DataSegments, DataCount);
- Result:=true;
- end;
- begin
- Result:=False;
- Inc(SectionIndex);
- if not AReader.read(SectionId,1) then
- begin
- InputError('Error reading section ID');
- exit;
- end;
- CheckSectionBounds:=false;
- if not ReadUleb32(SectionSize) then
- begin
- InputError('Error reading section size');
- exit;
- end;
- if (AReader.Pos+SectionSize)>AReader.size then
- begin
- InputError('Section exceeds beyond the end of file');
- exit;
- end;
- SectionStart:=AReader.Pos;
- CheckSectionBounds:=true;
- case SectionId of
- Byte(wsiCustom):
- if not ReadCustomSection then
- begin
- InputError('Error encountered, while reading a custom section');
- exit;
- end;
- Byte(wsiType):
- if not ReadTypeSection then
- begin
- InputError('Error reading the type section');
- exit;
- end;
- Byte(wsiImport):
- if not ReadImportSection then
- begin
- InputError('Error reading the import section');
- exit;
- end;
- Byte(wsiFunction):
- if not ReadFunctionSection then
- begin
- InputError('Error reading the function section');
- exit;
- end;
- Byte(wsiGlobal):
- if not ReadGlobalSection then
- begin
- InputError('Error reading the global section');
- exit;
- end;
- Byte(wsiExport):
- if not ReadExportSection then
- begin
- InputError('Error reading the export section');
- exit;
- end;
- Byte(wsiElement):
- if not ReadElementSection then
- begin
- InputError('Error reading the element section');
- exit;
- end;
- Byte(wsiTag):
- if not ReadTagSection then
- begin
- InputError('Error reading the tag section');
- exit;
- end;
- Byte(wsiCode):
- if not ReadCodeSection then
- begin
- InputError('Error reading the code section');
- exit;
- end;
- Byte(wsiData):
- if not ReadDataSection then
- begin
- InputError('Error reading the data section');
- exit;
- end;
- Byte(wsiDataCount):
- begin
- if not ReadDataCountSection then
- begin
- InputError('Error reading the data count section');
- exit;
- end;
- end
- else
- begin
- InputError('Unknown section: ' + ToStr(SectionId));
- exit;
- end;
- end;
- if SectionSize>0 then
- AReader.seek(SectionStart+SectionSize);
- Result:=True;
- end;
- function FindCodeSegment(Ofs: uint32): Integer;
- var
- L, R, M: Integer;
- begin
- L:=Low(CodeSegments);
- R:=High(CodeSegments);
- while L<=R do
- begin
- M:=(L+R) div 2;
- if (CodeSegments[M].CodeSectionOffset+CodeSegments[M].CodeSize-1) < Ofs then
- L:=M+1
- else if CodeSegments[M].CodeSectionOffset > Ofs then
- R:=M-1
- else
- begin
- Result:=M;
- exit;
- end;
- end;
- Result:=-1;
- end;
- function FindDataSegment(Ofs: uint32): Integer;
- var
- L, R, M: Integer;
- begin
- L:=Low(DataSegments);
- R:=High(DataSegments);
- while L<=R do
- begin
- M:=(L+R) div 2;
- if (DataSegments[M].DataSectionOffset+DataSegments[M].Len-1) < Ofs then
- L:=M+1
- else if DataSegments[M].DataSectionOffset > Ofs then
- R:=M-1
- else
- begin
- Result:=M;
- exit;
- end;
- end;
- Result:=-1;
- end;
- var
- ModuleMagic: array [0..3] of Byte;
- ModuleVersion: array [0..3] of Byte;
- i, j, FirstCodeSegmentIdx, FirstDataSegmentIdx, SegI: Integer;
- CurrSec, ObjSec: TObjSection;
- BaseSectionOffset: UInt32;
- ObjReloc: TWasmObjRelocation;
- ds: TWasmCustomDebugSectionType;
- begin
- FReader:=AReader;
- InputFileName:=AReader.FileName;
- objdata:=CObjData.Create(InputFileName);
- result:=false;
- CodeSegments:=nil;
- DataSegments:=nil;
- SymbolTable:=nil;
- RelocationTable:=nil;
- SetLength(RelocationTable,2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))+1));
- FuncTypes:=nil;
- FuncTypeImportsCount:=0;
- TableTypes:=nil;
- TableTypeImportsCount:=0;
- MemTypes:=nil;
- MemTypeImportsCount:=0;
- GlobalTypes:=nil;
- GlobalTypeImportsCount:=0;
- TagTypes:=nil;
- TagTypeImportsCount:=0;
- if not AReader.read(ModuleMagic,4) then
- exit;
- for i:=0 to 3 do
- if ModuleMagic[i]<>WasmModuleMagic[i] then
- exit;
- if not AReader.read(ModuleVersion,4) then
- exit;
- for i:=0 to 3 do
- if ModuleVersion[i]<>WasmVersion[i] then
- exit;
- while AReader.Pos<AReader.size do
- if not ReadSection then
- exit;
- { fill the code segment names }
- for i:=low(SymbolTable) to high(SymbolTable) do
- with SymbolTable[i] do
- if (SymKind=SYMTAB_FUNCTION) and ((SymFlags and WASM_SYM_UNDEFINED)=0) then
- begin
- if FuncTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
- exit;
- end;
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
- begin
- with CodeSegments[SymIndex-FuncTypeImportsCount] do
- begin
- SegName:='.text.n_'+SymName;
- SegIsExported:=FuncTypes[SymIndex].IsExported;
- end;
- end;
- end;
- { create segments }
- FirstCodeSegmentIdx:=ObjData.ObjSectionList.Count;
- for i:=low(CodeSegments) to high(CodeSegments) do
- with CodeSegments[i] do
- begin
- if SegName='' then
- begin
- InputError('Code section ' + tostr(i) + ' does not have a main symbol defined in the symbol table');
- exit;
- end;
- if SegIsExported then
- CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load,oso_keep],false)
- else
- CurrSec:=ObjData.createsection(SegName,1,[oso_executable,oso_Data,oso_load],false);
- CurrSec.DataPos:=DataPos;
- CurrSec.Size:=CodeSize;
- end;
- FirstDataSegmentIdx:=ObjData.ObjSectionList.Count;
- for i:=low(DataSegments) to high(DataSegments) do
- with DataSegments[i] do
- if Active then
- begin
- CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
- CurrSec.DataPos:=DataPos;
- CurrSec.MemPos:=Offset;
- CurrSec.Size:=Len;
- end;
- ReadSectionContent(ObjData);
- for i:=low(SymbolTable) to high(SymbolTable) do
- with SymbolTable[i] do
- case SymKind of
- SYMTAB_DATA:
- if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_DATA;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=0;
- end
- else
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
- objsym.bind:=AB_LOCAL
- else
- objsym.bind:=AB_GLOBAL;
- objsym.typ:=AT_DATA;
- objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SymIndex]);
- objsym.offset:=SymOffset;
- objsym.size:=SymSize;
- end;
- SYMTAB_FUNCTION:
- begin
- if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
- begin
- if not FuncTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
- exit;
- end;
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_FUNCTION;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=0;
- objsym.LinkingData.ImportModule:=FuncTypes[SymIndex].ImportModName;
- objsym.LinkingData.ImportName:=FuncTypes[SymIndex].ImportName;
- end
- else
- begin
- if FuncTypes[SymIndex].ImportModName = 'env' then
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportName))
- else
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_FUNCTION;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=0;
- end;
- end
- else
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_GLOBAL;
- objsym.typ:=AT_FUNCTION;
- objsym.objsection:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]);
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
- TWasmObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SymIndex-FuncTypeImportsCount]).MainFuncSymbol:=objsym;
- objsym.offset:=0;
- objsym.size:=objsym.objsection.Size;
- end;
- objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[FuncTypes[SymIndex].typidx]);
- objsym.LinkingData.IsExported:=FuncTypes[SymIndex].IsExported;
- objsym.LinkingData.ExportName:=FuncTypes[SymIndex].ExportName;
- end;
- SYMTAB_GLOBAL:
- begin
- if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
- begin
- if not GlobalTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED set on a SYMTAB_GLOBAL symbol, that is not an import');
- exit;
- end;
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_WASM_GLOBAL;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=1;
- objsym.LinkingData.ImportModule:=GlobalTypes[SymIndex].ImportModName;
- objsym.LinkingData.ImportName:=GlobalTypes[SymIndex].ImportName;
- end
- else
- begin
- if GlobalTypes[SymIndex].ImportModName = 'env' then
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
- else
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_WASM_GLOBAL;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=1;
- end;
- end
- else
- begin
- if GlobalTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_GLOBAL symbol, that is an import');
- exit;
- end;
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_GLOBAL;
- objsym.typ:=AT_WASM_GLOBAL;
- objsym.objsection:=ObjData.createsection('.wasm_globals.n_'+SymName,1,[oso_Data,oso_load],true);
- if objsym.objsection.Size=0 then
- objsym.objsection.WriteZeros(1);
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
- TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
- objsym.offset:=0;
- objsym.size:=1;
- objsym.LinkingData.GlobalInitializer:=GlobalTypes[SymIndex].GlobalInit;
- end;
- objsym.LinkingData.GlobalType:=GlobalTypes[SymIndex].valtype;
- objsym.LinkingData.GlobalIsMutable:=GlobalTypes[SymIndex].IsMutable;
- objsym.LinkingData.IsExported:=GlobalTypes[SymIndex].IsExported;
- objsym.LinkingData.ExportName:=GlobalTypes[SymIndex].ExportName;
- end;
- SYMTAB_SECTION:
- begin
- for ds:=Low(DebugSectionIndex) to High(DebugSectionIndex) do
- if DebugSectionIndex[ds]=TargetSection then
- begin
- ObjSec:=TWasmObjSection(ObjData.findsection(WasmCustomSectionName[ds]));
- break;
- end;
- if ObjSec=nil then
- begin
- InputError('SYMTAB_SECTION entry points to an unsupported section');
- exit;
- end;
- end;
- SYMTAB_EVENT:
- begin
- if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
- begin
- if not TagTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED set on a SYMTAB_EVENT symbol, that is not an import');
- exit;
- end;
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
- begin
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_WASM_EXCEPTION_TAG;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=1;
- objsym.LinkingData.ImportModule:=TagTypes[SymIndex].ImportModName;
- objsym.LinkingData.ImportName:=TagTypes[SymIndex].ImportName;
- end
- else
- begin
- if GlobalTypes[SymIndex].ImportModName = 'env' then
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportName))
- else
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(GlobalTypes[SymIndex].ImportModName + '.' + GlobalTypes[SymIndex].ImportName));
- objsym.bind:=AB_EXTERNAL;
- objsym.typ:=AT_WASM_EXCEPTION_TAG;
- objsym.objsection:=nil;
- objsym.offset:=0;
- objsym.size:=1;
- end;
- end
- else
- begin
- if TagTypes[SymIndex].IsImport then
- begin
- InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_EVENT symbol, that is an import');
- exit;
- end;
- objsym:=TWasmObjSymbol(ObjData.CreateSymbol(SymName));
- if (symflags and WASM_SYM_BINDING_WEAK) <> 0 then
- objsym.bind:=AB_WEAK_EXTERNAL
- else if (symflags and WASM_SYM_BINDING_LOCAL) <> 0 then
- objsym.bind:=AB_LOCAL
- else
- objsym.bind:=AB_GLOBAL;
- objsym.typ:=AT_WASM_EXCEPTION_TAG;
- objsym.objsection:=ObjData.createsection('.wasm_tags.n_'+SymName,1,[oso_Data,oso_load],true);
- if objsym.objsection.Size=0 then
- objsym.objsection.WriteZeros(1);
- if (SymFlags and WASM_SYM_EXPLICIT_NAME)=0 then
- TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
- objsym.offset:=0;
- objsym.size:=1;
- end;
- objsym.LinkingData.FuncType:=TWasmFuncType.Create(FFuncTypes[TagTypes[SymIndex].TagTypeIdx]);
- objsym.LinkingData.IsExported:=TagTypes[SymIndex].IsExported;
- objsym.LinkingData.ExportName:=TagTypes[SymIndex].ExportName;
- end;
- SYMTAB_TABLE:
- {TODO};
- end;
- for j:=0 to high(RelocationTable) do
- for i:=0 to high(RelocationTable[j]) do
- with RelocationTable[j,i] do
- begin
- case j of
- 0:
- begin
- SegI:=FindCodeSegment(RelocOffset);
- if SegI=-1 then
- begin
- InputError('Relocation offset not found in code segment');
- Exit;
- end;
- BaseSectionOffset:=CodeSegments[SegI].CodeSectionOffset;
- ObjSec:=TObjSection(ObjData.ObjSectionList[FirstCodeSegmentIdx+SegI]);
- end;
- 1:
- begin
- SegI:=FindDataSegment(RelocOffset);
- if SegI=-1 then
- begin
- InputError('Relocation offset not found in data segment');
- Exit;
- end;
- BaseSectionOffset:=DataSegments[SegI].DataSectionOffset;
- ObjSec:=TObjSection(ObjData.ObjSectionList[FirstDataSegmentIdx+SegI]);
- end;
- 2..2+(Ord(High(TWasmCustomDebugSectionType))-Ord(Low(TWasmCustomDebugSectionType))):
- begin
- BaseSectionOffset:=0;
- ObjSec:=ObjData.findsection(WasmCustomSectionName[TWasmCustomSectionType((j-2)+Ord(Low(TWasmCustomDebugSectionType)))]);
- end;
- else
- internalerror(2023122801);
- end;
- case RelocType of
- R_WASM_FUNCTION_INDEX_LEB:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_FUNCTION_INDEX_LEB));
- R_WASM_TABLE_INDEX_SLEB:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB));
- R_WASM_TABLE_INDEX_I32:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE));
- R_WASM_MEMORY_ADDR_LEB:
- begin
- ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_LEB);
- ObjReloc.Addend:=RelocAddend;
- ObjSec.ObjRelocations.Add(ObjReloc);
- end;
- R_WASM_MEMORY_ADDR_SLEB:
- begin
- ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB);
- ObjReloc.Addend:=RelocAddend;
- ObjSec.ObjRelocations.Add(ObjReloc);
- end;
- R_WASM_MEMORY_ADDR_I32:
- begin
- ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
- ObjReloc.Addend:=RelocAddend;
- ObjSec.ObjRelocations.Add(ObjReloc);
- end;
- R_WASM_TYPE_INDEX_LEB:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateFuncType(RelocOffset-BaseSectionOffset,FFuncTypes[RelocIndex]));
- R_WASM_FUNCTION_OFFSET_I32:
- begin
- ObjReloc:=TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_ABSOLUTE);
- ObjReloc.Addend:=RelocAddend;
- ObjReloc.IsFunctionOffsetI32:=True;
- ObjSec.ObjRelocations.Add(ObjReloc);
- end;
- R_WASM_SECTION_OFFSET_I32:
- begin
- ObjReloc:=TWasmObjRelocation.CreateSection(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSec,RELOC_ABSOLUTE);
- ObjReloc.Addend:=RelocAddend;
- ObjSec.ObjRelocations.Add(ObjReloc);
- end;
- R_WASM_GLOBAL_INDEX_LEB:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_GLOBAL_INDEX_LEB));
- R_WASM_TAG_INDEX_LEB:
- ObjSec.ObjRelocations.Add(TWasmObjRelocation.CreateSymbol(RelocOffset-BaseSectionOffset,SymbolTable[RelocIndex].ObjSym,RELOC_TAG_INDEX_LEB));
- else
- internalerror(2023122802);
- end;
- end;
- Result:=True;
- end;
- {****************************************************************************
- TWasmExeOutput
- ****************************************************************************}
- procedure TWasmExeOutput.WriteWasmSection(wsid: TWasmSectionID);
- var
- b: byte;
- begin
- b:=ord(wsid);
- Writer.write(b,1);
- WriteUleb(Writer,FWasmSections[wsid].size);
- Writer.writearray(FWasmSections[wsid]);
- end;
- procedure TWasmExeOutput.WriteWasmSectionIfNotEmpty(wsid: TWasmSectionID);
- begin
- if FWasmSections[wsid].size>0 then
- WriteWasmSection(wsid);
- end;
- procedure TWasmExeOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
- var
- b: byte;
- begin
- b:=0;
- Writer.write(b,1);
- WriteUleb(Writer,FWasmCustomSections[wcst].size);
- Writer.writearray(FWasmCustomSections[wcst]);
- end;
- function TWasmExeOutput.writeData: boolean;
- procedure WriteImportSection;
- var
- imports_count: SizeInt;
- i: Integer;
- begin
- imports_count:=Length(FFunctionImports);
- WriteUleb(FWasmSections[wsiImport],imports_count);
- for i:=0 to Length(FFunctionImports)-1 do
- with FFunctionImports[i] do
- begin
- WriteName(FWasmSections[wsiImport],ModName);
- WriteName(FWasmSections[wsiImport],Name);
- WriteByte(FWasmSections[wsiImport],$00);
- WriteUleb(FWasmSections[wsiImport],TypeIdx);
- end;
- end;
- procedure WriteCodeSegments;
- var
- i: Integer;
- exesec: TExeSection;
- objsec: TWasmObjSection;
- begin
- exesec:=FindExeSection('.text');
- if not assigned(exesec) then
- internalerror(2023123102);
- if not (oso_Data in exesec.SecOptions) then
- internalerror(2023123103);
- WriteUleb(FWasmSections[wsiFunction],exesec.ObjSectionList.Count);
- WriteUleb(FWasmSections[wsiCode],exesec.ObjSectionList.Count);
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
- if not (oso_data in objsec.secoptions) then
- internalerror(2023123104);
- if not assigned(objsec.data) then
- internalerror(2023123105);
- if objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex<>(i+Length(FFunctionImports)) then
- internalerror(2024010101);
- WriteUleb(FWasmSections[wsiFunction],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
- WriteUleb(FWasmSections[wsiCode],objsec.Data.size);
- objsec.Data.seek(0);
- CopyDynamicArray(objsec.Data,FWasmSections[wsiCode],objsec.Data.size);
- end;
- end;
- procedure WriteDataSegments;
- procedure WriteExeSection(exesec: TExeSection);
- var
- i: Integer;
- objsec: TObjSection;
- exesecdatapos: LongWord;
- dpos, pad: QWord;
- begin
- WriteByte(FWasmSections[wsiData],0);
- WriteByte(FWasmSections[wsiData],$41); { i32.const }
- WriteSleb(FWasmSections[wsiData],longint(exesec.MemPos));
- WriteByte(FWasmSections[wsiData],$0B); { end }
- WriteUleb(FWasmSections[wsiData],exesec.Size);
- exesecdatapos:=FWasmSections[wsiData].size;
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TObjSection(exesec.ObjSectionList[i]);
- if not (oso_data in objsec.secoptions) then
- internalerror(2024010104);
- if not assigned(objsec.data) then
- internalerror(2024010105);
- dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
- pad:=dpos-FWasmSections[wsiData].size;
- { objsection must be within SecAlign bytes from the previous one }
- if (dpos<FWasmSections[wsiData].Size) or
- (pad>=max(objsec.SecAlign,1)) then
- internalerror(2024010106);
- writeZeros(FWasmSections[wsiData],pad);
- objsec.data.seek(0);
- CopyDynamicArray(objsec.data,FWasmSections[wsiData],objsec.data.size);
- end;
- if (FWasmSections[wsiData].size-exesecdatapos)<>exesec.Size then
- internalerror(2024010107);
- end;
- var
- DataCount: Integer;
- begin
- DataCount:=2;
- WriteUleb(FWasmSections[wsiDataCount],DataCount);
- WriteUleb(FWasmSections[wsiData],DataCount);
- WriteExeSection(FindExeSection('.rodata'));
- WriteExeSection(FindExeSection('.data'));
- end;
- procedure WriteTableAndElemSections;
- const
- TableCount=1;
- var
- i: Integer;
- begin
- { Table section }
- WriteUleb(FWasmSections[wsiTable],TableCount);
- { table 0 }
- { table type }
- WriteByte(FWasmSections[wsiTable],encode_wasm_basic_type(wbt_funcref));
- { table limits }
- WriteByte(FWasmSections[wsiTable],$01); { has min & max }
- WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { min }
- WriteUleb(FWasmSections[wsiTable],Length(FIndirectFunctionTable)); { max }
- { Elem section }
- WriteUleb(FWasmSections[wsiElement],1); { 1 element segment }
- { element segment 0 }
- WriteByte(FWasmSections[wsiElement],0); { type funcref, init((ref.func y) end)*, mode active <table 0, offset e> }
- { e:expr }
- WriteByte(FWasmSections[wsiElement],$41); { i32.const }
- WriteSleb(FWasmSections[wsiElement],1); { starting from 1 (table entry 0 is ref.null) }
- WriteByte(FWasmSections[wsiElement],$0B); { end }
- { y*:vec(funcidx) }
- WriteUleb(FWasmSections[wsiElement],Length(FIndirectFunctionTable)-1);
- for i:=1 to Length(FIndirectFunctionTable)-1 do
- WriteUleb(FWasmSections[wsiElement],FIndirectFunctionTable[i].FuncIdx);
- end;
- procedure WriteGlobalSection;
- var
- exesec: TExeSection;
- globals_count, i: Integer;
- objsec: TWasmObjSection;
- begin
- exesec:=FindExeSection('.wasm_globals');
- if not assigned(exesec) then
- internalerror(2024010112);
- globals_count:=exesec.ObjSectionList.Count;
- if globals_count<>exesec.Size then
- internalerror(2024010113);
- WriteUleb(FWasmSections[wsiGlobal],globals_count);
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
- WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(objsec.MainFuncSymbol.LinkingData.GlobalType));
- if objsec.MainFuncSymbol.LinkingData.GlobalIsMutable then
- WriteByte(FWasmSections[wsiGlobal],1)
- else
- WriteByte(FWasmSections[wsiGlobal],0);
- { initializer expr }
- with objsec.MainFuncSymbol.LinkingData.GlobalInitializer do
- case typ of
- wbt_i32:
- begin
- WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
- WriteSleb(FWasmSections[wsiGlobal],init_i32);
- end;
- wbt_i64:
- begin
- WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
- WriteSleb(FWasmSections[wsiGlobal],init_i64);
- end;
- wbt_f32:
- begin
- WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
- WriteF32LE(FWasmSections[wsiGlobal],init_f32);
- end;
- wbt_f64:
- begin
- WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
- WriteF64LE(FWasmSections[wsiGlobal],init_f64);
- end;
- wbt_funcref,
- wbt_externref:
- begin
- WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null }
- WriteByte(FWasmSections[wsiGlobal],encode_wasm_basic_type(typ));
- end;
- else
- internalerror(2024010114);
- end;
- WriteByte(FWasmSections[wsiGlobal],$0B); { end }
- end;
- end;
- procedure WriteTagSection;
- var
- exesec: TExeSection;
- tags_count, i: Integer;
- objsec: TWasmObjSection;
- begin
- exesec:=FindExeSection('.wasm_tags');
- if not assigned(exesec) then
- exit;
- tags_count:=exesec.ObjSectionList.Count;
- if tags_count<>exesec.Size then
- internalerror(2024010702);
- if tags_count=0 then
- exit;
- WriteUleb(FWasmSections[wsiTag],tags_count);
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
- WriteByte(FWasmSections[wsiTag],0);
- WriteUleb(FWasmSections[wsiTag],objsec.MainFuncSymbol.LinkingData.ExeTypeIndex);
- end;
- end;
- procedure WriteExportSection;
- const
- MemoryExportsCount=1;
- var
- FunctionExportsCount: Integer;
- ExportsCount: Integer;
- textsec: TExeSection;
- i: Integer;
- objsec: TWasmObjSection;
- begin
- FunctionExportsCount:=0;
- textsec:=FindExeSection('.text');
- if not assigned(textsec) then
- internalerror(2024010115);
- for i:=0 to textsec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
- if objsec.MainFuncSymbol.LinkingData.IsExported then
- Inc(FunctionExportsCount)
- end;
- ExportsCount:=MemoryExportsCount+FunctionExportsCount;
- WriteUleb(FWasmSections[wsiExport],ExportsCount);
- { export 0 }
- WriteName(FWasmSections[wsiExport],'memory');
- WriteByte(FWasmSections[wsiExport],$02); { mem }
- WriteUleb(FWasmSections[wsiExport],0); { memidx = 0 }
- for i:=0 to textsec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(textsec.ObjSectionList[i]);
- if objsec.MainFuncSymbol.LinkingData.IsExported then
- begin
- WriteName(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExportName);
- WriteByte(FWasmSections[wsiExport],$00); { func }
- WriteUleb(FWasmSections[wsiExport],objsec.MainFuncSymbol.LinkingData.ExeFunctionIndex); { funcidx }
- end;
- end;
- end;
- procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
- var
- exesec: TExeSection;
- begin
- exesec:=FindExeSection(WasmCustomSectionName[st]);
- if assigned(exesec) then
- begin
- WriteExeSectionToDynArray(exesec,FWasmCustomSections[st]);
- WriteWasmCustomSection(st);
- end;
- end;
- var
- cust_sec: TWasmCustomSectionType;
- begin
- result:=false;
- { each custom sections starts with its name }
- for cust_sec in TWasmCustomSectionType do
- WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
- SetStackPointer;
- FFuncTypes.WriteTo(FWasmSections[wsiType]);
- WriteImportSection;
- WriteCodeSegments;
- WriteDataSegments;
- WriteTableAndElemSections;
- WriteGlobalSection;
- WriteTagSection;
- WriteExportSection;
- WriteUleb(FWasmSections[wsiMemory],1);
- WriteByte(FWasmSections[wsiMemory],0);
- WriteUleb(FWasmSections[wsiMemory],FMinMemoryPages);
- {...}
- Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
- Writer.write(WasmVersion,SizeOf(WasmVersion));
- WriteWasmSection(wsiType);
- WriteWasmSection(wsiImport);
- WriteWasmSection(wsiFunction);
- WriteWasmSection(wsiTable);
- WriteWasmSection(wsiMemory);
- WriteWasmSectionIfNotEmpty(wsiTag);
- WriteWasmSection(wsiGlobal);
- WriteWasmSection(wsiExport);
- WriteWasmSection(wsiElement);
- WriteWasmSection(wsiDataCount);
- WriteWasmSection(wsiCode);
- WriteWasmSection(wsiData);
- MaybeWriteDebugSection(wcstDebugAbbrev);
- MaybeWriteDebugSection(wcstDebugInfo);
- MaybeWriteDebugSection(wcstDebugStr);
- MaybeWriteDebugSection(wcstDebugLine);
- MaybeWriteDebugSection(wcstDebugFrame);
- MaybeWriteDebugSection(wcstDebugAranges);
- MaybeWriteDebugSection(wcstDebugRanges);
- result := true;
- end;
- procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
- procedure writeUInt32LE(v: uint32);
- begin
- {$ifdef FPC_BIG_ENDIAN}
- v:=SwapEndian(v);
- {$endif FPC_BIG_ENDIAN}
- objsec.data.write(v,4);
- end;
- var
- i: Integer;
- objreloc: TWasmObjRelocation;
- objsym: TWasmObjSymbol;
- begin
- for i:=0 to objsec.ObjRelocations.Count-1 do
- begin
- objreloc:=TWasmObjRelocation(objsec.ObjRelocations[i]);
- if assigned(objreloc.symbol) then
- begin
- objsym:=TWasmObjSymbol(objreloc.symbol);
- case objreloc.typ of
- RELOC_FUNCTION_INDEX_LEB:
- begin
- if objsym.LinkingData.ExeFunctionIndex=-1 then
- internalerror(2024010103);
- objsec.Data.seek(objreloc.DataOffset);
- WriteUleb5(objsec.Data,objsym.LinkingData.ExeFunctionIndex);
- end;
- RELOC_ABSOLUTE:
- begin
- case objsym.typ of
- AT_FUNCTION:
- begin
- if objreloc.IsFunctionOffsetI32 then
- begin
- { R_WASM_FUNCTION_OFFSET_I32 }
- objsec.Data.seek(objreloc.DataOffset);
- writeUInt32LE(UInt32(objsym.objsection.MemPos+objreloc.Addend));
- end
- else
- begin
- { R_WASM_TABLE_INDEX_I32 }
- if objsym.LinkingData.ExeFunctionIndex=-1 then
- internalerror(2024010103);
- if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
- objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
- objsec.Data.seek(objreloc.DataOffset);
- writeUInt32LE(UInt32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
- end;
- end;
- AT_DATA:
- begin
- if objreloc.IsFunctionOffsetI32 then
- internalerror(2024010602);
- objsec.Data.seek(objreloc.DataOffset);
- writeUInt32LE(UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
- end;
- else
- internalerror(2024010108);
- end;
- end;
- RELOC_MEMORY_ADDR_LEB:
- begin
- if objsym.typ<>AT_DATA then
- internalerror(2024010109);
- objsec.Data.seek(objreloc.DataOffset);
- WriteUleb5(objsec.Data,UInt32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
- end;
- RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
- begin
- case objsym.typ of
- AT_FUNCTION:
- begin
- if objsym.LinkingData.ExeFunctionIndex=-1 then
- internalerror(2024010103);
- if objsym.LinkingData.ExeIndirectFunctionTableIndex=-1 then
- objsym.LinkingData.ExeIndirectFunctionTableIndex:=AddOrGetIndirectFunctionTableIndex(objsym.LinkingData.ExeFunctionIndex);
- objsec.Data.seek(objreloc.DataOffset);
- WriteSleb5(objsec.Data,Int32(objsym.LinkingData.ExeIndirectFunctionTableIndex));
- end;
- AT_DATA:
- begin
- objsec.Data.seek(objreloc.DataOffset);
- WriteSleb5(objsec.Data,Int32((objsym.offset+objsym.objsection.MemPos)+objreloc.Addend));
- end;
- else
- internalerror(2024010110);
- end;
- end;
- RELOC_GLOBAL_INDEX_LEB:
- begin
- if objsym.typ<>AT_WASM_GLOBAL then
- internalerror(2024010111);
- objsec.Data.seek(objreloc.DataOffset);
- WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
- end;
- RELOC_TAG_INDEX_LEB:
- begin
- if objsym.typ<>AT_WASM_EXCEPTION_TAG then
- internalerror(2024010708);
- objsec.Data.seek(objreloc.DataOffset);
- WriteUleb5(objsec.Data,UInt32(objsym.offset+objsym.objsection.MemPos));
- end;
- else
- internalerror(2024010109);
- end;
- end
- else if assigned(objreloc.objsection) then
- begin
- if objreloc.typ<>RELOC_ABSOLUTE then
- internalerror(2024010601);
- objsec.Data.seek(objreloc.DataOffset);
- writeUInt32LE(UInt32((objreloc.objsection.MemPos)+objreloc.Addend));
- end
- else if objreloc.typ=RELOC_TYPE_INDEX_LEB then
- begin
- objreloc.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(objreloc.FuncType);
- objsec.Data.seek(objreloc.DataOffset);
- WriteUleb5(objsec.Data,objreloc.ExeTypeIndex);
- end
- else
- internalerror(2024010110);
- end;
- end;
- constructor TWasmExeOutput.create;
- var
- i: TWasmSectionID;
- j: TWasmCustomSectionType;
- begin
- inherited create;
- CObjData:=TWasmObjData;
- MaxMemPos:=$FFFFFFFF;
- FFuncTypes:=TWasmFuncTypeTable.Create;
- for i in TWasmSectionID do
- FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
- for j in TWasmCustomSectionType do
- FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
- SetLength(FIndirectFunctionTable,1);
- FIndirectFunctionTable[0].FuncIdx:=-1;
- end;
- destructor TWasmExeOutput.destroy;
- var
- i: TWasmSectionID;
- j: TWasmCustomSectionType;
- begin
- for i in TWasmSectionID do
- FWasmSections[i].Free;
- for j in TWasmCustomSectionType do
- FWasmCustomSections[j].Free;
- FFuncTypes.Free;
- inherited destroy;
- end;
- procedure TWasmExeOutput.GenerateLibraryImports(ImportLibraryList: TFPHashObjectList);
- var
- i, j: Integer;
- ImportLibrary: TImportLibrary;
- ImportSymbol: TImportSymbol;
- exesym: TExeSymbol;
- begin
- { Here map import symbols to exe symbols and create necessary sections.
- Actual import generation is done after unused sections (and symbols) are removed. }
- FImports:=ImportLibraryList;
- for i:=0 to ImportLibraryList.Count-1 do
- begin
- ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
- for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
- begin
- ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
- exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
- if assigned(exesym) and
- (exesym.State<>symstate_defined) then
- begin
- ImportSymbol.CachedExeSymbol:=exesym;
- exesym.State:=symstate_defined;
- end;
- end;
- end;
- PackUnresolvedExeSymbols('after module imports');
- end;
- procedure TWasmExeOutput.AfterUnusedSectionRemoval;
- begin
- PrepareImports;
- PrepareFunctions;
- PrepareTags;
- end;
- procedure TWasmExeOutput.MemPos_ExeSection(const aname: string);
- const
- DebugPrefix = '.debug_';
- var
- ExeSec: TExeSection;
- i: Integer;
- objsec: TObjSection;
- begin
- { WebAssembly is a Harvard architecture.
- Data lives in a separate address space, so start addressing back from 0
- (the LLVM leaves the first 1024 bytes in the data segment empty, so we
- start at 1024). }
- if aname='.rodata' then
- begin
- CurrMemPos:=1024;
- inherited;
- end
- else if aname='.text' then
- begin
- CurrMemPos:=0;
- ExeSec:=FindExeSection(aname);
- if not assigned(ExeSec) then
- exit;
- exesec.MemPos:=CurrMemPos;
- CurrMemPos:=CurrMemPos+UlebEncodingSize(exesec.ObjSectionList.Count);
- { set position of object ObjSections }
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TObjSection(exesec.ObjSectionList[i]);
- CurrMemPos:=CurrMemPos+UlebEncodingSize(objsec.Size);
- CurrMemPos:=objsec.setmempos(CurrMemPos);
- end;
- { calculate size of the section }
- exesec.Size:=CurrMemPos-exesec.MemPos;
- end
- else if (aname='.wasm_globals') or (aname='.wasm_tags') or
- (Copy(aname,1,Length(DebugPrefix))=DebugPrefix) then
- begin
- CurrMemPos:=0;
- inherited;
- end
- else
- inherited;
- end;
- procedure TWasmExeOutput.Load_Symbol(const aname: string);
- begin
- if aname=StackPointerSymStr then
- begin
- internalObjData.createsection('*'+aname,1,[oso_Data,oso_load]);
- FStackPointerSym:=TWasmObjSymbol(internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_WASM_GLOBAL));
- FStackPointerSym.size:=1;
- FStackPointerSym.ObjSection.WriteZeros(1);
- TWasmObjSection(FStackPointerSym.ObjSection).MainFuncSymbol:=FStackPointerSym;
- FStackPointerSym.LinkingData.GlobalType:=wbt_i32;
- FStackPointerSym.LinkingData.GlobalIsMutable:=True;
- FStackPointerSym.LinkingData.GlobalInitializer.typ:=wbt_i32;
- FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=0;
- end
- else
- inherited;
- end;
- procedure TWasmExeOutput.PrepareImports;
- function AddFunctionImport(const libname,symname:TCmdStr; functype: TWasmFuncType): Integer;
- begin
- SetLength(FFunctionImports,Length(FFunctionImports)+1);
- Result:=High(FFunctionImports);
- if assigned(exemap) then
- exemap.Add(' Importing Function[' + tostr(Result) + '] ' + symname + functype.ToString);
- with FFunctionImports[Result] do
- begin
- ModName:=libname;
- Name:=symname;
- TypeIdx:=FFuncTypes.AddOrGetFuncType(functype);
- end;
- end;
- var
- i, j: Integer;
- ImportLibrary: TImportLibrary;
- ImportSymbol: TImportSymbol;
- exesym: TExeSymbol;
- newdll: Boolean;
- fsym: TWasmObjSymbol;
- objdata: TObjData;
- begin
- for i:=0 to FImports.Count-1 do
- begin
- ImportLibrary:=TImportLibrary(FImports[i]);
- newdll:=False;
- for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
- begin
- ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
- exesym:=ImportSymbol.CachedExeSymbol;
- if assigned(exesym) and
- exesym.Used then
- begin
- if (not newdll) and assigned(exemap) then
- begin
- exemap.Add('');
- exemap.Add('Importing from module '+ImportLibrary.Name);
- end;
- newdll:=True;
- TWasmObjSymbol(exesym.ObjSymbol).LinkingData.ExeFunctionIndex:=
- AddFunctionImport(ImportLibrary.Name,ImportSymbol.Name,TWasmObjSymbol(exesym.ObjSymbol).LinkingData.FuncType);
- end;
- end;
- end;
- { set ExeFunctionIndex to the alias symbols as well }
- for i:=0 to ObjDataList.Count-1 do
- begin
- objdata:=TObjData(ObjDataList[i]);
- for j:=0 to objdata.ObjSymbolList.Count-1 do
- begin
- fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
- if (fsym.LinkingData.ExeFunctionIndex=-1) and assigned(fsym.exesymbol) and (TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex<>-1) then
- fsym.LinkingData.ExeFunctionIndex:=TWasmObjSymbol(fsym.exesymbol.ObjSymbol).LinkingData.ExeFunctionIndex;
- end;
- end;
- end;
- procedure TWasmExeOutput.PrepareFunctions;
- var
- i, j: Integer;
- exesec: TExeSection;
- objsec: TWasmObjSection;
- fsym: TWasmObjSymbol;
- objdata: TObjData;
- begin
- if assigned(exemap) then
- begin
- exemap.Add('');
- exemap.Add('Functions, defined in this module:');
- end;
- exesec:=FindExeSection('.text');
- if not assigned(exesec) then
- internalerror(2023123106);
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
- fsym:=objsec.MainFuncSymbol;
- if not assigned(fsym) then
- internalerror(2023123107);
- if not assigned(fsym.LinkingData.FuncType) then
- internalerror(2023123108);
- if fsym.LinkingData.ExeFunctionIndex<>-1 then
- internalerror(2023123109);
- if fsym.LinkingData.ExeTypeIndex<>-1 then
- internalerror(2023123109);
- fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
- fsym.LinkingData.ExeFunctionIndex:=i+Length(FFunctionImports);
- if assigned(exemap) then
- begin
- exemap.Add(' Function[' + tostr(fsym.LinkingData.ExeFunctionIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
- end;
- end;
- { set ExeFunctionIndex to the alias symbols as well }
- for i:=0 to ObjDataList.Count-1 do
- begin
- objdata:=TObjData(ObjDataList[i]);
- for j:=0 to objdata.ObjSymbolList.Count-1 do
- begin
- fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
- if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_FUNCTION) and (fsym.LinkingData.ExeFunctionIndex=-1) then
- begin
- fsym.LinkingData.ExeFunctionIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeFunctionIndex;
- if fsym.LinkingData.ExeFunctionIndex=-1 then
- internalerror(2024010102);
- end;
- end;
- end;
- end;
- procedure TWasmExeOutput.PrepareTags;
- var
- exesec: TExeSection;
- i, j: Integer;
- objsec: TWasmObjSection;
- fsym: TWasmObjSymbol;
- objdata: TObjData;
- begin
- exesec:=FindExeSection('.wasm_tags');
- if not assigned(exesec) then
- exit;
- if assigned(exemap) then
- begin
- exemap.Add('');
- exemap.Add('Tags, defined in this module:');
- end;
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TWasmObjSection(exesec.ObjSectionList[i]);
- fsym:=objsec.MainFuncSymbol;
- if not assigned(fsym) then
- internalerror(2024010703);
- if not assigned(fsym.LinkingData.FuncType) then
- internalerror(2024010704);
- if fsym.LinkingData.ExeTagIndex<>-1 then
- internalerror(2024010705);
- if fsym.LinkingData.ExeTypeIndex<>-1 then
- internalerror(2024010706);
- fsym.LinkingData.ExeTypeIndex:=FFuncTypes.AddOrGetFuncType(fsym.LinkingData.FuncType);
- fsym.LinkingData.ExeTagIndex:=i+Length(FTagImports);
- if assigned(exemap) then
- begin
- exemap.Add(' Tag[' + tostr(fsym.LinkingData.ExeTagIndex) + '] ' + fsym.Name + fsym.LinkingData.FuncType.ToString);
- end;
- end;
- { set ExeTagIndex to the alias symbols as well }
- for i:=0 to ObjDataList.Count-1 do
- begin
- objdata:=TObjData(ObjDataList[i]);
- for j:=0 to objdata.ObjSymbolList.Count-1 do
- begin
- fsym:=TWasmObjSymbol(objdata.ObjSymbolList[j]);
- if assigned(fsym.objsection) and fsym.objsection.USed and (fsym.typ=AT_WASM_EXCEPTION_TAG) and (fsym.LinkingData.ExeTagIndex=-1) then
- begin
- fsym.LinkingData.ExeTagIndex:=TWasmObjSection(fsym.objsection).MainFuncSymbol.LinkingData.ExeTagIndex;
- if fsym.LinkingData.ExeTagIndex=-1 then
- internalerror(2024010707);
- end;
- end;
- end;
- end;
- function TWasmExeOutput.AddOrGetIndirectFunctionTableIndex(FuncIdx: Integer): integer;
- var
- i: Integer;
- begin
- for i:=1 to length(FIndirectFunctionTable)-1 do
- if FIndirectFunctionTable[i].FuncIdx=FuncIdx then
- begin
- Result:=i;
- exit;
- end;
- SetLength(FIndirectFunctionTable,Length(FIndirectFunctionTable)+1);
- Result:=High(FIndirectFunctionTable);
- FIndirectFunctionTable[Result].FuncIdx:=FuncIdx;
- end;
- procedure TWasmExeOutput.SetStackPointer;
- var
- BssSec: TExeSection;
- StackStart, InitialStackPtrAddr: QWord;
- begin
- BssSec:=FindExeSection('.bss');
- InitialStackPtrAddr := (BssSec.MemPos+BssSec.Size+stacksize+15) and (not 15);
- FMinMemoryPages := (InitialStackPtrAddr+65535) shr 16;
- FStackPointerSym.LinkingData.GlobalInitializer.init_i32:=Int32(InitialStackPtrAddr);
- end;
- procedure TWasmExeOutput.WriteExeSectionToDynArray(exesec: TExeSection; dynarr: tdynamicarray);
- var
- exesecdatapos: LongWord;
- i: Integer;
- objsec: TObjSection;
- dpos, pad: QWord;
- begin
- exesecdatapos:=dynarr.size;
- for i:=0 to exesec.ObjSectionList.Count-1 do
- begin
- objsec:=TObjSection(exesec.ObjSectionList[i]);
- if not (oso_data in objsec.secoptions) then
- internalerror(2024010104);
- if not assigned(objsec.data) then
- internalerror(2024010105);
- dpos:=objsec.MemPos-exesec.MemPos+exesecdatapos;
- pad:=dpos-dynarr.size;
- { objsection must be within SecAlign bytes from the previous one }
- if (dpos<dynarr.Size) or
- (pad>=max(objsec.SecAlign,1)) then
- internalerror(2024010106);
- writeZeros(dynarr,pad);
- objsec.data.seek(0);
- CopyDynamicArray(objsec.data,dynarr,objsec.data.size);
- end;
- if (dynarr.size-exesecdatapos)<>exesec.Size then
- internalerror(2024010107);
- end;
- {****************************************************************************
- TWasmAssembler
- ****************************************************************************}
- constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
- begin
- inherited;
- CObjOutput:=TWasmObjOutput;
- end;
- {*****************************************************************************
- Initialize
- *****************************************************************************}
- {$ifdef wasm32}
- const
- as_wasm32_wasm_info : tasminfo =
- (
- id : as_wasm32_wasm;
- idtxt : 'WASM';
- asmbin : '';
- asmcmd : '';
- supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
- flags : [af_outputbinary,af_smartlink_sections];
- labelprefix : '..@';
- labelmaxlen : -1;
- comment : '; ';
- dollarsign: '$';
- );
- {$endif wasm32}
- initialization
- {$ifdef wasm32}
- RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
- {$endif wasm32}
- end.
|