ogwasm.pas 48 KB

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