ogwasm.pas 46 KB

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