ogwasm.pas 161 KB

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