ogwasm.pas 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805
  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. { TWasmObjSymbol }
  35. TWasmObjSymbol = class(TObjSymbol)
  36. FuncIndex: Integer;
  37. SymbolIndex: Integer;
  38. GlobalIndex: Integer;
  39. TagIndex: Integer;
  40. AliasOf: string;
  41. ExtraData: TWasmObjSymbolExtraData;
  42. constructor create(AList:TFPHashObjectList;const AName:string);override;
  43. function IsAlias: Boolean;
  44. end;
  45. { TWasmObjRelocation }
  46. TWasmObjRelocation = class(TObjRelocation)
  47. public
  48. TypeIndex: Integer;
  49. Addend: LongInt;
  50. constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
  51. end;
  52. { TWasmObjSymbolExtraData }
  53. TWasmObjSymbolExtraData = class(TFPHashObject)
  54. TypeIdx: Integer;
  55. ExceptionTagTypeIdx: Integer;
  56. ImportModule: string;
  57. ImportName: string;
  58. ExportName: string;
  59. GlobalType: TWasmBasicType;
  60. GlobalIsImmutable: Boolean;
  61. Locals: array of TWasmBasicType;
  62. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  63. procedure AddLocal(bastyp: TWasmBasicType);
  64. end;
  65. { TWasmObjSection }
  66. TWasmObjSection = class(TObjSection)
  67. public
  68. SegIdx: Integer;
  69. SegSymIdx: Integer;
  70. SegOfs: qword;
  71. FileSectionOfs: qword;
  72. MainFuncSymbol: TWasmObjSymbol;
  73. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  74. function IsCode: Boolean;
  75. function IsData: Boolean;
  76. function IsDebug: Boolean;
  77. end;
  78. { TWasmObjData }
  79. TWasmObjData = class(TObjData)
  80. private
  81. FFuncTypes: array of TWasmFuncType;
  82. FObjSymbolsExtraDataList: TFPHashObjectList;
  83. FLastFuncName: string;
  84. function is_smart_section(atype:TAsmSectiontype):boolean;
  85. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  86. public
  87. constructor create(const n:string);override;
  88. destructor destroy; override;
  89. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  90. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  91. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  92. function AddFuncType(wft: TWasmFuncType): integer;
  93. function globalref(asmsym:TAsmSymbol):TObjSymbol;
  94. function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
  95. procedure DeclareGlobalType(gt: tai_globaltype);
  96. procedure DeclareFuncType(ft: tai_functype);
  97. procedure DeclareTagType(tt: tai_tagtype);
  98. procedure DeclareExportName(en: tai_export_name);
  99. procedure DeclareImportModule(aim: tai_import_module);
  100. procedure DeclareImportName(ain: tai_import_name);
  101. procedure DeclareLocal(al: tai_local);
  102. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  103. end;
  104. { TWasmObjOutput }
  105. TWasmObjOutput = class(tObjOutput)
  106. private
  107. FData: TWasmObjData;
  108. FWasmRelocationCodeTable: tdynamicarray;
  109. FWasmRelocationCodeTableEntriesCount: Integer;
  110. FWasmRelocationDataTable: tdynamicarray;
  111. FWasmRelocationDataTableEntriesCount: Integer;
  112. FWasmRelocationDebugFrameTable: tdynamicarray;
  113. FWasmRelocationDebugFrameTableEntriesCount: Integer;
  114. FWasmRelocationDebugInfoTable: tdynamicarray;
  115. FWasmRelocationDebugInfoTableEntriesCount: Integer;
  116. FWasmRelocationDebugLineTable: tdynamicarray;
  117. FWasmRelocationDebugLineTableEntriesCount: Integer;
  118. FWasmRelocationDebugAbbrevTable: tdynamicarray;
  119. FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
  120. FWasmRelocationDebugArangesTable: tdynamicarray;
  121. FWasmRelocationDebugArangesTableEntriesCount: Integer;
  122. FWasmRelocationDebugRangesTable: tdynamicarray;
  123. FWasmRelocationDebugRangesTableEntriesCount: Integer;
  124. FWasmRelocationDebugStrTable: tdynamicarray;
  125. FWasmRelocationDebugStrTableEntriesCount: Integer;
  126. FWasmSymbolTable: tdynamicarray;
  127. FWasmSymbolTableEntriesCount: Integer;
  128. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  129. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  130. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  131. procedure WriteUleb(d: tdynamicarray; v: uint64);
  132. procedure WriteUleb(w: TObjectWriter; v: uint64);
  133. procedure WriteSleb(d: tdynamicarray; v: int64);
  134. procedure WriteByte(d: tdynamicarray; b: byte);
  135. procedure WriteName(d: tdynamicarray; const s: string);
  136. procedure WriteWasmSection(wsid: TWasmSectionID);
  137. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  138. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  139. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  140. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  141. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  142. function IsExternalFunction(sym: TObjSymbol): Boolean;
  143. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  144. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  145. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  146. procedure WriteSymbolTable;
  147. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  148. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  149. procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  150. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  151. procedure DoRelocations;
  152. procedure WriteRelocations;
  153. function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  154. protected
  155. function writeData(Data:TObjData):boolean;override;
  156. public
  157. constructor create(AWriter:TObjectWriter);override;
  158. destructor destroy;override;
  159. end;
  160. { TWasmObjInput }
  161. TWasmObjInput = class(TObjInput)
  162. private
  163. FFuncTypes: array of TWasmFuncType;
  164. function ReadUleb(r: TObjectReader; out v: uint64): boolean;
  165. function ReadName(r: TObjectReader; out v: ansistring): boolean;
  166. public
  167. constructor create;override;
  168. destructor Destroy;override;
  169. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  170. function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
  171. end;
  172. { TWasmExeOutput }
  173. TWasmExeOutput = class(TExeOutput)
  174. protected
  175. function writeData:boolean;override;
  176. procedure DoRelocationFixup(objsec:TObjSection);override;
  177. public
  178. constructor create;override;
  179. end;
  180. { TWasmAssembler }
  181. TWasmAssembler = class(tinternalassembler)
  182. constructor create(info: pasminfo; smart:boolean);override;
  183. end;
  184. implementation
  185. uses
  186. cutils,verbose,version,globals;
  187. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  188. var
  189. b: byte;
  190. i: Integer;
  191. begin
  192. for i:=1 to 5 do
  193. begin
  194. b:=byte(v) and 127;
  195. v:=v shr 7;
  196. if i<>5 then
  197. b:=b or 128;
  198. d.write(b,1);
  199. end;
  200. end;
  201. procedure WriteUleb5(d: tobjsection; v: uint64);
  202. var
  203. b: byte;
  204. i: Integer;
  205. begin
  206. for i:=1 to 5 do
  207. begin
  208. b:=byte(v) and 127;
  209. v:=v shr 7;
  210. if i<>5 then
  211. b:=b or 128;
  212. d.write(b,1);
  213. end;
  214. end;
  215. procedure WriteSleb5(d: tdynamicarray; v: int64);
  216. var
  217. b: byte;
  218. i: Integer;
  219. begin
  220. for i:=1 to 5 do
  221. begin
  222. b:=byte(v) and 127;
  223. v:=SarInt64(v,7);
  224. if i<>5 then
  225. b:=b or 128;
  226. d.write(b,1);
  227. end;
  228. end;
  229. procedure WriteSleb5(d: tobjsection; v: int64);
  230. var
  231. b: byte;
  232. i: Integer;
  233. begin
  234. for i:=1 to 5 do
  235. begin
  236. b:=byte(v) and 127;
  237. v:=SarInt64(v,7);
  238. if i<>5 then
  239. b:=b or 128;
  240. d.write(b,1);
  241. end;
  242. end;
  243. function ReadUleb(d: tdynamicarray): uint64;
  244. var
  245. b: byte;
  246. shift:integer;
  247. begin
  248. b:=0;
  249. result:=0;
  250. shift:=0;
  251. repeat
  252. d.read(b,1);
  253. result:=result or (uint64(b and 127) shl shift);
  254. inc(shift,7);
  255. until (b and 128)=0;
  256. end;
  257. function ReadSleb(d: tdynamicarray): int64;
  258. var
  259. b: byte;
  260. shift:integer;
  261. begin
  262. b:=0;
  263. result:=0;
  264. shift:=0;
  265. repeat
  266. d.read(b,1);
  267. result:=result or (uint64(b and 127) shl shift);
  268. inc(shift,7);
  269. until (b and 128)=0;
  270. {$ifopt Q+}
  271. {$define overflowon}
  272. {$Q-}
  273. {$endif}
  274. {$ifopt R+}
  275. {$define rangeon}
  276. {$R-}
  277. {$endif}
  278. if (b and 64)<>0 then
  279. result:=result or (high(uint64) shl shift);
  280. end;
  281. {$ifdef overflowon}
  282. {$Q+}
  283. {$undef overflowon}
  284. {$endif}
  285. {$ifdef rangeon}
  286. {$R+}
  287. {$undef rangeon}
  288. {$endif}
  289. procedure AddSleb5(d: tdynamicarray; v: int64);
  290. var
  291. q: Int64;
  292. p: LongWord;
  293. begin
  294. p:=d.Pos;
  295. q:=ReadSleb(d);
  296. q:=q+v;
  297. d.seek(p);
  298. WriteSleb5(d,q);
  299. end;
  300. procedure AddUleb5(d: tdynamicarray; v: int64);
  301. var
  302. q: UInt64;
  303. p: LongWord;
  304. begin
  305. p:=d.Pos;
  306. q:=ReadUleb(d);
  307. q:=q+v;
  308. d.seek(p);
  309. WriteUleb5(d,q);
  310. end;
  311. procedure AddInt32(d: tdynamicarray; v: int32);
  312. var
  313. q: int32;
  314. p: LongWord;
  315. begin
  316. p:=d.Pos;
  317. d.read(q,4);
  318. {$ifdef FPC_BIG_ENDIAN}
  319. q:=SwapEndian(q);
  320. {$endif FPC_BIG_ENDIAN}
  321. q:=q+v;
  322. {$ifdef FPC_BIG_ENDIAN}
  323. q:=SwapEndian(q);
  324. {$endif FPC_BIG_ENDIAN}
  325. d.seek(p);
  326. d.write(q,4);
  327. end;
  328. {****************************************************************************
  329. TWasmObjRelocation
  330. ****************************************************************************}
  331. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  332. begin
  333. DataOffset:=ADataOffset;
  334. Symbol:=nil;
  335. OrgSize:=0;
  336. Group:=nil;
  337. ObjSection:=nil;
  338. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  339. TypeIndex:=ATypeIndex;
  340. end;
  341. {****************************************************************************
  342. TWasmObjSymbol
  343. ****************************************************************************}
  344. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  345. begin
  346. inherited create(AList,AName);
  347. FuncIndex:=-1;
  348. SymbolIndex:=-1;
  349. GlobalIndex:=-1;
  350. TagIndex:=-1;
  351. AliasOf:='';
  352. ExtraData:=nil;
  353. end;
  354. function TWasmObjSymbol.IsAlias: Boolean;
  355. begin
  356. result:=AliasOf<>'';
  357. end;
  358. {****************************************************************************
  359. TWasmObjSymbolExtraData
  360. ****************************************************************************}
  361. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  362. begin
  363. inherited Create(HashObjectList,s);
  364. TypeIdx:=-1;
  365. ExceptionTagTypeIdx:=-1;
  366. end;
  367. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  368. begin
  369. SetLength(Locals,Length(Locals)+1);
  370. Locals[High(Locals)]:=bastyp;
  371. end;
  372. {****************************************************************************
  373. TWasmObjSection
  374. ****************************************************************************}
  375. constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  376. begin
  377. inherited create(AList, Aname, Aalign, Aoptions);
  378. SegIdx:=-1;
  379. SegSymIdx:=-1;
  380. MainFuncSymbol:=nil;
  381. end;
  382. function TWasmObjSection.IsCode: Boolean;
  383. const
  384. CodePrefix = '.text';
  385. begin
  386. result:=(Length(Name)>=Length(CodePrefix)) and
  387. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  388. end;
  389. function TWasmObjSection.IsData: Boolean;
  390. begin
  391. result:=not (IsCode or IsDebug);
  392. end;
  393. function TWasmObjSection.IsDebug: Boolean;
  394. const
  395. DebugPrefix = '.debug';
  396. begin
  397. result:=(Length(Name)>=Length(DebugPrefix)) and
  398. (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
  399. end;
  400. {****************************************************************************
  401. TWasmObjData
  402. ****************************************************************************}
  403. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  404. begin
  405. { For bss we need to set some flags that are target dependent,
  406. it is easier to disable it for smartlinking. It doesn't take up
  407. filespace }
  408. result:=not(target_info.system in systems_darwin) and
  409. create_smartlink_sections and
  410. (atype<>sec_toc) and
  411. (atype<>sec_user) and
  412. { on embedded systems every byte counts, so smartlink bss too }
  413. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  414. end;
  415. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  416. const aname: string; aorder: TAsmSectionOrder): string;
  417. const
  418. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  419. '.text',
  420. '.data',
  421. { why doesn't .rodata work? (FK) }
  422. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  423. { vtables (and anything else containing relocations), otherwise those are }
  424. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  425. { vtable for a class called Window: }
  426. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  427. { TODO: .data.ro not yet working}
  428. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  429. '.rodata',
  430. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  431. '.data',
  432. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  433. '.rodata',
  434. '.bss',
  435. '.tbss',
  436. '.pdata',
  437. '', { stubs }
  438. '__DATA,__nl_symbol_ptr',
  439. '__DATA,__la_symbol_ptr',
  440. '__DATA,__mod_init_func',
  441. '__DATA,__mod_term_func',
  442. '.stab',
  443. '.stabstr',
  444. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  445. '.eh_frame',
  446. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  447. '.fpc',
  448. '.toc',
  449. '.init',
  450. '.fini',
  451. '.objc_class',
  452. '.objc_meta_class',
  453. '.objc_cat_cls_meth',
  454. '.objc_cat_inst_meth',
  455. '.objc_protocol',
  456. '.objc_string_object',
  457. '.objc_cls_meth',
  458. '.objc_inst_meth',
  459. '.objc_cls_refs',
  460. '.objc_message_refs',
  461. '.objc_symbols',
  462. '.objc_category',
  463. '.objc_class_vars',
  464. '.objc_instance_vars',
  465. '.objc_module_info',
  466. '.objc_class_names',
  467. '.objc_meth_var_types',
  468. '.objc_meth_var_names',
  469. '.objc_selector_strs',
  470. '.objc_protocol_ext',
  471. '.objc_class_ext',
  472. '.objc_property',
  473. '.objc_image_info',
  474. '.objc_cstring_object',
  475. '.objc_sel_fixup',
  476. '__DATA,__objc_data',
  477. '__DATA,__objc_const',
  478. '.objc_superrefs',
  479. '__DATA, __datacoal_nt,coalesced',
  480. '.objc_classlist',
  481. '.objc_nlclasslist',
  482. '.objc_catlist',
  483. '.obcj_nlcatlist',
  484. '.objc_protolist',
  485. '.stack',
  486. '.heap',
  487. '.gcc_except_table',
  488. '.ARM.attributes'
  489. );
  490. var
  491. sep : string[3];
  492. secname : string;
  493. begin
  494. secname:=secnames[atype];
  495. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  496. begin
  497. result:=secname+'.'+aname;
  498. exit;
  499. end;
  500. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  501. Thus, data which normally goes into .rodata and .rodata_norel sections must
  502. end up in .data section }
  503. if (atype in [sec_rodata,sec_rodata_norel]) and
  504. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  505. secname:='.data';
  506. { Windows correctly handles reallocations in readonly sections }
  507. if (atype=sec_rodata) and
  508. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  509. secname:='.rodata';
  510. { section type user gives the user full controll on the section name }
  511. if atype=sec_user then
  512. secname:=aname;
  513. if is_smart_section(atype) and (aname<>'') then
  514. begin
  515. case aorder of
  516. secorder_begin :
  517. sep:='.b_';
  518. secorder_end :
  519. sep:='.z_';
  520. else
  521. sep:='.n_';
  522. end;
  523. result:=secname+sep+aname
  524. end
  525. else
  526. result:=secname;
  527. end;
  528. constructor TWasmObjData.create(const n: string);
  529. begin
  530. inherited;
  531. CObjSection:=TWasmObjSection;
  532. CObjSymbol:=TWasmObjSymbol;
  533. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  534. end;
  535. destructor TWasmObjData.destroy;
  536. var
  537. i: Integer;
  538. begin
  539. FObjSymbolsExtraDataList.Free;
  540. for i:=low(FFuncTypes) to high(FFuncTypes) do
  541. begin
  542. FFuncTypes[i].free;
  543. FFuncTypes[i]:=nil;
  544. end;
  545. inherited destroy;
  546. end;
  547. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  548. const aname: string; aorder: TAsmSectionOrder): string;
  549. begin
  550. if (atype=sec_fpc) or
  551. ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
  552. atype:=sec_data;
  553. Result:=sectionname_gas(atype, aname, aorder);
  554. end;
  555. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  556. p: TObjSymbol; Reloctype: TObjRelocationType);
  557. const
  558. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  559. var
  560. objreloc: TWasmObjRelocation;
  561. begin
  562. if CurrObjSec=nil then
  563. internalerror(200403072);
  564. { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
  565. todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
  566. if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
  567. Reloctype:=RELOC_ABSOLUTE;
  568. objreloc:=nil;
  569. case Reloctype of
  570. RELOC_FUNCTION_INDEX_LEB:
  571. begin
  572. if Data<>0 then
  573. internalerror(2021092502);
  574. if len<>5 then
  575. internalerror(2021092503);
  576. if not assigned(p) then
  577. internalerror(2021092504);
  578. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  579. CurrObjSec.ObjRelocations.Add(objreloc);
  580. writebytes(leb_zero,5);
  581. end;
  582. RELOC_MEMORY_ADDR_LEB,
  583. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  584. begin
  585. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  586. internalerror(2021092602);
  587. if len<>5 then
  588. internalerror(2021092503);
  589. if not assigned(p) then
  590. internalerror(2021092504);
  591. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  592. objreloc.Addend:=Data;
  593. CurrObjSec.ObjRelocations.Add(objreloc);
  594. if RelocType=RELOC_MEMORY_ADDR_LEB then
  595. WriteUleb5(CurrObjSec,Data)
  596. else
  597. WriteSleb5(CurrObjSec,Data);
  598. end;
  599. RELOC_ABSOLUTE:
  600. begin
  601. if len<>4 then
  602. internalerror(2021092607);
  603. if not assigned(p) then
  604. internalerror(2021092608);
  605. if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
  606. (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
  607. begin
  608. objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
  609. objreloc.Addend:=Data+p.Address;
  610. CurrObjSec.ObjRelocations.Add(objreloc);
  611. {inc(data,p.address);}
  612. data:=0;
  613. Data:=NtoLE(Data);
  614. writebytes(Data,4);
  615. end
  616. else
  617. begin
  618. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  619. objreloc.Addend:=Data;
  620. CurrObjSec.ObjRelocations.Add(objreloc);
  621. Data:=NtoLE(Data);
  622. writebytes(Data,4);
  623. end;
  624. end;
  625. RELOC_TYPE_INDEX_LEB:
  626. begin
  627. if len<>5 then
  628. internalerror(2021092612);
  629. if assigned(p) then
  630. internalerror(2021092613);
  631. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  632. CurrObjSec.ObjRelocations.Add(objreloc);
  633. WriteUleb5(CurrObjSec,Data);
  634. end;
  635. RELOC_GLOBAL_INDEX_LEB:
  636. begin
  637. if len<>5 then
  638. internalerror(2021092701);
  639. if Data<>0 then
  640. internalerror(2021092702);
  641. if not assigned(p) then
  642. internalerror(2021092703);
  643. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  644. CurrObjSec.ObjRelocations.Add(objreloc);
  645. WriteUleb5(CurrObjSec,0);
  646. end;
  647. RELOC_TAG_INDEX_LEB:
  648. begin
  649. if len<>5 then
  650. internalerror(2021092712);
  651. if Data<>0 then
  652. internalerror(2021092713);
  653. if not assigned(p) then
  654. internalerror(2021092714);
  655. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  656. CurrObjSec.ObjRelocations.Add(objreloc);
  657. WriteSleb5(CurrObjSec,0);
  658. end;
  659. else
  660. internalerror(2021092501);
  661. end;
  662. end;
  663. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  664. begin
  665. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  666. if not assigned(result) then
  667. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  668. end;
  669. function TWasmObjData.AddFuncType(wft: TWasmFuncType): integer;
  670. var
  671. i: Integer;
  672. begin
  673. for i:=low(FFuncTypes) to high(FFuncTypes) do
  674. if wft.Equals(FFuncTypes[i]) then
  675. exit(i);
  676. result:=Length(FFuncTypes);
  677. SetLength(FFuncTypes,result+1);
  678. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  679. end;
  680. function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
  681. begin
  682. if assigned(asmsym) then
  683. begin
  684. if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
  685. internalerror(2021092706);
  686. result:=symbolref(asmsym);
  687. result.typ:=asmsym.typ;
  688. end
  689. else
  690. result:=nil;
  691. end;
  692. function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
  693. begin
  694. if assigned(asmsym) then
  695. begin
  696. if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
  697. internalerror(2021092707);
  698. result:=symbolref(asmsym);
  699. result.typ:=AT_WASM_EXCEPTION_TAG;
  700. end
  701. else
  702. result:=nil;
  703. end;
  704. procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
  705. var
  706. ObjSymExtraData: TWasmObjSymbolExtraData;
  707. ObjSym: TObjSymbol;
  708. begin
  709. if not gt.is_external then
  710. begin
  711. ObjSym:=symboldefine(gt.sym);
  712. ObjSym.typ:=AT_WASM_GLOBAL;
  713. end;
  714. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
  715. ObjSymExtraData.GlobalType:=gt.gtype;
  716. ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
  717. end;
  718. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  719. var
  720. i: Integer;
  721. ObjSymExtraData: TWasmObjSymbolExtraData;
  722. begin
  723. FLastFuncName:=ft.funcname;
  724. i:=AddFuncType(ft.functype);
  725. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  726. ObjSymExtraData.TypeIdx:=i;
  727. end;
  728. procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
  729. var
  730. ObjSymExtraData: TWasmObjSymbolExtraData;
  731. ft: TWasmFuncType;
  732. i: Integer;
  733. begin
  734. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
  735. ft:=TWasmFuncType.Create([],tt.params);
  736. i:=AddFuncType(ft);
  737. ft.free;
  738. ObjSymExtraData.ExceptionTagTypeIdx:=i;
  739. end;
  740. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  741. var
  742. ObjSymExtraData: TWasmObjSymbolExtraData;
  743. begin
  744. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  745. ObjSymExtraData.ExportName:=en.extname;
  746. end;
  747. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  748. var
  749. ObjSymExtraData: TWasmObjSymbolExtraData;
  750. begin
  751. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  752. ObjSymExtraData.ImportModule:=aim.importmodule;
  753. end;
  754. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  755. var
  756. ObjSymExtraData: TWasmObjSymbolExtraData;
  757. begin
  758. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  759. ObjSymExtraData.ImportName:=ain.importname;
  760. end;
  761. procedure TWasmObjData.DeclareLocal(al: tai_local);
  762. var
  763. ObjSymExtraData: TWasmObjSymbolExtraData;
  764. begin
  765. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  766. ObjSymExtraData.AddLocal(al.bastyp);
  767. end;
  768. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  769. var
  770. valsym: TObjSymbol;
  771. aliassym: TWasmObjSymbol;
  772. begin
  773. valsym:=CreateSymbol(avalue);
  774. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  775. aliassym.AliasOf:=valsym.Name;
  776. end;
  777. {****************************************************************************
  778. TWasmObjOutput
  779. ****************************************************************************}
  780. procedure TWasmObjOutput.WriteUleb(d: tdynamicarray; v: uint64);
  781. var
  782. b: byte;
  783. begin
  784. repeat
  785. b:=byte(v) and 127;
  786. v:=v shr 7;
  787. if v<>0 then
  788. b:=b or 128;
  789. d.write(b,1);
  790. until v=0;
  791. end;
  792. procedure TWasmObjOutput.WriteUleb(w: TObjectWriter; v: uint64);
  793. var
  794. b: byte;
  795. begin
  796. repeat
  797. b:=byte(v) and 127;
  798. v:=v shr 7;
  799. if v<>0 then
  800. b:=b or 128;
  801. w.write(b,1);
  802. until v=0;
  803. end;
  804. procedure TWasmObjOutput.WriteSleb(d: tdynamicarray; v: int64);
  805. var
  806. b: byte;
  807. Done: Boolean=false;
  808. begin
  809. repeat
  810. b:=byte(v) and 127;
  811. v:=SarInt64(v,7);
  812. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  813. Done:=true
  814. else
  815. b:=b or 128;
  816. d.write(b,1);
  817. until Done;
  818. end;
  819. procedure TWasmObjOutput.WriteByte(d: tdynamicarray; b: byte);
  820. begin
  821. d.write(b,1);
  822. end;
  823. procedure TWasmObjOutput.WriteName(d: tdynamicarray; const s: string);
  824. begin
  825. WriteUleb(d,Length(s));
  826. d.writestr(s);
  827. end;
  828. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  829. var
  830. b: byte;
  831. begin
  832. b:=ord(wsid);
  833. Writer.write(b,1);
  834. WriteUleb(Writer,FWasmSections[wsid].size);
  835. Writer.writearray(FWasmSections[wsid]);
  836. end;
  837. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  838. var
  839. b: byte;
  840. begin
  841. b:=0;
  842. Writer.write(b,1);
  843. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  844. Writer.writearray(FWasmCustomSections[wcst]);
  845. end;
  846. procedure TWasmObjOutput.CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  847. var
  848. buf: array [0..4095] of byte;
  849. bs: Integer;
  850. begin
  851. while size>0 do
  852. begin
  853. if size<SizeOf(buf) then
  854. bs:=Integer(size)
  855. else
  856. bs:=SizeOf(buf);
  857. src.read(buf,bs);
  858. dest.write(buf,bs);
  859. dec(size,bs);
  860. end;
  861. end;
  862. procedure TWasmObjOutput.WriteZeros(dest: tdynamicarray; size: QWord);
  863. var
  864. buf : array[0..1023] of byte;
  865. bs: Integer;
  866. begin
  867. fillchar(buf,sizeof(buf),0);
  868. while size>0 do
  869. begin
  870. if size<SizeOf(buf) then
  871. bs:=Integer(size)
  872. else
  873. bs:=SizeOf(buf);
  874. dest.write(buf,bs);
  875. dec(size,bs);
  876. end;
  877. end;
  878. procedure TWasmObjOutput.WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  879. var
  880. i: Integer;
  881. begin
  882. WriteUleb(dest,Length(wrt));
  883. for i:=low(wrt) to high(wrt) do
  884. WriteWasmBasicType(dest,wrt[i]);
  885. end;
  886. procedure TWasmObjOutput.WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  887. begin
  888. WriteByte(dest,encode_wasm_basic_type(wbt));
  889. end;
  890. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  891. var
  892. ExtraData: TWasmObjSymbolExtraData;
  893. begin
  894. if sym.bind=AB_EXTERNAL then
  895. begin
  896. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  897. result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
  898. end
  899. else
  900. result:=false;
  901. end;
  902. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  903. var
  904. ExtraData: TWasmObjSymbolExtraData;
  905. begin
  906. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  907. begin
  908. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  909. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  910. end
  911. else
  912. result:=false;
  913. end;
  914. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  915. var
  916. i,
  917. rle_entries,
  918. cnt: Integer;
  919. lasttype: TWasmBasicType;
  920. begin
  921. if Length(ed.Locals)=0 then
  922. begin
  923. WriteUleb(dest,0);
  924. exit;
  925. end;
  926. rle_entries:=1;
  927. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  928. if ed.Locals[i]<>ed.Locals[i-1] then
  929. inc(rle_entries);
  930. WriteUleb(dest,rle_entries);
  931. lasttype:=ed.Locals[Low(ed.Locals)];
  932. cnt:=1;
  933. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  934. if ed.Locals[i]=ed.Locals[i-1] then
  935. inc(cnt)
  936. else
  937. begin
  938. WriteUleb(dest,cnt);
  939. WriteWasmBasicType(dest,lasttype);
  940. lasttype:=ed.Locals[i];
  941. cnt:=1;
  942. end;
  943. WriteUleb(dest,cnt);
  944. WriteWasmBasicType(dest,lasttype);
  945. end;
  946. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  947. var
  948. encoded_locals: tdynamicarray;
  949. ObjSymExtraData: TWasmObjSymbolExtraData;
  950. codelen: LongWord;
  951. ObjSection: TWasmObjSection;
  952. codeexprlen: QWord;
  953. begin
  954. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  955. ObjSection:=TWasmObjSection(objsym.objsection);
  956. ObjSection.Data.seek(objsym.address);
  957. codeexprlen:=objsym.size;
  958. encoded_locals:=tdynamicarray.Create(64);
  959. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  960. codelen:=encoded_locals.size+codeexprlen+1;
  961. WriteUleb(dest,codelen);
  962. encoded_locals.seek(0);
  963. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  964. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  965. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  966. WriteByte(dest,$0B);
  967. encoded_locals.Free;
  968. end;
  969. procedure TWasmObjOutput.WriteSymbolTable;
  970. begin
  971. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  972. FWasmSymbolTable.seek(0);
  973. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  974. end;
  975. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  976. begin
  977. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  978. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  979. FWasmRelocationCodeTable.seek(0);
  980. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  981. end;
  982. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  983. begin
  984. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  985. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  986. FWasmRelocationDataTable.seek(0);
  987. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  988. end;
  989. procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  990. begin
  991. if EntriesCount>0 then
  992. begin
  993. WriteUleb(FWasmCustomSections[cst],SectionIndex);
  994. WriteUleb(FWasmCustomSections[cst],EntriesCount);
  995. Table.seek(0);
  996. CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
  997. WriteWasmCustomSection(cst);
  998. end;
  999. end;
  1000. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  1001. begin
  1002. if FWasmLinkingSubsections[wlst].size>0 then
  1003. begin
  1004. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  1005. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1006. FWasmLinkingSubsections[wlst].seek(0);
  1007. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1008. end;
  1009. end;
  1010. procedure TWasmObjOutput.DoRelocations;
  1011. var
  1012. si, ri: Integer;
  1013. objsec: TWasmObjSection;
  1014. objrel: TWasmObjRelocation;
  1015. begin
  1016. for si:=0 to FData.ObjSectionList.Count-1 do
  1017. begin
  1018. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1019. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1020. begin
  1021. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1022. case objrel.typ of
  1023. RELOC_FUNCTION_INDEX_LEB:
  1024. begin
  1025. if not assigned(objrel.symbol) then
  1026. internalerror(2021092509);
  1027. objsec.Data.seek(objrel.DataOffset);
  1028. if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
  1029. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1030. else
  1031. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
  1032. end;
  1033. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1034. begin
  1035. if not assigned(objrel.symbol) then
  1036. internalerror(2021092605);
  1037. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1038. begin
  1039. objsec.Data.seek(objrel.DataOffset);
  1040. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1041. end;
  1042. end;
  1043. RELOC_MEMORY_ADDR_LEB:
  1044. begin
  1045. if not assigned(objrel.symbol) then
  1046. internalerror(2021092606);
  1047. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1048. internalerror(2021092628);
  1049. if objrel.symbol.bind<>AB_EXTERNAL then
  1050. begin
  1051. objsec.Data.seek(objrel.DataOffset);
  1052. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1053. end;
  1054. end;
  1055. RELOC_ABSOLUTE:
  1056. begin
  1057. if assigned(objrel.ObjSection) then
  1058. begin
  1059. { todo: should we do something here? }
  1060. //Writeln('todo: section relocation');
  1061. end
  1062. else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1063. begin
  1064. objsec.Data.seek(objrel.DataOffset);
  1065. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1066. end;
  1067. end;
  1068. RELOC_TYPE_INDEX_LEB:
  1069. ;
  1070. RELOC_GLOBAL_INDEX_LEB:
  1071. begin
  1072. if not assigned(objrel.symbol) then
  1073. internalerror(2021092509);
  1074. objsec.Data.seek(objrel.DataOffset);
  1075. if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
  1076. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1077. else
  1078. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
  1079. end;
  1080. RELOC_TAG_INDEX_LEB:
  1081. begin
  1082. if not assigned(objrel.symbol) then
  1083. internalerror(2021092716);
  1084. objsec.Data.seek(objrel.DataOffset);
  1085. if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
  1086. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1087. else
  1088. WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
  1089. end;
  1090. else
  1091. internalerror(2021092510);
  1092. end;
  1093. end;
  1094. end;
  1095. end;
  1096. procedure TWasmObjOutput.WriteRelocations;
  1097. var
  1098. si, ri: Integer;
  1099. objsec: TWasmObjSection;
  1100. objrel: TWasmObjRelocation;
  1101. relout: tdynamicarray;
  1102. relcount: PInteger;
  1103. FuncSym: TWasmObjSymbol;
  1104. begin
  1105. for si:=0 to FData.ObjSectionList.Count-1 do
  1106. begin
  1107. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1108. if objsec.IsCode then
  1109. begin
  1110. relout:=FWasmRelocationCodeTable;
  1111. relcount:=@FWasmRelocationCodeTableEntriesCount;
  1112. end
  1113. else if objsec.IsData then
  1114. begin
  1115. relout:=FWasmRelocationDataTable;
  1116. relcount:=@FWasmRelocationDataTableEntriesCount;
  1117. end
  1118. else if objsec.IsDebug then
  1119. begin
  1120. case objsec.Name of
  1121. '.debug_frame':
  1122. begin
  1123. relout:=FWasmRelocationDebugFrameTable;
  1124. relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
  1125. end;
  1126. '.debug_info':
  1127. begin
  1128. relout:=FWasmRelocationDebugInfoTable;
  1129. relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
  1130. end;
  1131. '.debug_line':
  1132. begin
  1133. relout:=FWasmRelocationDebugLineTable;
  1134. relcount:=@FWasmRelocationDebugLineTableEntriesCount;
  1135. end;
  1136. '.debug_abbrev':
  1137. begin
  1138. relout:=FWasmRelocationDebugAbbrevTable;
  1139. relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
  1140. end;
  1141. '.debug_aranges':
  1142. begin
  1143. relout:=FWasmRelocationDebugArangesTable;
  1144. relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
  1145. end;
  1146. '.debug_ranges':
  1147. begin
  1148. relout:=FWasmRelocationDebugRangesTable;
  1149. relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
  1150. end;
  1151. '.debug_str':
  1152. begin
  1153. relout:=FWasmRelocationDebugStrTable;
  1154. relcount:=@FWasmRelocationDebugStrTableEntriesCount;
  1155. end;
  1156. else
  1157. internalerror(2022071601);
  1158. end;
  1159. end
  1160. else
  1161. continue;
  1162. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1163. begin
  1164. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1165. case objrel.typ of
  1166. RELOC_FUNCTION_INDEX_LEB:
  1167. begin
  1168. if not assigned(objrel.symbol) then
  1169. internalerror(2021092508);
  1170. Inc(relcount^);
  1171. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  1172. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1173. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1174. end;
  1175. RELOC_MEMORY_ADDR_LEB:
  1176. begin
  1177. if not assigned(objrel.symbol) then
  1178. internalerror(2021092603);
  1179. Inc(relcount^);
  1180. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1181. internalerror(2021092628);
  1182. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  1183. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1184. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1185. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1186. end;
  1187. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1188. begin
  1189. if not assigned(objrel.symbol) then
  1190. internalerror(2021092604);
  1191. Inc(relcount^);
  1192. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1193. begin
  1194. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  1195. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1196. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1197. end
  1198. else
  1199. begin
  1200. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  1201. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1202. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1203. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1204. end;
  1205. end;
  1206. RELOC_ABSOLUTE:
  1207. begin
  1208. // todo: figure this out, why do these exist?
  1209. //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
  1210. // Writeln('!!! ', objrel.symbol.name);
  1211. if assigned(objrel.objsection) then
  1212. begin
  1213. Inc(relcount^);
  1214. WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
  1215. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1216. if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
  1217. message1(asmw_e_illegal_unset_index,objrel.objsection.name)
  1218. else
  1219. WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
  1220. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1221. end
  1222. else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
  1223. begin
  1224. Inc(relcount^);
  1225. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  1226. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1227. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1228. end
  1229. else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
  1230. begin
  1231. Inc(relcount^);
  1232. WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
  1233. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1234. FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
  1235. if FuncSym.SymbolIndex<0 then
  1236. message1(asmw_e_illegal_unset_index,FuncSym.Name)
  1237. else
  1238. WriteUleb(relout,FuncSym.SymbolIndex);
  1239. WriteSleb(relout,objrel.Addend+objrel.symbol.address); { addend to add to the address }
  1240. end
  1241. else
  1242. begin
  1243. Inc(relcount^);
  1244. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1245. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1246. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1247. begin
  1248. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1249. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1250. end
  1251. else
  1252. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1253. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1254. end;
  1255. end;
  1256. RELOC_TYPE_INDEX_LEB:
  1257. begin
  1258. Inc(relcount^);
  1259. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1260. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1261. WriteUleb(relout,objrel.TypeIndex);
  1262. end;
  1263. RELOC_GLOBAL_INDEX_LEB:
  1264. begin
  1265. if not assigned(objrel.symbol) then
  1266. internalerror(2021092704);
  1267. Inc(relcount^);
  1268. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1269. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1270. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1271. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1272. else
  1273. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1274. end;
  1275. RELOC_TAG_INDEX_LEB:
  1276. begin
  1277. if not assigned(objrel.symbol) then
  1278. internalerror(2021092717);
  1279. Inc(relcount^);
  1280. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1281. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1282. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1283. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1284. else
  1285. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1286. end;
  1287. else
  1288. internalerror(2021092507);
  1289. end;
  1290. end;
  1291. end;
  1292. end;
  1293. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1294. begin
  1295. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1296. end;
  1297. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1298. var
  1299. section_nr: Integer;
  1300. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1301. var
  1302. objsec: TWasmObjSection;
  1303. begin
  1304. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1305. if Assigned(objsec) then
  1306. begin
  1307. debug_section_nr:=section_nr;
  1308. Inc(section_nr);
  1309. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1310. Inc(FWasmSymbolTableEntriesCount);
  1311. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1312. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1313. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1314. end;
  1315. end;
  1316. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1317. var
  1318. objsec: TWasmObjSection;
  1319. begin
  1320. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1321. if Assigned(objsec) then
  1322. begin
  1323. if oso_Data in objsec.SecOptions then
  1324. begin
  1325. objsec.Data.seek(0);
  1326. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1327. end
  1328. else
  1329. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1330. WriteWasmCustomSection(st);
  1331. end;
  1332. end;
  1333. var
  1334. i: Integer;
  1335. objsec: TWasmObjSection;
  1336. segment_count: Integer = 0;
  1337. cur_seg_ofs: qword = 0;
  1338. types_count,
  1339. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1340. code_section_nr, data_section_nr,
  1341. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1342. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1343. debug_ranges_section_nr,
  1344. NextGlobalIndex, NextTagIndex: Integer;
  1345. import_globals_count: Integer = 0;
  1346. globals_count: Integer = 0;
  1347. import_functions_count: Integer = 0;
  1348. export_functions_count: Integer = 0;
  1349. functions_count: Integer = 0;
  1350. import_exception_tags_count: Integer = 0;
  1351. exception_tags_count: Integer = 0;
  1352. objsym, ObjSymAlias: TWasmObjSymbol;
  1353. cust_sec: TWasmCustomSectionType;
  1354. SegmentFlags, SymbolFlags: UInt64;
  1355. begin
  1356. FData:=TWasmObjData(Data);
  1357. { each custom sections starts with its name }
  1358. for cust_sec in TWasmCustomSectionType do
  1359. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1360. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1361. for i:=0 to Data.ObjSymbolList.Count-1 do
  1362. begin
  1363. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1364. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1365. if objsym.bind=AB_EXTERNAL then
  1366. Inc(import_exception_tags_count)
  1367. else
  1368. Inc(exception_tags_count);
  1369. if objsym.typ=AT_WASM_GLOBAL then
  1370. if objsym.bind=AB_EXTERNAL then
  1371. Inc(import_globals_count)
  1372. else
  1373. Inc(globals_count);
  1374. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1375. Inc(import_globals_count);
  1376. if IsExternalFunction(objsym) then
  1377. Inc(import_functions_count);
  1378. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1379. begin
  1380. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1381. Inc(functions_count);
  1382. end;
  1383. if IsExportedFunction(objsym) then
  1384. Inc(export_functions_count);
  1385. end;
  1386. types_count:=Length(FData.FFuncTypes);
  1387. WriteUleb(FWasmSections[wsiType],types_count);
  1388. for i:=0 to types_count-1 do
  1389. with FData.FFuncTypes[i] do
  1390. begin
  1391. WriteByte(FWasmSections[wsiType],$60);
  1392. WriteWasmResultType(FWasmSections[wsiType],params);
  1393. WriteWasmResultType(FWasmSections[wsiType],results);
  1394. end;
  1395. for i:=0 to Data.ObjSectionList.Count-1 do
  1396. begin
  1397. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1398. if objsec.IsCode then
  1399. objsec.SegIdx:=-1
  1400. else if objsec.IsData then
  1401. begin
  1402. objsec.SegIdx:=segment_count;
  1403. objsec.SegOfs:=cur_seg_ofs;
  1404. Inc(segment_count);
  1405. Inc(cur_seg_ofs,objsec.Size);
  1406. end;
  1407. end;
  1408. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1409. WriteUleb(FWasmSections[wsiImport],imports_count);
  1410. { import memories }
  1411. WriteName(FWasmSections[wsiImport],'env');
  1412. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1413. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1414. WriteByte(FWasmSections[wsiImport],$00); { min }
  1415. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1416. { import globals }
  1417. NextGlobalIndex:=0;
  1418. for i:=0 to Data.ObjSymbolList.Count-1 do
  1419. begin
  1420. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1421. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1422. begin
  1423. objsym.GlobalIndex:=NextGlobalIndex;
  1424. Inc(NextGlobalIndex);
  1425. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1426. if objsym.ExtraData.ImportModule<>'' then
  1427. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1428. else
  1429. WriteName(FWasmSections[wsiImport],'env');
  1430. WriteName(FWasmSections[wsiImport],objsym.Name);
  1431. WriteByte(FWasmSections[wsiImport],$03); { global }
  1432. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1433. if objsym.ExtraData.GlobalIsImmutable then
  1434. WriteByte(FWasmSections[wsiImport],$00) { const }
  1435. else
  1436. WriteByte(FWasmSections[wsiImport],$01); { var }
  1437. end
  1438. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1439. begin
  1440. objsym.GlobalIndex:=NextGlobalIndex;
  1441. Inc(NextGlobalIndex);
  1442. objsym.ExtraData:=nil;
  1443. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1444. WriteName(FWasmSections[wsiImport],objsym.Name);
  1445. WriteByte(FWasmSections[wsiImport],$03); { global }
  1446. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1447. WriteByte(FWasmSections[wsiImport],$01); { var }
  1448. end;
  1449. end;
  1450. { import functions }
  1451. NextImportFunctionIndex:=0;
  1452. for i:=0 to Data.ObjSymbolList.Count-1 do
  1453. begin
  1454. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1455. if IsExternalFunction(objsym) then
  1456. begin
  1457. objsym.FuncIndex:=NextImportFunctionIndex;
  1458. Inc(NextImportFunctionIndex);
  1459. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1460. if objsym.ExtraData.ImportModule<>'' then
  1461. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1462. else
  1463. WriteName(FWasmSections[wsiImport],'env');
  1464. WriteName(FWasmSections[wsiImport],objsym.Name);
  1465. WriteByte(FWasmSections[wsiImport],$00); { func }
  1466. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1467. end;
  1468. end;
  1469. { import tables }
  1470. WriteName(FWasmSections[wsiImport],'env');
  1471. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1472. WriteByte(FWasmSections[wsiImport],$01); { table }
  1473. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1474. WriteByte(FWasmSections[wsiImport],$00); { min }
  1475. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1476. { import tags }
  1477. NextTagIndex:=0;
  1478. for i:=0 to Data.ObjSymbolList.Count-1 do
  1479. begin
  1480. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1481. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1482. begin
  1483. objsym.TagIndex:=NextTagIndex;
  1484. Inc(NextTagIndex);
  1485. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1486. if objsym.ExtraData.ImportModule<>'' then
  1487. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1488. else
  1489. WriteName(FWasmSections[wsiImport],'env');
  1490. WriteName(FWasmSections[wsiImport],objsym.Name);
  1491. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1492. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1493. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1494. end;
  1495. end;
  1496. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1497. NextFunctionIndex:=NextImportFunctionIndex;
  1498. for i:=0 to Data.ObjSymbolList.Count-1 do
  1499. begin
  1500. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1501. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1502. begin
  1503. objsym.FuncIndex:=NextFunctionIndex;
  1504. Inc(NextFunctionIndex);
  1505. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1506. end;
  1507. end;
  1508. if exception_tags_count>0 then
  1509. begin
  1510. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1511. for i:=0 to Data.ObjSymbolList.Count-1 do
  1512. begin
  1513. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1514. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1515. begin
  1516. objsym.TagIndex:=NextTagIndex;
  1517. Inc(NextTagIndex);
  1518. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1519. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1520. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1521. end;
  1522. end;
  1523. end;
  1524. if globals_count>0 then
  1525. begin
  1526. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1527. for i:=0 to Data.ObjSymbolList.Count-1 do
  1528. begin
  1529. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1530. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1531. begin
  1532. objsym.GlobalIndex:=NextGlobalIndex;
  1533. Inc(NextGlobalIndex);
  1534. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1535. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1536. if objsym.ExtraData.GlobalIsImmutable then
  1537. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1538. else
  1539. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1540. { init expr }
  1541. case objsym.ExtraData.GlobalType of
  1542. wbt_i32:
  1543. begin
  1544. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1545. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1546. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1547. end;
  1548. wbt_i64:
  1549. begin
  1550. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1551. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1552. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1553. end;
  1554. wbt_f32:
  1555. begin
  1556. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1557. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1558. WriteByte(FWasmSections[wsiGlobal],$00);
  1559. WriteByte(FWasmSections[wsiGlobal],$00);
  1560. WriteByte(FWasmSections[wsiGlobal],$00);
  1561. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1562. end;
  1563. wbt_f64:
  1564. begin
  1565. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1566. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1567. WriteByte(FWasmSections[wsiGlobal],$00);
  1568. WriteByte(FWasmSections[wsiGlobal],$00);
  1569. WriteByte(FWasmSections[wsiGlobal],$00);
  1570. WriteByte(FWasmSections[wsiGlobal],$00);
  1571. WriteByte(FWasmSections[wsiGlobal],$00);
  1572. WriteByte(FWasmSections[wsiGlobal],$00);
  1573. WriteByte(FWasmSections[wsiGlobal],$00);
  1574. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1575. end;
  1576. wbt_externref:
  1577. begin
  1578. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1579. WriteByte(FWasmSections[wsiGlobal],$6F);
  1580. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1581. end;
  1582. wbt_funcref:
  1583. begin
  1584. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1585. WriteByte(FWasmSections[wsiGlobal],$70);
  1586. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1587. end;
  1588. else
  1589. internalerror(2022052801);
  1590. end;
  1591. end;
  1592. end;
  1593. end;
  1594. if export_functions_count>0 then
  1595. begin
  1596. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1597. for i:=0 to Data.ObjSymbolList.Count-1 do
  1598. begin
  1599. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1600. if IsExportedFunction(objsym) then
  1601. begin
  1602. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1603. WriteByte(FWasmSections[wsiExport],0); { func }
  1604. if (objsym.FuncIndex<0) then
  1605. message1(asmw_e_illegal_unset_index,objsym.name)
  1606. else
  1607. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1608. end;
  1609. end;
  1610. end;
  1611. for i:=0 to Data.ObjSymbolList.Count-1 do
  1612. begin
  1613. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1614. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1615. begin
  1616. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1617. Inc(FWasmSymbolTableEntriesCount);
  1618. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1619. if objsym.bind=AB_GLOBAL then
  1620. WriteUleb(FWasmSymbolTable,0)
  1621. else if objsym.bind=AB_LOCAL then
  1622. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1623. else if objsym.bind=AB_EXTERNAL then
  1624. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1625. else if objsym.bind=AB_WEAK then
  1626. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  1627. else
  1628. internalerror(2021092715);
  1629. if (objsym.TagIndex<0) then
  1630. message1(asmw_e_illegal_unset_index,objsym.name)
  1631. else
  1632. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  1633. if objsym.bind<>AB_EXTERNAL then
  1634. WriteName(FWasmSymbolTable,objsym.Name);
  1635. end
  1636. else if objsym.typ=AT_WASM_GLOBAL then
  1637. begin
  1638. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1639. Inc(FWasmSymbolTableEntriesCount);
  1640. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  1641. if objsym.bind=AB_EXTERNAL then
  1642. begin
  1643. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1644. if (objsym.GlobalIndex<0) then
  1645. message1(asmw_e_illegal_unset_index,objsym.name)
  1646. else
  1647. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1648. end
  1649. else
  1650. begin
  1651. WriteUleb(FWasmSymbolTable,0);
  1652. if (objsym.GlobalIndex<0) then
  1653. message1(asmw_e_illegal_unset_index,objsym.name)
  1654. else
  1655. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1656. WriteName(FWasmSymbolTable,objsym.Name);
  1657. end;
  1658. end
  1659. else if IsExternalFunction(objsym) then
  1660. begin
  1661. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1662. Inc(FWasmSymbolTableEntriesCount);
  1663. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1664. if objsym.ExtraData.ImportModule<>'' then
  1665. begin
  1666. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1667. if (objsym.FuncIndex<0) then
  1668. message1(asmw_e_illegal_unset_index,objsym.name)
  1669. else
  1670. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1671. WriteName(FWasmSymbolTable,objsym.Name);
  1672. end
  1673. else
  1674. begin
  1675. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1676. if (objsym.FuncIndex<0) then
  1677. message1(asmw_e_illegal_unset_index,objsym.name)
  1678. else
  1679. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1680. end;
  1681. end
  1682. else if objsym.typ=AT_FUNCTION then
  1683. begin
  1684. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1685. Inc(FWasmSymbolTableEntriesCount);
  1686. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1687. if objsym.IsAlias then
  1688. begin
  1689. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1690. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1691. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1692. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1693. end
  1694. else
  1695. begin
  1696. if IsExportedFunction(objsym) then
  1697. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  1698. else
  1699. WriteUleb(FWasmSymbolTable,0);
  1700. if (objsym.FuncIndex<0) then
  1701. message1(asmw_e_illegal_unset_index,objsym.name)
  1702. else
  1703. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1704. end;
  1705. WriteName(FWasmSymbolTable,objsym.Name);
  1706. end
  1707. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1708. begin
  1709. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  1710. begin
  1711. {todo: debug symbols}
  1712. end
  1713. else
  1714. begin
  1715. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1716. Inc(FWasmSymbolTableEntriesCount);
  1717. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1718. if objsym.bind=AB_GLOBAL then
  1719. SymbolFlags:=0
  1720. else if objsym.bind=AB_LOCAL then
  1721. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  1722. else if objsym.bind=AB_EXTERNAL then
  1723. SymbolFlags:=WASM_SYM_UNDEFINED
  1724. else
  1725. internalerror(2021092506);
  1726. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1727. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  1728. WriteUleb(FWasmSymbolTable,SymbolFlags);
  1729. WriteName(FWasmSymbolTable,objsym.Name);
  1730. if objsym.bind<>AB_EXTERNAL then
  1731. begin
  1732. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1733. WriteUleb(FWasmSymbolTable,objsym.offset);
  1734. WriteUleb(FWasmSymbolTable,objsym.size);
  1735. end;
  1736. end;
  1737. end;
  1738. end;
  1739. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1740. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1741. if ts_wasm_threads in current_settings.targetswitches then
  1742. begin
  1743. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1744. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1745. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1746. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1747. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1748. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1749. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1750. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1751. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1752. end
  1753. else
  1754. begin
  1755. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  1756. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1757. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1758. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1759. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1760. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1761. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1762. end;
  1763. { Write the producers section:
  1764. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1765. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1766. WriteName(FWasmCustomSections[wcstProducers],'language');
  1767. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1768. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1769. WriteName(FWasmCustomSections[wcstProducers],'');
  1770. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1771. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1772. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1773. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1774. code_section_nr:=-1;
  1775. data_section_nr:=-1;
  1776. debug_abbrev_section_nr:=-1;
  1777. debug_info_section_nr:=-1;
  1778. debug_str_section_nr:=-1;
  1779. debug_line_section_nr:=-1;
  1780. debug_frame_section_nr:=-1;
  1781. debug_aranges_section_nr:=-1;
  1782. debug_ranges_section_nr:=-1;
  1783. section_nr:=0;
  1784. WriteWasmSection(wsiType);
  1785. Inc(section_nr);
  1786. WriteWasmSection(wsiImport);
  1787. Inc(section_nr);
  1788. WriteWasmSection(wsiFunction);
  1789. Inc(section_nr);
  1790. if exception_tags_count>0 then
  1791. begin
  1792. WriteWasmSection(wsiTag);
  1793. Inc(section_nr);
  1794. end;
  1795. if globals_count>0 then
  1796. begin
  1797. WriteWasmSection(wsiGlobal);
  1798. Inc(section_nr);
  1799. end;
  1800. if export_functions_count>0 then
  1801. begin
  1802. WriteWasmSection(wsiExport);
  1803. Inc(section_nr);
  1804. end;
  1805. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1806. if segment_count>0 then
  1807. Inc(section_nr); { the DataCount section }
  1808. code_section_nr:=section_nr; { the Code section }
  1809. Inc(section_nr);
  1810. if segment_count>0 then
  1811. begin
  1812. data_section_nr:=section_nr; { the Data section }
  1813. Inc(section_nr);
  1814. end;
  1815. { the debug sections }
  1816. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1817. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1818. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1819. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1820. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1821. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1822. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1823. DoRelocations;
  1824. if segment_count>0 then
  1825. begin
  1826. WriteUleb(FWasmSections[wsiData],segment_count);
  1827. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  1828. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  1829. for i:=0 to Data.ObjSectionList.Count-1 do
  1830. begin
  1831. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1832. if objsec.IsData then
  1833. begin
  1834. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  1835. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  1836. SegmentFlags:=0;
  1837. if (ts_wasm_threads in current_settings.targetswitches) and
  1838. (oso_threadvar in objsec.SecOptions) then
  1839. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  1840. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  1841. WriteByte(FWasmSections[wsiData],0);
  1842. WriteByte(FWasmSections[wsiData],$41);
  1843. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  1844. WriteByte(FWasmSections[wsiData],$0b);
  1845. WriteUleb(FWasmSections[wsiData],objsec.Size);
  1846. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  1847. if oso_Data in objsec.SecOptions then
  1848. begin
  1849. objsec.Data.seek(0);
  1850. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  1851. end
  1852. else
  1853. begin
  1854. WriteZeros(FWasmSections[wsiData],objsec.Size);
  1855. end;
  1856. end;
  1857. end;
  1858. end;
  1859. WriteUleb(FWasmSections[wsiCode],functions_count);
  1860. for i:=0 to Data.ObjSymbolList.Count-1 do
  1861. begin
  1862. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1863. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1864. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  1865. end;
  1866. if segment_count>0 then
  1867. WriteWasmSection(wsiDataCount);
  1868. WriteWasmSection(wsiCode);
  1869. if segment_count>0 then
  1870. WriteWasmSection(wsiData);
  1871. MaybeWriteDebugSection(wcstDebugAbbrev);
  1872. MaybeWriteDebugSection(wcstDebugInfo);
  1873. MaybeWriteDebugSection(wcstDebugStr);
  1874. MaybeWriteDebugSection(wcstDebugLine);
  1875. MaybeWriteDebugSection(wcstDebugFrame);
  1876. MaybeWriteDebugSection(wcstDebugAranges);
  1877. MaybeWriteDebugSection(wcstDebugRanges);
  1878. WriteRelocations;
  1879. WriteSymbolTable;
  1880. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  1881. if segment_count>0 then
  1882. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  1883. WriteRelocationCodeTable(code_section_nr);
  1884. if segment_count>0 then
  1885. WriteRelocationDataTable(data_section_nr);
  1886. WriteWasmCustomSection(wcstLinking);
  1887. Inc(section_nr);
  1888. WriteWasmCustomSection(wcstRelocCode);
  1889. Inc(section_nr);
  1890. if segment_count>0 then
  1891. begin
  1892. WriteWasmCustomSection(wcstRelocData);
  1893. Inc(section_nr);
  1894. end;
  1895. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  1896. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  1897. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  1898. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  1899. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  1900. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  1901. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  1902. WriteWasmCustomSection(wcstProducers);
  1903. Inc(section_nr);
  1904. WriteWasmCustomSection(wcstTargetFeatures);
  1905. Inc(section_nr);
  1906. result:=true;
  1907. end;
  1908. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  1909. var
  1910. i: TWasmSectionID;
  1911. j: TWasmCustomSectionType;
  1912. k: TWasmLinkingSubsectionType;
  1913. begin
  1914. inherited;
  1915. cobjdata:=TWasmObjData;
  1916. for i in TWasmSectionID do
  1917. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  1918. for j in TWasmCustomSectionType do
  1919. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  1920. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1921. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  1922. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  1923. FWasmSymbolTableEntriesCount:=0;
  1924. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  1925. FWasmRelocationCodeTableEntriesCount:=0;
  1926. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  1927. FWasmRelocationDataTableEntriesCount:=0;
  1928. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  1929. FWasmRelocationDebugFrameTableEntriesCount:=0;
  1930. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  1931. FWasmRelocationDebugInfoTableEntriesCount:=0;
  1932. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  1933. FWasmRelocationDebugLineTableEntriesCount:=0;
  1934. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  1935. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  1936. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  1937. FWasmRelocationDebugArangesTableEntriesCount:=0;
  1938. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  1939. FWasmRelocationDebugRangesTableEntriesCount:=0;
  1940. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  1941. FWasmRelocationDebugStrTableEntriesCount:=0;
  1942. end;
  1943. destructor TWasmObjOutput.destroy;
  1944. var
  1945. i: TWasmSectionID;
  1946. j: TWasmCustomSectionType;
  1947. k: TWasmLinkingSubsectionType;
  1948. begin
  1949. for i in TWasmSectionID do
  1950. FWasmSections[i].Free;
  1951. for j in TWasmCustomSectionType do
  1952. FWasmCustomSections[j].Free;
  1953. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1954. FWasmLinkingSubsections[k].Free;
  1955. FWasmSymbolTable.Free;
  1956. FWasmRelocationCodeTable.Free;
  1957. FWasmRelocationDataTable.Free;
  1958. FWasmRelocationDebugFrameTable.Free;
  1959. FWasmRelocationDebugInfoTable.Free;
  1960. FWasmRelocationDebugLineTable.Free;
  1961. FWasmRelocationDebugAbbrevTable.Free;
  1962. FWasmRelocationDebugArangesTable.Free;
  1963. FWasmRelocationDebugRangesTable.Free;
  1964. FWasmRelocationDebugStrTable.Free;
  1965. inherited destroy;
  1966. end;
  1967. {****************************************************************************
  1968. TWasmObjInput
  1969. ****************************************************************************}
  1970. function TWasmObjInput.ReadUleb(r: TObjectReader; out v: uint64): boolean;
  1971. var
  1972. b: byte;
  1973. shift:integer;
  1974. begin
  1975. result:=false;
  1976. b:=0;
  1977. v:=0;
  1978. shift:=0;
  1979. repeat
  1980. if not r.read(b,1) then
  1981. exit;
  1982. v:=v or (uint64(b and 127) shl shift);
  1983. inc(shift,7);
  1984. until (b and 128)=0;
  1985. result:=true;
  1986. end;
  1987. function TWasmObjInput.ReadName(r: TObjectReader; out v: ansistring): boolean;
  1988. var
  1989. len: uint64;
  1990. begin
  1991. result:=false;
  1992. if not ReadUleb(r,len) then
  1993. exit;
  1994. if len>high(uint32) then
  1995. exit;
  1996. SetLength(v,len);
  1997. if len>0 then
  1998. result:=r.read(v[1],len)
  1999. else
  2000. result:=true;
  2001. end;
  2002. constructor TWasmObjInput.create;
  2003. begin
  2004. inherited create;
  2005. cobjdata:=TWasmObjData;
  2006. end;
  2007. destructor TWasmObjInput.Destroy;
  2008. var
  2009. i: Integer;
  2010. begin
  2011. for i:=low(FFuncTypes) to high(FFuncTypes) do
  2012. begin
  2013. FFuncTypes[i].free;
  2014. FFuncTypes[i]:=nil;
  2015. end;
  2016. inherited Destroy;
  2017. end;
  2018. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  2019. var
  2020. ModuleMagic: array [0..3] of Byte;
  2021. ModuleVersion: array [0..3] of Byte;
  2022. i: Integer;
  2023. begin
  2024. Writeln('CanReadObjData');
  2025. result:=false;
  2026. if not AReader.read(ModuleMagic,4) then
  2027. exit;
  2028. for i:=0 to 3 do
  2029. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2030. exit;
  2031. if not AReader.read(ModuleVersion,4) then
  2032. exit;
  2033. for i:=0 to 3 do
  2034. if ModuleVersion[i]<>WasmVersion[i] then
  2035. exit;
  2036. result:=true;
  2037. end;
  2038. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2039. function ReadSection: Boolean;
  2040. var
  2041. SectionId: Byte;
  2042. SectionSize: uint64;
  2043. SectionStart: LongInt;
  2044. TypeSectionRead: Boolean = false;
  2045. ImportSectionRead: Boolean = false;
  2046. FunctionSectionRead: Boolean = false;
  2047. DataCountSectionRead: Boolean = false;
  2048. DataCount: uint32;
  2049. function ReadCustomSection: Boolean;
  2050. begin
  2051. Result:=False;
  2052. end;
  2053. function ReadTypeSection: Boolean;
  2054. var
  2055. FuncTypesCount, ParamsCount, ResultsCount: uint64;
  2056. FuncTypeId, WasmTypeId: Byte;
  2057. i, j: Integer;
  2058. wbt: TWasmBasicType;
  2059. begin
  2060. Result:=False;
  2061. if TypeSectionRead then
  2062. begin
  2063. InputError('Type section is duplicated');
  2064. exit;
  2065. end;
  2066. TypeSectionRead:=True;
  2067. if not ReadUleb(AReader, FuncTypesCount) then
  2068. begin
  2069. InputError('Error reading the func types count');
  2070. exit;
  2071. end;
  2072. if AReader.Pos>(SectionStart+SectionSize) then
  2073. begin
  2074. InputError('The func types count stretches beyond the end of the type section');
  2075. exit;
  2076. end;
  2077. if FuncTypesCount>high(uint32) then
  2078. begin
  2079. InputError('The func types count does not fit in an unsigned 32-bit int');
  2080. exit;
  2081. end;
  2082. SetLength(FFuncTypes,FuncTypesCount);
  2083. for i:=0 to FuncTypesCount - 1 do
  2084. begin
  2085. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2086. if not AReader.read(FuncTypeId,1) then
  2087. begin
  2088. InputError('Error reading the function type identifier');
  2089. exit;
  2090. end;
  2091. if FuncTypeId<>$60 then
  2092. begin
  2093. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2094. exit;
  2095. end;
  2096. if not ReadUleb(AReader, ParamsCount) then
  2097. begin
  2098. InputError('Error reading the function parameters count');
  2099. exit;
  2100. end;
  2101. if AReader.Pos>(SectionStart+SectionSize) then
  2102. begin
  2103. InputError('The function paramaters count stretches beyond the end of the type section');
  2104. exit;
  2105. end;
  2106. if ParamsCount>high(uint32) then
  2107. begin
  2108. InputError('The function parameters count does not fit in an unsigned 32-bit int');
  2109. exit;
  2110. end;
  2111. for j:=0 to ParamsCount-1 do
  2112. begin
  2113. if not AReader.read(WasmTypeId,1) then
  2114. begin
  2115. InputError('Error reading a function parameter basic type');
  2116. exit;
  2117. end;
  2118. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2119. begin
  2120. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2121. exit;
  2122. end;
  2123. FFuncTypes[i].add_param(wbt);
  2124. end;
  2125. if not ReadUleb(AReader, ResultsCount) then
  2126. begin
  2127. InputError('Error reading the function results count');
  2128. exit;
  2129. end;
  2130. if AReader.Pos>(SectionStart+SectionSize) then
  2131. begin
  2132. InputError('The function results count stretches beyond the end of the type section');
  2133. exit;
  2134. end;
  2135. if ResultsCount>high(uint32) then
  2136. begin
  2137. InputError('The function results count does not fit in an unsigned 32-bit int');
  2138. exit;
  2139. end;
  2140. for j:=0 to ResultsCount-1 do
  2141. begin
  2142. if not AReader.read(WasmTypeId,1) then
  2143. begin
  2144. InputError('Error reading a function result basic type');
  2145. exit;
  2146. end;
  2147. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2148. begin
  2149. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2150. exit;
  2151. end;
  2152. FFuncTypes[i].add_result(wbt);
  2153. end;
  2154. end;
  2155. if AReader.Pos<>(SectionStart+SectionSize) then
  2156. begin
  2157. InputError('Unexpected type section size');
  2158. exit;
  2159. end;
  2160. Result:=true;
  2161. end;
  2162. function ReadImportSection: Boolean;
  2163. var
  2164. ImportsCount, typidx, TableLimitsMin, TableLimitsMax,
  2165. MemoryLimitsMin, MemoryLimitsMax: uint64;
  2166. i: Integer;
  2167. ModName, Name: ansistring;
  2168. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2169. GlobalType, GlobalMutabilityType: Byte;
  2170. TableElemWBT, GlobalTypeWBT: TWasmBasicType;
  2171. begin
  2172. Result:=False;
  2173. if ImportSectionRead then
  2174. begin
  2175. InputError('Import section is duplicated');
  2176. exit;
  2177. end;
  2178. ImportSectionRead:=True;
  2179. if not ReadUleb(AReader,ImportsCount) then
  2180. begin
  2181. InputError('Error reading the imports count');
  2182. exit;
  2183. end;
  2184. if AReader.Pos>(SectionStart+SectionSize) then
  2185. begin
  2186. InputError('The imports count stretches beyond the end of the import section');
  2187. exit;
  2188. end;
  2189. if ImportsCount>high(uint32) then
  2190. begin
  2191. InputError('The imports count does not fit in an unsigned 32-bit int');
  2192. exit;
  2193. end;
  2194. for i:=0 to ImportsCount-1 do
  2195. begin
  2196. if not ReadName(AReader,ModName) then
  2197. begin
  2198. InputError('Error reading import module name');
  2199. exit;
  2200. end;
  2201. if not ReadName(AReader,Name) then
  2202. begin
  2203. InputError('Error import name');
  2204. exit;
  2205. end;
  2206. if not AReader.Read(ImportType,1) then
  2207. begin
  2208. InputError('Error reading import type');
  2209. exit;
  2210. end;
  2211. case ImportType of
  2212. $00: { func }
  2213. begin
  2214. if not ReadUleb(AReader,typidx) then
  2215. begin
  2216. InputError('Error reading type index for func import');
  2217. exit;
  2218. end;
  2219. if typidx>high(FFuncTypes) then
  2220. begin
  2221. InputError('Type index in func import exceeds bounds of the types table');
  2222. exit;
  2223. end;
  2224. end;
  2225. $01: { table }
  2226. begin
  2227. if not AReader.read(TableElemTyp,1) then
  2228. begin
  2229. InputError('Error reading table element type for table import');
  2230. exit;
  2231. end;
  2232. if not decode_wasm_basic_type(TableElemTyp,TableElemWBT) then
  2233. begin
  2234. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2235. exit;
  2236. end;
  2237. if not (TableElemWBT in WasmReferenceTypes) then
  2238. begin
  2239. InputError('Table element type for table import must be a reference type');
  2240. exit;
  2241. end;
  2242. if not AReader.read(TableLimitsKind,1) then
  2243. begin
  2244. InputError('Error reading table limits kind for table import');
  2245. exit;
  2246. end;
  2247. case TableLimitsKind of
  2248. $00:
  2249. begin
  2250. if not ReadUleb(AReader,TableLimitsMin) then
  2251. begin
  2252. InputError('Error reading table limits min for table import');
  2253. exit;
  2254. end;
  2255. if TableLimitsMin>high(uint32) then
  2256. begin
  2257. InputError('Table limits min does not fit in an unsigned 32-bit int');
  2258. exit;
  2259. end;
  2260. end;
  2261. $01:
  2262. begin
  2263. if not ReadUleb(AReader,TableLimitsMin) then
  2264. begin
  2265. InputError('Error reading table limits min for table import');
  2266. exit;
  2267. end;
  2268. if TableLimitsMin>high(uint32) then
  2269. begin
  2270. InputError('Table limits min does not fit in an unsigned 32-bit int');
  2271. exit;
  2272. end;
  2273. if not ReadUleb(AReader,TableLimitsMax) then
  2274. begin
  2275. InputError('Error reading table limits max for table import');
  2276. exit;
  2277. end;
  2278. if TableLimitsMax>high(uint32) then
  2279. begin
  2280. InputError('Table limits max does not fit in an unsigned 32-bit int');
  2281. exit;
  2282. end;
  2283. if TableLimitsMin>TableLimitsMax then
  2284. begin
  2285. InputError('Table limits min exceed table limits max in table import');
  2286. exit;
  2287. end;
  2288. end;
  2289. else
  2290. begin
  2291. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2292. exit;
  2293. end;
  2294. end;
  2295. end;
  2296. $02: { mem }
  2297. begin
  2298. if not AReader.read(MemoryLimitsKind,1) then
  2299. begin
  2300. InputError('Error reading memory limits kind for memory import');
  2301. exit;
  2302. end;
  2303. case MemoryLimitsKind of
  2304. $00:
  2305. begin
  2306. if not ReadUleb(AReader,MemoryLimitsMin) then
  2307. begin
  2308. InputError('Error reading memory limits min for memory import');
  2309. exit;
  2310. end;
  2311. if MemoryLimitsMin>high(uint32) then
  2312. begin
  2313. InputError('Memory limits min does not fit in an unsigned 32-bit int');
  2314. exit;
  2315. end;
  2316. end;
  2317. $01:
  2318. begin
  2319. if not ReadUleb(AReader,MemoryLimitsMin) then
  2320. begin
  2321. InputError('Error reading memory limits min for memory import');
  2322. exit;
  2323. end;
  2324. if MemoryLimitsMin>high(uint32) then
  2325. begin
  2326. InputError('Memory limits min does not fit in an unsigned 32-bit int');
  2327. exit;
  2328. end;
  2329. if not ReadUleb(AReader,MemoryLimitsMax) then
  2330. begin
  2331. InputError('Error reading memory limits max for memory import');
  2332. exit;
  2333. end;
  2334. if MemoryLimitsMax>high(uint32) then
  2335. begin
  2336. InputError('Memory limits max does not fit in an unsigned 32-bit int');
  2337. exit;
  2338. end;
  2339. if MemoryLimitsMin>MemoryLimitsMax then
  2340. begin
  2341. InputError('Memory limits min exceed memory limits max in memory import');
  2342. exit;
  2343. end;
  2344. end;
  2345. else
  2346. begin
  2347. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2348. exit;
  2349. end;
  2350. end;
  2351. end;
  2352. $03: { global }
  2353. begin
  2354. if not AReader.read(GlobalType,1) then
  2355. begin
  2356. InputError('Error reading global type for global import');
  2357. exit;
  2358. end;
  2359. if not decode_wasm_basic_type(GlobalType,GlobalTypeWBT) then
  2360. begin
  2361. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  2362. exit;
  2363. end;
  2364. if not AReader.read(GlobalMutabilityType,1) then
  2365. begin
  2366. InputError('Error reading global mutability flag for global import');
  2367. exit;
  2368. end;
  2369. case GlobalMutabilityType of
  2370. $00:
  2371. {const};
  2372. $01:
  2373. {var};
  2374. else
  2375. begin
  2376. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  2377. exit;
  2378. end;
  2379. end;
  2380. end;
  2381. else
  2382. begin
  2383. InputError('Unknown import type: $' + HexStr(ImportType,2));
  2384. exit;
  2385. end;
  2386. end;
  2387. end;
  2388. if AReader.Pos<>(SectionStart+SectionSize) then
  2389. begin
  2390. InputError('Unexpected import section size');
  2391. exit;
  2392. end;
  2393. Result:=true;
  2394. end;
  2395. function ReadFunctionSection: Boolean;
  2396. var
  2397. FunctionsCount, typidx: uint64;
  2398. i: Integer;
  2399. begin
  2400. Result:=False;
  2401. if FunctionSectionRead then
  2402. begin
  2403. InputError('Function section is duplicated');
  2404. exit;
  2405. end;
  2406. FunctionSectionRead:=True;
  2407. if not ReadUleb(AReader,FunctionsCount) then
  2408. begin
  2409. InputError('Error reading the functions count');
  2410. exit;
  2411. end;
  2412. if AReader.Pos>(SectionStart+SectionSize) then
  2413. begin
  2414. InputError('The functions count stretches beyond the end of the function section');
  2415. exit;
  2416. end;
  2417. if FunctionsCount>high(uint32) then
  2418. begin
  2419. InputError('The functions count does not fit in an unsigned 32-bit int');
  2420. exit;
  2421. end;
  2422. for i:=0 to FunctionsCount-1 do
  2423. begin
  2424. if not ReadUleb(AReader,typidx) then
  2425. begin
  2426. InputError('Error reading type index for function');
  2427. exit;
  2428. end;
  2429. if typidx>high(FFuncTypes) then
  2430. begin
  2431. InputError('Type index in the function section exceeds bounds of the types table');
  2432. exit;
  2433. end;
  2434. end;
  2435. if AReader.Pos<>(SectionStart+SectionSize) then
  2436. begin
  2437. InputError('Unexpected function section size');
  2438. exit;
  2439. end;
  2440. Result:=true;
  2441. end;
  2442. function ReadGlobalSection: Boolean;
  2443. begin
  2444. Result:=False;
  2445. end;
  2446. function ReadExportSection: Boolean;
  2447. begin
  2448. Result:=False;
  2449. end;
  2450. function ReadCodeSection: Boolean;
  2451. begin
  2452. Result:=False;
  2453. end;
  2454. function ReadDataSection: Boolean;
  2455. begin
  2456. Result:=False;
  2457. end;
  2458. function ReadDataCountSection: Boolean;
  2459. var
  2460. v: uint64;
  2461. begin
  2462. Result:=False;
  2463. if DataCountSectionRead then
  2464. begin
  2465. InputError('Data count section is duplicated');
  2466. exit;
  2467. end;
  2468. DataCountSectionRead:=True;
  2469. if not ReadUleb(AReader,v) then
  2470. begin
  2471. InputError('Error reading the data count from the data count section');
  2472. exit;
  2473. end;
  2474. if v>high(uint32) then
  2475. begin
  2476. InputError('Data count does not fit in an unsigned 32-bit int');
  2477. exit;
  2478. end;
  2479. DataCount:=v;
  2480. if AReader.Pos<>(SectionStart+SectionSize) then
  2481. begin
  2482. InputError('Unexpected data count section size');
  2483. exit;
  2484. end;
  2485. Result:=true;
  2486. end;
  2487. begin
  2488. Result:=False;
  2489. if not AReader.read(SectionId,1) then
  2490. begin
  2491. InputError('Error reading section ID');
  2492. exit;
  2493. end;
  2494. if not ReadUleb(AReader,SectionSize) then
  2495. begin
  2496. InputError('Error reading section size');
  2497. exit;
  2498. end;
  2499. if SectionSize>high(uint32) then
  2500. begin
  2501. InputError('Invalid section size');
  2502. exit;
  2503. end;
  2504. if (AReader.Pos+SectionSize)>AReader.size then
  2505. begin
  2506. InputError('Section exceeds beyond the end of file');
  2507. exit;
  2508. end;
  2509. SectionStart:=AReader.Pos;
  2510. case SectionId of
  2511. Byte(wsiCustom):
  2512. Result := ReadCustomSection;
  2513. Byte(wsiType):
  2514. if not ReadTypeSection then
  2515. begin
  2516. InputError('Error reading the type section');
  2517. exit;
  2518. end;
  2519. Byte(wsiImport):
  2520. if not ReadImportSection then
  2521. begin
  2522. InputError('Error reading the import section');
  2523. exit;
  2524. end;
  2525. Byte(wsiFunction):
  2526. if not ReadFunctionSection then
  2527. begin
  2528. InputError('Error reading the function section');
  2529. exit;
  2530. end;
  2531. Byte(wsiGlobal):
  2532. Result := ReadGlobalSection;
  2533. Byte(wsiExport):
  2534. Result := ReadExportSection;
  2535. Byte(wsiCode):
  2536. Result := ReadCodeSection;
  2537. Byte(wsiData):
  2538. Result := ReadDataSection;
  2539. Byte(wsiDataCount):
  2540. begin
  2541. if not ReadDataCountSection then
  2542. begin
  2543. InputError('Error reading the data count section');
  2544. exit;
  2545. end;
  2546. end
  2547. else
  2548. begin
  2549. InputError('Unknown section: ' + ToStr(SectionId));
  2550. exit;
  2551. end;
  2552. end;
  2553. if SectionSize>0 then
  2554. AReader.seek(SectionStart+SectionSize);
  2555. Result:=True;
  2556. end;
  2557. var
  2558. ModuleMagic: array [0..3] of Byte;
  2559. ModuleVersion: array [0..3] of Byte;
  2560. i: Integer;
  2561. begin
  2562. objdata:=CObjData.Create(InputFileName);
  2563. result:=false;
  2564. if not AReader.read(ModuleMagic,4) then
  2565. exit;
  2566. for i:=0 to 3 do
  2567. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2568. exit;
  2569. if not AReader.read(ModuleVersion,4) then
  2570. exit;
  2571. for i:=0 to 3 do
  2572. if ModuleVersion[i]<>WasmVersion[i] then
  2573. exit;
  2574. while AReader.Pos<AReader.size do
  2575. if not ReadSection then
  2576. exit;
  2577. Result:=True;
  2578. end;
  2579. {****************************************************************************
  2580. TWasmExeOutput
  2581. ****************************************************************************}
  2582. function TWasmExeOutput.writeData: boolean;
  2583. begin
  2584. result:=false;
  2585. {TODO: implement}
  2586. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  2587. Writer.write(WasmVersion,SizeOf(WasmVersion));
  2588. result := true;
  2589. end;
  2590. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  2591. begin
  2592. {TODO: implement}
  2593. end;
  2594. constructor TWasmExeOutput.create;
  2595. begin
  2596. inherited create;
  2597. CObjData:=TWasmObjData;
  2598. end;
  2599. {****************************************************************************
  2600. TWasmAssembler
  2601. ****************************************************************************}
  2602. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  2603. begin
  2604. inherited;
  2605. CObjOutput:=TWasmObjOutput;
  2606. end;
  2607. {*****************************************************************************
  2608. Initialize
  2609. *****************************************************************************}
  2610. {$ifdef wasm32}
  2611. const
  2612. as_wasm32_wasm_info : tasminfo =
  2613. (
  2614. id : as_wasm32_wasm;
  2615. idtxt : 'WASM';
  2616. asmbin : '';
  2617. asmcmd : '';
  2618. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  2619. flags : [af_outputbinary,af_smartlink_sections];
  2620. labelprefix : '..@';
  2621. labelmaxlen : -1;
  2622. comment : '; ';
  2623. dollarsign: '$';
  2624. );
  2625. {$endif wasm32}
  2626. initialization
  2627. {$ifdef wasm32}
  2628. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  2629. {$endif wasm32}
  2630. end.