ogwasm.pas 196 KB

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