ogwasm.pas 163 KB

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