ogwasm.pas 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  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. ImportIndex: Integer;
  37. FuncIndex: Integer;
  38. SymbolIndex: Integer;
  39. AliasOf: string;
  40. ExtraData: TWasmObjSymbolExtraData;
  41. constructor create(AList:TFPHashObjectList;const AName:string);override;
  42. function ImportOrFuncIndex: Integer;
  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. ImportModule: string;
  56. ImportName: string;
  57. ExportName: string;
  58. Locals: array of TWasmBasicType;
  59. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  60. procedure AddLocal(bastyp: TWasmBasicType);
  61. end;
  62. { TWasmObjSection }
  63. TWasmObjSection = class(TObjSection)
  64. public
  65. SegIdx: Integer;
  66. SegOfs: qword;
  67. FileSectionOfs: qword;
  68. function IsCode: Boolean;
  69. function IsData: Boolean;
  70. end;
  71. { TWasmObjData }
  72. TWasmObjData = class(TObjData)
  73. private
  74. FFuncTypes: array of TWasmFuncType;
  75. FObjSymbolsExtraDataList: TFPHashObjectList;
  76. FLastFuncName: string;
  77. function is_smart_section(atype:TAsmSectiontype):boolean;
  78. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  79. public
  80. constructor create(const n:string);override;
  81. destructor destroy; override;
  82. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  83. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  84. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  85. function AddFuncType(wft: TWasmFuncType): integer;
  86. procedure DeclareFuncType(ft: tai_functype);
  87. procedure DeclareExportName(en: tai_export_name);
  88. procedure DeclareImportModule(aim: tai_import_module);
  89. procedure DeclareImportName(ain: tai_import_name);
  90. procedure DeclareLocal(al: tai_local);
  91. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  92. end;
  93. { TWasmObjOutput }
  94. TWasmObjOutput = class(tObjOutput)
  95. private
  96. FData: TWasmObjData;
  97. FWasmRelocationCodeTable: tdynamicarray;
  98. FWasmRelocationCodeTableEntriesCount: Integer;
  99. FWasmRelocationDataTable: tdynamicarray;
  100. FWasmRelocationDataTableEntriesCount: Integer;
  101. FWasmSymbolTable: tdynamicarray;
  102. FWasmSymbolTableEntriesCount: Integer;
  103. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  104. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  105. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  106. procedure WriteUleb(d: tdynamicarray; v: uint64);
  107. procedure WriteUleb(w: TObjectWriter; v: uint64);
  108. procedure WriteSleb(d: tdynamicarray; v: int64);
  109. procedure WriteByte(d: tdynamicarray; b: byte);
  110. procedure WriteName(d: tdynamicarray; const s: string);
  111. procedure WriteWasmSection(wsid: TWasmSectionID);
  112. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  113. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  114. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  115. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  116. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  117. function IsExternalFunction(sym: TObjSymbol): Boolean;
  118. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  119. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  120. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  121. procedure WriteSymbolTable;
  122. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  123. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  124. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  125. procedure DoRelocations;
  126. procedure WriteRelocations;
  127. protected
  128. function writeData(Data:TObjData):boolean;override;
  129. public
  130. constructor create(AWriter:TObjectWriter);override;
  131. destructor destroy;override;
  132. end;
  133. { TWasmAssembler }
  134. TWasmAssembler = class(tinternalassembler)
  135. constructor create(info: pasminfo; smart:boolean);override;
  136. end;
  137. implementation
  138. uses
  139. verbose;
  140. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  141. var
  142. b: byte;
  143. i: Integer;
  144. begin
  145. for i:=1 to 5 do
  146. begin
  147. b:=byte(v) and 127;
  148. v:=v shr 7;
  149. if i<>5 then
  150. b:=b or 128;
  151. d.write(b,1);
  152. end;
  153. end;
  154. procedure WriteUleb5(d: tobjsection; v: uint64);
  155. var
  156. b: byte;
  157. i: Integer;
  158. begin
  159. for i:=1 to 5 do
  160. begin
  161. b:=byte(v) and 127;
  162. v:=v shr 7;
  163. if i<>5 then
  164. b:=b or 128;
  165. d.write(b,1);
  166. end;
  167. end;
  168. procedure WriteSleb5(d: tdynamicarray; v: int64);
  169. var
  170. b: byte;
  171. i: Integer;
  172. begin
  173. for i:=1 to 5 do
  174. begin
  175. b:=byte(v) and 127;
  176. v:=SarInt64(v,7);
  177. if i<>5 then
  178. b:=b or 128;
  179. d.write(b,1);
  180. end;
  181. end;
  182. procedure WriteSleb5(d: tobjsection; v: int64);
  183. var
  184. b: byte;
  185. i: Integer;
  186. begin
  187. for i:=1 to 5 do
  188. begin
  189. b:=byte(v) and 127;
  190. v:=SarInt64(v,7);
  191. if i<>5 then
  192. b:=b or 128;
  193. d.write(b,1);
  194. end;
  195. end;
  196. function ReadUleb(d: tdynamicarray): uint64;
  197. var
  198. b: byte;
  199. shift:integer;
  200. begin
  201. b:=0;
  202. result:=0;
  203. shift:=0;
  204. repeat
  205. d.read(b,1);
  206. result:=result or (uint64(b and 127) shl shift);
  207. inc(shift,7);
  208. until (b and 128)=0;
  209. end;
  210. function ReadSleb(d: tdynamicarray): int64;
  211. var
  212. b: byte;
  213. shift:integer;
  214. begin
  215. b:=0;
  216. result:=0;
  217. shift:=0;
  218. repeat
  219. d.read(b,1);
  220. result:=result or (uint64(b and 127) shl shift);
  221. inc(shift,7);
  222. until (b and 128)=0;
  223. if (b and 64)<>0 then
  224. result:=result or (high(uint64) shl shift);
  225. end;
  226. procedure AddSleb5(d: tdynamicarray; v: int64);
  227. var
  228. q: Int64;
  229. p: LongWord;
  230. begin
  231. p:=d.Pos;
  232. q:=ReadSleb(d);
  233. q:=q+v;
  234. d.seek(p);
  235. WriteSleb5(d,q);
  236. end;
  237. procedure AddUleb5(d: tdynamicarray; v: int64);
  238. var
  239. q: UInt64;
  240. p: LongWord;
  241. begin
  242. p:=d.Pos;
  243. q:=ReadUleb(d);
  244. q:=q+v;
  245. d.seek(p);
  246. WriteUleb5(d,q);
  247. end;
  248. procedure AddInt32(d: tdynamicarray; v: int32);
  249. var
  250. q: int32;
  251. p: LongWord;
  252. begin
  253. p:=d.Pos;
  254. d.read(q,4);
  255. {$ifdef FPC_BIG_ENDIAN}
  256. q:=SwapEndian(q);
  257. {$endif FPC_BIG_ENDIAN}
  258. q:=q+v;
  259. {$ifdef FPC_BIG_ENDIAN}
  260. q:=SwapEndian(q);
  261. {$endif FPC_BIG_ENDIAN}
  262. d.seek(p);
  263. d.write(q,4);
  264. end;
  265. {****************************************************************************
  266. TWasmObjRelocation
  267. ****************************************************************************}
  268. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  269. begin
  270. DataOffset:=ADataOffset;
  271. Symbol:=nil;
  272. OrgSize:=0;
  273. Group:=nil;
  274. ObjSection:=nil;
  275. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  276. TypeIndex:=ATypeIndex;
  277. end;
  278. {****************************************************************************
  279. TWasmObjSymbol
  280. ****************************************************************************}
  281. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  282. begin
  283. inherited create(AList,AName);
  284. ImportIndex:=-1;
  285. FuncIndex:=-1;
  286. SymbolIndex:=-1;
  287. AliasOf:='';
  288. ExtraData:=nil;
  289. end;
  290. function TWasmObjSymbol.ImportOrFuncIndex: Integer;
  291. begin
  292. if ImportIndex<>-1 then
  293. result:=ImportIndex
  294. else if FuncIndex<>-1 then
  295. result:=FuncIndex
  296. else
  297. internalerror(2021092601);
  298. end;
  299. function TWasmObjSymbol.IsAlias: Boolean;
  300. begin
  301. result:=AliasOf<>'';
  302. end;
  303. {****************************************************************************
  304. TWasmObjSymbolExtraData
  305. ****************************************************************************}
  306. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  307. begin
  308. inherited Create(HashObjectList,s);
  309. TypeIdx:=-1;
  310. end;
  311. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  312. begin
  313. SetLength(Locals,Length(Locals)+1);
  314. Locals[High(Locals)]:=bastyp;
  315. end;
  316. {****************************************************************************
  317. TWasmObjSection
  318. ****************************************************************************}
  319. function TWasmObjSection.IsCode: Boolean;
  320. const
  321. CodePrefix = '.text';
  322. begin
  323. result:=(Length(Name)>=Length(CodePrefix)) and
  324. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  325. end;
  326. function TWasmObjSection.IsData: Boolean;
  327. begin
  328. result:=not IsCode;
  329. end;
  330. {****************************************************************************
  331. TWasmObjData
  332. ****************************************************************************}
  333. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  334. begin
  335. { For bss we need to set some flags that are target dependent,
  336. it is easier to disable it for smartlinking. It doesn't take up
  337. filespace }
  338. result:=not(target_info.system in systems_darwin) and
  339. create_smartlink_sections and
  340. (atype<>sec_toc) and
  341. (atype<>sec_user) and
  342. { on embedded systems every byte counts, so smartlink bss too }
  343. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  344. end;
  345. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  346. const aname: string; aorder: TAsmSectionOrder): string;
  347. const
  348. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  349. '.text',
  350. '.data',
  351. { why doesn't .rodata work? (FK) }
  352. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  353. { vtables (and anything else containing relocations), otherwise those are }
  354. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  355. { vtable for a class called Window: }
  356. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  357. { TODO: .data.ro not yet working}
  358. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  359. '.rodata',
  360. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  361. '.data',
  362. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  363. '.rodata',
  364. '.bss',
  365. '.threadvar',
  366. '.pdata',
  367. '', { stubs }
  368. '__DATA,__nl_symbol_ptr',
  369. '__DATA,__la_symbol_ptr',
  370. '__DATA,__mod_init_func',
  371. '__DATA,__mod_term_func',
  372. '.stab',
  373. '.stabstr',
  374. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  375. '.eh_frame',
  376. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  377. '.fpc',
  378. '.toc',
  379. '.init',
  380. '.fini',
  381. '.objc_class',
  382. '.objc_meta_class',
  383. '.objc_cat_cls_meth',
  384. '.objc_cat_inst_meth',
  385. '.objc_protocol',
  386. '.objc_string_object',
  387. '.objc_cls_meth',
  388. '.objc_inst_meth',
  389. '.objc_cls_refs',
  390. '.objc_message_refs',
  391. '.objc_symbols',
  392. '.objc_category',
  393. '.objc_class_vars',
  394. '.objc_instance_vars',
  395. '.objc_module_info',
  396. '.objc_class_names',
  397. '.objc_meth_var_types',
  398. '.objc_meth_var_names',
  399. '.objc_selector_strs',
  400. '.objc_protocol_ext',
  401. '.objc_class_ext',
  402. '.objc_property',
  403. '.objc_image_info',
  404. '.objc_cstring_object',
  405. '.objc_sel_fixup',
  406. '__DATA,__objc_data',
  407. '__DATA,__objc_const',
  408. '.objc_superrefs',
  409. '__DATA, __datacoal_nt,coalesced',
  410. '.objc_classlist',
  411. '.objc_nlclasslist',
  412. '.objc_catlist',
  413. '.obcj_nlcatlist',
  414. '.objc_protolist',
  415. '.stack',
  416. '.heap',
  417. '.gcc_except_table',
  418. '.ARM.attributes'
  419. );
  420. var
  421. sep : string[3];
  422. secname : string;
  423. begin
  424. secname:=secnames[atype];
  425. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  426. begin
  427. result:=secname+'.'+aname;
  428. exit;
  429. end;
  430. if atype=sec_threadvar then
  431. begin
  432. if (target_info.system in (systems_windows+systems_wince)) then
  433. secname:='.tls'
  434. else if (target_info.system in systems_linux) then
  435. secname:='.tbss';
  436. end;
  437. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  438. Thus, data which normally goes into .rodata and .rodata_norel sections must
  439. end up in .data section }
  440. if (atype in [sec_rodata,sec_rodata_norel]) and
  441. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  442. secname:='.data';
  443. { Windows correctly handles reallocations in readonly sections }
  444. if (atype=sec_rodata) and
  445. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  446. secname:='.rodata';
  447. { section type user gives the user full controll on the section name }
  448. if atype=sec_user then
  449. secname:=aname;
  450. if is_smart_section(atype) and (aname<>'') then
  451. begin
  452. case aorder of
  453. secorder_begin :
  454. sep:='.b_';
  455. secorder_end :
  456. sep:='.z_';
  457. else
  458. sep:='.n_';
  459. end;
  460. result:=secname+sep+aname
  461. end
  462. else
  463. result:=secname;
  464. end;
  465. constructor TWasmObjData.create(const n: string);
  466. begin
  467. inherited;
  468. CObjSection:=TWasmObjSection;
  469. CObjSymbol:=TWasmObjSymbol;
  470. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  471. end;
  472. destructor TWasmObjData.destroy;
  473. var
  474. i: Integer;
  475. begin
  476. FObjSymbolsExtraDataList.Free;
  477. for i:=low(FFuncTypes) to high(FFuncTypes) do
  478. begin
  479. FFuncTypes[i].free;
  480. FFuncTypes[i]:=nil;
  481. end;
  482. inherited destroy;
  483. end;
  484. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  485. const aname: string; aorder: TAsmSectionOrder): string;
  486. begin
  487. if (atype=sec_fpc) or (atype=sec_threadvar) then
  488. atype:=sec_data;
  489. Result:=sectionname_gas(atype, aname, aorder);
  490. end;
  491. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  492. p: TObjSymbol; Reloctype: TObjRelocationType);
  493. const
  494. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  495. var
  496. objreloc: TWasmObjRelocation;
  497. begin
  498. if CurrObjSec=nil then
  499. internalerror(200403072);
  500. objreloc:=nil;
  501. case Reloctype of
  502. RELOC_FUNCTION_INDEX_LEB:
  503. begin
  504. if Data<>0 then
  505. internalerror(2021092502);
  506. if len<>5 then
  507. internalerror(2021092503);
  508. if not assigned(p) then
  509. internalerror(2021092504);
  510. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  511. CurrObjSec.ObjRelocations.Add(objreloc);
  512. writebytes(leb_zero,5);
  513. end;
  514. RELOC_MEMORY_ADDR_LEB,
  515. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  516. begin
  517. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  518. internalerror(2021092602);
  519. if len<>5 then
  520. internalerror(2021092503);
  521. if not assigned(p) then
  522. internalerror(2021092504);
  523. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  524. objreloc.Addend:=Data;
  525. CurrObjSec.ObjRelocations.Add(objreloc);
  526. if RelocType=RELOC_MEMORY_ADDR_LEB then
  527. WriteUleb5(CurrObjSec,Data)
  528. else
  529. WriteSleb5(CurrObjSec,Data);
  530. end;
  531. RELOC_ABSOLUTE:
  532. begin
  533. if len<>4 then
  534. internalerror(2021092607);
  535. if not assigned(p) then
  536. internalerror(2021092608);
  537. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  538. objreloc.Addend:=Data;
  539. CurrObjSec.ObjRelocations.Add(objreloc);
  540. Data:=NtoLE(Data);
  541. writebytes(Data,4);
  542. end;
  543. RELOC_TYPE_INDEX_LEB:
  544. begin
  545. if len<>5 then
  546. internalerror(2021092612);
  547. if assigned(p) then
  548. internalerror(2021092613);
  549. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  550. CurrObjSec.ObjRelocations.Add(objreloc);
  551. WriteUleb5(CurrObjSec,Data);
  552. end;
  553. else
  554. internalerror(2021092501);
  555. end;
  556. end;
  557. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  558. begin
  559. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  560. if not assigned(result) then
  561. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  562. end;
  563. function TWasmObjData.AddFuncType(wft: TWasmFuncType): integer;
  564. var
  565. i: Integer;
  566. begin
  567. for i:=low(FFuncTypes) to high(FFuncTypes) do
  568. if wft.Equals(FFuncTypes[i]) then
  569. exit(i);
  570. result:=Length(FFuncTypes);
  571. SetLength(FFuncTypes,result+1);
  572. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  573. end;
  574. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  575. var
  576. i: Integer;
  577. ObjSymExtraData: TWasmObjSymbolExtraData;
  578. begin
  579. FLastFuncName:=ft.funcname;
  580. i:=AddFuncType(ft.functype);
  581. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  582. ObjSymExtraData.TypeIdx:=i;
  583. end;
  584. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  585. var
  586. ObjSymExtraData: TWasmObjSymbolExtraData;
  587. begin
  588. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  589. ObjSymExtraData.ExportName:=en.extname;
  590. end;
  591. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  592. var
  593. ObjSymExtraData: TWasmObjSymbolExtraData;
  594. begin
  595. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  596. ObjSymExtraData.ImportModule:=aim.importmodule;
  597. end;
  598. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  599. var
  600. ObjSymExtraData: TWasmObjSymbolExtraData;
  601. begin
  602. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  603. ObjSymExtraData.ImportName:=ain.importname;
  604. end;
  605. procedure TWasmObjData.DeclareLocal(al: tai_local);
  606. var
  607. ObjSymExtraData: TWasmObjSymbolExtraData;
  608. begin
  609. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  610. ObjSymExtraData.AddLocal(al.bastyp);
  611. end;
  612. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  613. var
  614. valsym: TObjSymbol;
  615. aliassym: TWasmObjSymbol;
  616. begin
  617. valsym:=CreateSymbol(avalue);
  618. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  619. aliassym.AliasOf:=valsym.Name;
  620. end;
  621. {****************************************************************************
  622. TWasmObjOutput
  623. ****************************************************************************}
  624. procedure TWasmObjOutput.WriteUleb(d: tdynamicarray; v: uint64);
  625. var
  626. b: byte;
  627. begin
  628. repeat
  629. b:=byte(v) and 127;
  630. v:=v shr 7;
  631. if v<>0 then
  632. b:=b or 128;
  633. d.write(b,1);
  634. until v=0;
  635. end;
  636. procedure TWasmObjOutput.WriteUleb(w: TObjectWriter; v: uint64);
  637. var
  638. b: byte;
  639. begin
  640. repeat
  641. b:=byte(v) and 127;
  642. v:=v shr 7;
  643. if v<>0 then
  644. b:=b or 128;
  645. w.write(b,1);
  646. until v=0;
  647. end;
  648. procedure TWasmObjOutput.WriteSleb(d: tdynamicarray; v: int64);
  649. var
  650. b: byte;
  651. Done: Boolean=false;
  652. begin
  653. repeat
  654. b:=byte(v) and 127;
  655. v:=SarInt64(v,7);
  656. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  657. Done:=true
  658. else
  659. b:=b or 128;
  660. d.write(b,1);
  661. until Done;
  662. end;
  663. procedure TWasmObjOutput.WriteByte(d: tdynamicarray; b: byte);
  664. begin
  665. d.write(b,1);
  666. end;
  667. procedure TWasmObjOutput.WriteName(d: tdynamicarray; const s: string);
  668. begin
  669. WriteUleb(d,Length(s));
  670. d.writestr(s);
  671. end;
  672. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  673. var
  674. b: byte;
  675. begin
  676. b:=ord(wsid);
  677. Writer.write(b,1);
  678. WriteUleb(Writer,FWasmSections[wsid].size);
  679. Writer.writearray(FWasmSections[wsid]);
  680. end;
  681. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  682. var
  683. b: byte;
  684. begin
  685. b:=0;
  686. Writer.write(b,1);
  687. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  688. Writer.writearray(FWasmCustomSections[wcst]);
  689. end;
  690. procedure TWasmObjOutput.CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  691. var
  692. buf: array [0..4095] of byte;
  693. bs: Integer;
  694. begin
  695. while size>0 do
  696. begin
  697. if size<SizeOf(buf) then
  698. bs:=Integer(size)
  699. else
  700. bs:=SizeOf(buf);
  701. src.read(buf,bs);
  702. dest.write(buf,bs);
  703. dec(size,bs);
  704. end;
  705. end;
  706. procedure TWasmObjOutput.WriteZeros(dest: tdynamicarray; size: QWord);
  707. var
  708. buf : array[0..1023] of byte;
  709. bs: Integer;
  710. begin
  711. fillchar(buf,sizeof(buf),0);
  712. while size>0 do
  713. begin
  714. if size<SizeOf(buf) then
  715. bs:=Integer(size)
  716. else
  717. bs:=SizeOf(buf);
  718. dest.write(buf,bs);
  719. dec(size,bs);
  720. end;
  721. end;
  722. procedure TWasmObjOutput.WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  723. var
  724. i: Integer;
  725. begin
  726. WriteUleb(dest,Length(wrt));
  727. for i:=low(wrt) to high(wrt) do
  728. WriteWasmBasicType(dest,wrt[i]);
  729. end;
  730. procedure TWasmObjOutput.WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  731. begin
  732. WriteByte(dest,encode_wasm_basic_type(wbt));
  733. end;
  734. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  735. begin
  736. result:=(sym.bind=AB_EXTERNAL) and (TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name)<>nil);
  737. end;
  738. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  739. var
  740. ExtraData: TWasmObjSymbolExtraData;
  741. begin
  742. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  743. begin
  744. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  745. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  746. end
  747. else
  748. result:=false;
  749. end;
  750. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  751. var
  752. i,
  753. rle_entries,
  754. cnt: Integer;
  755. lasttype: TWasmBasicType;
  756. begin
  757. if Length(ed.Locals)=0 then
  758. begin
  759. WriteUleb(dest,0);
  760. exit;
  761. end;
  762. rle_entries:=1;
  763. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  764. if ed.Locals[i]<>ed.Locals[i-1] then
  765. inc(rle_entries);
  766. WriteUleb(dest,rle_entries);
  767. lasttype:=ed.Locals[Low(ed.Locals)];
  768. cnt:=1;
  769. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  770. if ed.Locals[i]=ed.Locals[i-1] then
  771. inc(cnt)
  772. else
  773. begin
  774. WriteUleb(dest,cnt);
  775. WriteWasmBasicType(dest,lasttype);
  776. lasttype:=ed.Locals[i];
  777. cnt:=1;
  778. end;
  779. WriteUleb(dest,cnt);
  780. WriteWasmBasicType(dest,lasttype);
  781. end;
  782. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  783. var
  784. encoded_locals: tdynamicarray;
  785. ObjSymExtraData: TWasmObjSymbolExtraData;
  786. codelen: LongWord;
  787. ObjSection: TWasmObjSection;
  788. codeexprlen: QWord;
  789. begin
  790. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  791. ObjSection:=TWasmObjSection(objsym.objsection);
  792. ObjSection.Data.seek(objsym.address);
  793. codeexprlen:=objsym.size;
  794. encoded_locals:=tdynamicarray.Create(64);
  795. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  796. codelen:=encoded_locals.size+codeexprlen+1;
  797. WriteUleb(dest,codelen);
  798. encoded_locals.seek(0);
  799. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  800. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  801. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  802. WriteByte(dest,$0B);
  803. encoded_locals.Free;
  804. end;
  805. procedure TWasmObjOutput.WriteSymbolTable;
  806. begin
  807. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  808. FWasmSymbolTable.seek(0);
  809. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  810. end;
  811. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  812. begin
  813. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  814. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  815. FWasmRelocationCodeTable.seek(0);
  816. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  817. end;
  818. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  819. begin
  820. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  821. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  822. FWasmRelocationDataTable.seek(0);
  823. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  824. end;
  825. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  826. begin
  827. if FWasmLinkingSubsections[wlst].size>0 then
  828. begin
  829. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  830. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  831. FWasmLinkingSubsections[wlst].seek(0);
  832. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  833. end;
  834. end;
  835. procedure TWasmObjOutput.DoRelocations;
  836. var
  837. si, ri: Integer;
  838. objsec: TWasmObjSection;
  839. objrel: TWasmObjRelocation;
  840. begin
  841. for si:=0 to FData.ObjSectionList.Count-1 do
  842. begin
  843. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  844. for ri:=0 to objsec.ObjRelocations.Count-1 do
  845. begin
  846. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  847. case objrel.typ of
  848. RELOC_FUNCTION_INDEX_LEB:
  849. begin
  850. if not assigned(objrel.symbol) then
  851. internalerror(2021092509);
  852. objsec.Data.seek(objrel.DataOffset);
  853. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).ImportOrFuncIndex);
  854. end;
  855. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  856. begin
  857. if not assigned(objrel.symbol) then
  858. internalerror(2021092605);
  859. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  860. begin
  861. objsec.Data.seek(objrel.DataOffset);
  862. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  863. end;
  864. end;
  865. RELOC_MEMORY_ADDR_LEB:
  866. begin
  867. if not assigned(objrel.symbol) then
  868. internalerror(2021092606);
  869. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  870. internalerror(2021092628);
  871. if objrel.symbol.bind<>AB_EXTERNAL then
  872. begin
  873. objsec.Data.seek(objrel.DataOffset);
  874. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  875. end;
  876. end;
  877. RELOC_ABSOLUTE:
  878. begin
  879. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  880. begin
  881. objsec.Data.seek(objrel.DataOffset);
  882. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  883. end;
  884. end;
  885. RELOC_TYPE_INDEX_LEB:
  886. ;
  887. else
  888. internalerror(2021092510);
  889. end;
  890. end;
  891. end;
  892. end;
  893. procedure TWasmObjOutput.WriteRelocations;
  894. var
  895. si, ri: Integer;
  896. objsec: TWasmObjSection;
  897. objrel: TWasmObjRelocation;
  898. relout: tdynamicarray;
  899. relcount: PInteger;
  900. begin
  901. for si:=0 to FData.ObjSectionList.Count-1 do
  902. begin
  903. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  904. if objsec.IsCode then
  905. begin
  906. relout:=FWasmRelocationCodeTable;
  907. relcount:=@FWasmRelocationCodeTableEntriesCount;
  908. end
  909. else
  910. begin
  911. relout:=FWasmRelocationDataTable;
  912. relcount:=@FWasmRelocationDataTableEntriesCount;
  913. end;
  914. for ri:=0 to objsec.ObjRelocations.Count-1 do
  915. begin
  916. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  917. case objrel.typ of
  918. RELOC_FUNCTION_INDEX_LEB:
  919. begin
  920. if not assigned(objrel.symbol) then
  921. internalerror(2021092508);
  922. Inc(relcount^);
  923. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  924. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  925. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  926. end;
  927. RELOC_MEMORY_ADDR_LEB:
  928. begin
  929. if not assigned(objrel.symbol) then
  930. internalerror(2021092603);
  931. Inc(relcount^);
  932. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  933. internalerror(2021092628);
  934. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  935. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  936. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  937. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  938. end;
  939. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  940. begin
  941. if not assigned(objrel.symbol) then
  942. internalerror(2021092604);
  943. Inc(relcount^);
  944. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  945. begin
  946. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  947. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  948. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  949. end
  950. else
  951. begin
  952. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  953. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  954. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  955. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  956. end;
  957. end;
  958. RELOC_ABSOLUTE:
  959. begin
  960. if not assigned(objrel.symbol) then
  961. internalerror(2021092604);
  962. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  963. begin
  964. Inc(relcount^);
  965. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  966. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  967. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  968. end
  969. else
  970. begin
  971. Inc(relcount^);
  972. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  973. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  974. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  975. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  976. end;
  977. end;
  978. RELOC_TYPE_INDEX_LEB:
  979. begin
  980. Inc(relcount^);
  981. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  982. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  983. WriteUleb(relout,objrel.TypeIndex);
  984. end;
  985. else
  986. internalerror(2021092507);
  987. end;
  988. end;
  989. end;
  990. end;
  991. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  992. var
  993. i: Integer;
  994. objsec: TWasmObjSection;
  995. segment_count: Integer = 0;
  996. cur_seg_ofs: qword = 0;
  997. types_count,
  998. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  999. section_nr, code_section_nr, data_section_nr: Integer;
  1000. import_functions_count: Integer = 0;
  1001. export_functions_count: Integer = 0;
  1002. functions_count: Integer = 0;
  1003. objsym, ObjSymAlias: TWasmObjSymbol;
  1004. cust_sec: TWasmCustomSectionType;
  1005. begin
  1006. FData:=TWasmObjData(Data);
  1007. { each custom sections starts with its name }
  1008. for cust_sec in TWasmCustomSectionType do
  1009. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1010. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1011. for i:=0 to Data.ObjSymbolList.Count-1 do
  1012. begin
  1013. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1014. if IsExternalFunction(objsym) then
  1015. Inc(import_functions_count);
  1016. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1017. Inc(functions_count);
  1018. if IsExportedFunction(objsym) then
  1019. Inc(export_functions_count);
  1020. end;
  1021. types_count:=Length(FData.FFuncTypes);
  1022. WriteUleb(FWasmSections[wsiType],types_count);
  1023. for i:=0 to types_count-1 do
  1024. with FData.FFuncTypes[i] do
  1025. begin
  1026. WriteByte(FWasmSections[wsiType],$60);
  1027. WriteWasmResultType(FWasmSections[wsiType],params);
  1028. WriteWasmResultType(FWasmSections[wsiType],results);
  1029. end;
  1030. for i:=0 to Data.ObjSectionList.Count-1 do
  1031. begin
  1032. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1033. if objsec.IsCode then
  1034. objsec.SegIdx:=-1
  1035. else
  1036. begin
  1037. objsec.SegIdx:=segment_count;
  1038. objsec.SegOfs:=cur_seg_ofs;
  1039. Inc(segment_count);
  1040. Inc(cur_seg_ofs,objsec.Size);
  1041. end;
  1042. end;
  1043. WriteUleb(FWasmSections[wsiData],segment_count);
  1044. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  1045. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  1046. for i:=0 to Data.ObjSectionList.Count-1 do
  1047. begin
  1048. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1049. if objsec.IsData then
  1050. begin
  1051. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  1052. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  1053. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],0); { flags }
  1054. WriteByte(FWasmSections[wsiData],0);
  1055. WriteByte(FWasmSections[wsiData],$41);
  1056. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  1057. WriteByte(FWasmSections[wsiData],$0b);
  1058. WriteUleb(FWasmSections[wsiData],objsec.Size);
  1059. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  1060. if oso_Data in objsec.SecOptions then
  1061. begin
  1062. objsec.Data.seek(0);
  1063. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  1064. end
  1065. else
  1066. begin
  1067. WriteZeros(FWasmSections[wsiData],objsec.Size);
  1068. end;
  1069. end;
  1070. end;
  1071. imports_count:=3+import_functions_count;
  1072. WriteUleb(FWasmSections[wsiImport],imports_count);
  1073. { import[0] }
  1074. WriteName(FWasmSections[wsiImport],'env');
  1075. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1076. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1077. WriteByte(FWasmSections[wsiImport],$00); { min }
  1078. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1079. { import[1] }
  1080. WriteName(FWasmSections[wsiImport],'env');
  1081. WriteName(FWasmSections[wsiImport],'__stack_pointer');
  1082. WriteByte(FWasmSections[wsiImport],$03); { global }
  1083. WriteByte(FWasmSections[wsiImport],$7F); { i32 }
  1084. WriteByte(FWasmSections[wsiImport],$01); { var }
  1085. { import[2]..import[imports_count-2] }
  1086. NextImportFunctionIndex:=0;
  1087. for i:=0 to Data.ObjSymbolList.Count-1 do
  1088. begin
  1089. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1090. if IsExternalFunction(objsym) then
  1091. begin
  1092. objsym.ImportIndex:=NextImportFunctionIndex;
  1093. Inc(NextImportFunctionIndex);
  1094. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1095. if objsym.ExtraData.ImportModule<>'' then
  1096. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1097. else
  1098. WriteName(FWasmSections[wsiImport],'env');
  1099. WriteName(FWasmSections[wsiImport],objsym.Name);
  1100. WriteByte(FWasmSections[wsiImport],$00); { func }
  1101. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1102. end;
  1103. end;
  1104. { import[imports_count-1] }
  1105. WriteName(FWasmSections[wsiImport],'env');
  1106. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1107. WriteByte(FWasmSections[wsiImport],$01); { table }
  1108. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1109. WriteByte(FWasmSections[wsiImport],$00); { min }
  1110. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1111. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1112. NextFunctionIndex:=NextImportFunctionIndex;
  1113. for i:=0 to Data.ObjSymbolList.Count-1 do
  1114. begin
  1115. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1116. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1117. begin
  1118. objsym.FuncIndex:=NextFunctionIndex;
  1119. Inc(NextFunctionIndex);
  1120. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1121. end;
  1122. end;
  1123. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1124. for i:=0 to Data.ObjSymbolList.Count-1 do
  1125. begin
  1126. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1127. if IsExportedFunction(objsym) then
  1128. begin
  1129. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1130. WriteByte(FWasmSections[wsiExport],0); { func }
  1131. WriteUleb(FWasmSections[wsiExport],objsym.ImportOrFuncIndex);
  1132. end;
  1133. end;
  1134. for i:=0 to Data.ObjSymbolList.Count-1 do
  1135. begin
  1136. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1137. if IsExternalFunction(objsym) then
  1138. begin
  1139. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1140. Inc(FWasmSymbolTableEntriesCount);
  1141. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1142. if objsym.ExtraData.ImportModule<>'' then
  1143. begin
  1144. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1145. WriteUleb(FWasmSymbolTable,objsym.ImportIndex);
  1146. WriteName(FWasmSymbolTable,objsym.Name);
  1147. end
  1148. else
  1149. begin
  1150. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1151. WriteUleb(FWasmSymbolTable,objsym.ImportIndex);
  1152. end;
  1153. end
  1154. else if objsym.typ=AT_FUNCTION then
  1155. begin
  1156. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1157. Inc(FWasmSymbolTableEntriesCount);
  1158. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1159. if objsym.IsAlias then
  1160. begin
  1161. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1162. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1163. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1164. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1165. end
  1166. else
  1167. begin
  1168. if IsExportedFunction(objsym) then
  1169. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  1170. else
  1171. WriteUleb(FWasmSymbolTable,0);
  1172. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1173. end;
  1174. WriteName(FWasmSymbolTable,objsym.Name);
  1175. end
  1176. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1177. begin
  1178. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1179. Inc(FWasmSymbolTableEntriesCount);
  1180. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1181. if objsym.bind=AB_GLOBAL then
  1182. WriteUleb(FWasmSymbolTable,0)
  1183. else if objsym.bind=AB_LOCAL then
  1184. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1185. else if objsym.bind=AB_EXTERNAL then
  1186. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1187. else
  1188. internalerror(2021092506);
  1189. WriteName(FWasmSymbolTable,objsym.Name);
  1190. if objsym.bind<>AB_EXTERNAL then
  1191. begin
  1192. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1193. WriteUleb(FWasmSymbolTable,objsym.offset);
  1194. WriteUleb(FWasmSymbolTable,objsym.size);
  1195. end;
  1196. end;
  1197. end;
  1198. DoRelocations;
  1199. WriteUleb(FWasmSections[wsiCode],functions_count);
  1200. for i:=0 to Data.ObjSymbolList.Count-1 do
  1201. begin
  1202. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1203. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1204. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  1205. end;
  1206. WriteRelocations;
  1207. WriteSymbolTable;
  1208. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  1209. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  1210. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1211. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1212. code_section_nr:=-1;
  1213. data_section_nr:=-1;
  1214. section_nr:=0;
  1215. WriteWasmSection(wsiType);
  1216. Inc(section_nr);
  1217. WriteWasmSection(wsiImport);
  1218. Inc(section_nr);
  1219. WriteWasmSection(wsiFunction);
  1220. Inc(section_nr);
  1221. WriteWasmSection(wsiExport);
  1222. Inc(section_nr);
  1223. WriteWasmSection(wsiDataCount);
  1224. Inc(section_nr);
  1225. WriteWasmSection(wsiCode);
  1226. code_section_nr:=section_nr;
  1227. Inc(section_nr);
  1228. WriteWasmSection(wsiData);
  1229. data_section_nr:=section_nr;
  1230. Inc(section_nr);
  1231. WriteRelocationCodeTable(code_section_nr);
  1232. WriteRelocationDataTable(data_section_nr);
  1233. WriteWasmCustomSection(wcstLinking);
  1234. Inc(section_nr);
  1235. WriteWasmCustomSection(wcstRelocCode);
  1236. Inc(section_nr);
  1237. WriteWasmCustomSection(wcstRelocData);
  1238. Inc(section_nr);
  1239. result:=true;
  1240. end;
  1241. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  1242. var
  1243. i: TWasmSectionID;
  1244. j: TWasmCustomSectionType;
  1245. k: TWasmLinkingSubsectionType;
  1246. begin
  1247. inherited;
  1248. cobjdata:=TWasmObjData;
  1249. for i in TWasmSectionID do
  1250. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  1251. for j in TWasmCustomSectionType do
  1252. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  1253. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1254. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  1255. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  1256. FWasmSymbolTableEntriesCount:=0;
  1257. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  1258. FWasmRelocationCodeTableEntriesCount:=0;
  1259. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  1260. FWasmRelocationDataTableEntriesCount:=0;
  1261. end;
  1262. destructor TWasmObjOutput.destroy;
  1263. var
  1264. i: TWasmSectionID;
  1265. j: TWasmCustomSectionType;
  1266. k: TWasmLinkingSubsectionType;
  1267. begin
  1268. for i in TWasmSectionID do
  1269. FWasmSections[i].Free;
  1270. for j in TWasmCustomSectionType do
  1271. FWasmCustomSections[j].Free;
  1272. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1273. FWasmLinkingSubsections[k].Free;
  1274. FWasmSymbolTable.Free;
  1275. FWasmRelocationCodeTable.Free;
  1276. FWasmRelocationDataTable.Free;
  1277. inherited destroy;
  1278. end;
  1279. {****************************************************************************
  1280. TWasmAssembler
  1281. ****************************************************************************}
  1282. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  1283. begin
  1284. inherited;
  1285. CObjOutput:=TWasmObjOutput;
  1286. end;
  1287. {*****************************************************************************
  1288. Initialize
  1289. *****************************************************************************}
  1290. {$ifdef wasm32}
  1291. const
  1292. as_wasm32_wasm_info : tasminfo =
  1293. (
  1294. id : as_wasm32_wasm;
  1295. idtxt : 'OMF';
  1296. asmbin : '';
  1297. asmcmd : '';
  1298. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  1299. flags : [af_outputbinary,af_smartlink_sections];
  1300. labelprefix : '..@';
  1301. labelmaxlen : -1;
  1302. comment : '; ';
  1303. dollarsign: '$';
  1304. );
  1305. {$endif wasm32}
  1306. initialization
  1307. {$ifdef wasm32}
  1308. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  1309. {$endif wasm32}
  1310. end.