ogwasm.pas 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. {
  2. Copyright (c) 2021 by Nikolay Nikolov
  3. Contains the WebAssembly binary module format reader and writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit ogwasm;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cclasses,globtype,
  23. { target }
  24. systems,cpubase,
  25. { assembler }
  26. aasmbase,assemble,aasmcpu,
  27. { WebAssembly module format definitions }
  28. wasmbase,
  29. { output }
  30. ogbase,
  31. owbase;
  32. type
  33. TWasmObjSymbolExtraData = class;
  34. { TWasmObjSymbol }
  35. TWasmObjSymbol = class(TObjSymbol)
  36. ImportIndex: Integer;
  37. FuncIndex: Integer;
  38. SymbolIndex: Integer;
  39. AliasOf: string;
  40. ExtraData: TWasmObjSymbolExtraData;
  41. constructor create(AList:TFPHashObjectList;const AName:string);override;
  42. function ImportOrFuncIndex: Integer;
  43. function IsAlias: Boolean;
  44. end;
  45. { TWasmObjRelocation }
  46. TWasmObjRelocation = class(TObjRelocation)
  47. public
  48. TypeIndex: Integer;
  49. 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. WriteByte(dest,encode_wasm_basic_type(wbt));
  703. end;
  704. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  705. begin
  706. result:=(sym.bind=AB_EXTERNAL) and (TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name)<>nil);
  707. end;
  708. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  709. var
  710. i,
  711. rle_entries,
  712. cnt: Integer;
  713. lasttype: TWasmBasicType;
  714. begin
  715. if Length(ed.Locals)=0 then
  716. begin
  717. WriteUleb(dest,0);
  718. exit;
  719. end;
  720. rle_entries:=1;
  721. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  722. if ed.Locals[i]<>ed.Locals[i-1] then
  723. inc(rle_entries);
  724. WriteUleb(dest,rle_entries);
  725. lasttype:=ed.Locals[Low(ed.Locals)];
  726. cnt:=1;
  727. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  728. if ed.Locals[i]=ed.Locals[i-1] then
  729. inc(cnt)
  730. else
  731. begin
  732. WriteUleb(dest,cnt);
  733. WriteWasmBasicType(dest,lasttype);
  734. lasttype:=ed.Locals[i];
  735. cnt:=1;
  736. end;
  737. WriteUleb(dest,cnt);
  738. WriteWasmBasicType(dest,lasttype);
  739. end;
  740. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  741. var
  742. encoded_locals: tdynamicarray;
  743. ObjSymExtraData: TWasmObjSymbolExtraData;
  744. codelen: LongWord;
  745. ObjSection: TWasmObjSection;
  746. codeexprlen: QWord;
  747. begin
  748. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  749. ObjSection:=TWasmObjSection(objsym.objsection);
  750. ObjSection.Data.seek(objsym.address);
  751. codeexprlen:=ObjSection.Size-objsym.address;
  752. encoded_locals:=tdynamicarray.Create(64);
  753. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  754. codelen:=encoded_locals.size+codeexprlen+1;
  755. WriteUleb(dest,codelen);
  756. encoded_locals.seek(0);
  757. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  758. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  759. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  760. WriteByte(dest,$0B);
  761. encoded_locals.Free;
  762. end;
  763. procedure TWasmObjOutput.WriteSymbolTable;
  764. begin
  765. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  766. FWasmSymbolTable.seek(0);
  767. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  768. end;
  769. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  770. begin
  771. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  772. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  773. FWasmRelocationCodeTable.seek(0);
  774. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  775. end;
  776. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  777. begin
  778. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  779. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  780. FWasmRelocationDataTable.seek(0);
  781. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  782. end;
  783. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  784. begin
  785. if FWasmLinkingSubsections[wlst].size>0 then
  786. begin
  787. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  788. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  789. FWasmLinkingSubsections[wlst].seek(0);
  790. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  791. end;
  792. end;
  793. procedure TWasmObjOutput.DoRelocations;
  794. var
  795. si, ri: Integer;
  796. objsec: TWasmObjSection;
  797. objrel: TWasmObjRelocation;
  798. begin
  799. for si:=0 to FData.ObjSectionList.Count-1 do
  800. begin
  801. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  802. for ri:=0 to objsec.ObjRelocations.Count-1 do
  803. begin
  804. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  805. case objrel.typ of
  806. RELOC_FUNCTION_INDEX_LEB:
  807. begin
  808. if not assigned(objrel.symbol) then
  809. internalerror(2021092509);
  810. objsec.Data.seek(objrel.DataOffset);
  811. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).ImportOrFuncIndex);
  812. end;
  813. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  814. begin
  815. if not assigned(objrel.symbol) then
  816. internalerror(2021092605);
  817. if objrel.symbol.bind<>AB_EXTERNAL then
  818. begin
  819. objsec.Data.seek(objrel.DataOffset);
  820. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  821. end;
  822. end;
  823. RELOC_MEMORY_ADDR_LEB:
  824. begin
  825. if not assigned(objrel.symbol) then
  826. internalerror(2021092606);
  827. if objrel.symbol.bind<>AB_EXTERNAL then
  828. begin
  829. objsec.Data.seek(objrel.DataOffset);
  830. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  831. end;
  832. end;
  833. RELOC_ABSOLUTE:
  834. ;
  835. RELOC_TYPE_INDEX_LEB:
  836. ;
  837. else
  838. internalerror(2021092510);
  839. end;
  840. end;
  841. end;
  842. end;
  843. procedure TWasmObjOutput.WriteRelocations;
  844. var
  845. si, ri: Integer;
  846. objsec: TWasmObjSection;
  847. objrel: TWasmObjRelocation;
  848. relout: tdynamicarray;
  849. relcount: PInteger;
  850. begin
  851. for si:=0 to FData.ObjSectionList.Count-1 do
  852. begin
  853. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  854. if objsec.IsCode then
  855. begin
  856. relout:=FWasmRelocationCodeTable;
  857. relcount:=@FWasmRelocationCodeTableEntriesCount;
  858. end
  859. else
  860. begin
  861. relout:=FWasmRelocationDataTable;
  862. relcount:=@FWasmRelocationDataTableEntriesCount;
  863. end;
  864. for ri:=0 to objsec.ObjRelocations.Count-1 do
  865. begin
  866. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  867. case objrel.typ of
  868. RELOC_FUNCTION_INDEX_LEB:
  869. begin
  870. if not assigned(objrel.symbol) then
  871. internalerror(2021092508);
  872. Inc(relcount^);
  873. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  874. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  875. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  876. end;
  877. RELOC_MEMORY_ADDR_LEB:
  878. begin
  879. if not assigned(objrel.symbol) then
  880. internalerror(2021092603);
  881. Inc(relcount^);
  882. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  883. internalerror(2021092628);
  884. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  885. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  886. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  887. WriteUleb(relout,0); { addend to add to the address }
  888. end;
  889. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  890. begin
  891. if not assigned(objrel.symbol) then
  892. internalerror(2021092604);
  893. Inc(relcount^);
  894. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  895. begin
  896. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  897. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  898. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  899. end
  900. else
  901. begin
  902. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  903. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  904. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  905. WriteUleb(relout,0); { addend to add to the address }
  906. end;
  907. end;
  908. RELOC_ABSOLUTE:
  909. begin
  910. if not assigned(objrel.symbol) then
  911. internalerror(2021092604);
  912. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  913. begin
  914. Inc(relcount^);
  915. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  916. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  917. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  918. end
  919. else
  920. begin
  921. Inc(relcount^);
  922. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  923. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  924. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  925. WriteUleb(relout,0); { addend to add to the address }
  926. end;
  927. end;
  928. RELOC_TYPE_INDEX_LEB:
  929. begin
  930. Inc(relcount^);
  931. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  932. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  933. WriteUleb(relout,objrel.TypeIndex);
  934. end;
  935. else
  936. internalerror(2021092507);
  937. end;
  938. end;
  939. end;
  940. end;
  941. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  942. var
  943. i: Integer;
  944. objsec: TWasmObjSection;
  945. segment_count: Integer = 0;
  946. cur_seg_ofs: qword = 0;
  947. types_count,
  948. imports_count, NextImportFunctionIndex, NextFunctionIndex: Integer;
  949. import_functions_count: Integer = 0;
  950. functions_count: Integer = 0;
  951. objsym, ObjSymAlias: TWasmObjSymbol;
  952. cust_sec: TWasmCustomSectionType;
  953. begin
  954. FData:=TWasmObjData(Data);
  955. { each custom sections starts with its name }
  956. for cust_sec in TWasmCustomSectionType do
  957. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  958. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  959. for i:=0 to Data.ObjSymbolList.Count-1 do
  960. begin
  961. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  962. if IsExternalFunction(objsym) then
  963. Inc(import_functions_count);
  964. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  965. Inc(functions_count);
  966. end;
  967. types_count:=Length(FData.FFuncTypes);
  968. WriteUleb(FWasmSections[wsiType],types_count);
  969. for i:=0 to types_count-1 do
  970. with FData.FFuncTypes[i] do
  971. begin
  972. WriteByte(FWasmSections[wsiType],$60);
  973. WriteWasmResultType(FWasmSections[wsiType],params);
  974. WriteWasmResultType(FWasmSections[wsiType],results);
  975. end;
  976. for i:=0 to Data.ObjSectionList.Count-1 do
  977. begin
  978. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  979. if objsec.IsCode then
  980. objsec.SegIdx:=-1
  981. else
  982. begin
  983. objsec.SegIdx:=segment_count;
  984. objsec.SegOfs:=cur_seg_ofs;
  985. Inc(segment_count);
  986. Inc(cur_seg_ofs,objsec.Size);
  987. end;
  988. end;
  989. WriteUleb(FWasmSections[wsiData],segment_count);
  990. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  991. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  992. for i:=0 to Data.ObjSectionList.Count-1 do
  993. begin
  994. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  995. if objsec.IsData then
  996. begin
  997. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  998. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  999. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],0); { flags }
  1000. WriteByte(FWasmSections[wsiData],0);
  1001. WriteByte(FWasmSections[wsiData],$41);
  1002. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  1003. WriteByte(FWasmSections[wsiData],$0b);
  1004. WriteUleb(FWasmSections[wsiData],objsec.Size);
  1005. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  1006. if oso_Data in objsec.SecOptions then
  1007. begin
  1008. objsec.Data.seek(0);
  1009. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  1010. end
  1011. else
  1012. begin
  1013. WriteZeros(FWasmSections[wsiData],objsec.Size);
  1014. end;
  1015. end;
  1016. end;
  1017. imports_count:=3+import_functions_count;
  1018. WriteUleb(FWasmSections[wsiImport],imports_count);
  1019. { import[0] }
  1020. WriteName(FWasmSections[wsiImport],'env');
  1021. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1022. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1023. WriteByte(FWasmSections[wsiImport],$00); { min }
  1024. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1025. { import[1] }
  1026. WriteName(FWasmSections[wsiImport],'env');
  1027. WriteName(FWasmSections[wsiImport],'__stack_pointer');
  1028. WriteByte(FWasmSections[wsiImport],$03); { global }
  1029. WriteByte(FWasmSections[wsiImport],$7F); { i32 }
  1030. WriteByte(FWasmSections[wsiImport],$01); { var }
  1031. { import[2]..import[imports_count-2] }
  1032. NextImportFunctionIndex:=0;
  1033. for i:=0 to Data.ObjSymbolList.Count-1 do
  1034. begin
  1035. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1036. if IsExternalFunction(objsym) then
  1037. begin
  1038. objsym.ImportIndex:=NextImportFunctionIndex;
  1039. Inc(NextImportFunctionIndex);
  1040. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1041. if objsym.ExtraData.ImportModule<>'' then
  1042. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1043. else
  1044. WriteName(FWasmSections[wsiImport],'env');
  1045. WriteName(FWasmSections[wsiImport],objsym.Name);
  1046. WriteByte(FWasmSections[wsiImport],$00); { func }
  1047. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1048. end;
  1049. end;
  1050. { import[imports_count-1] }
  1051. WriteName(FWasmSections[wsiImport],'env');
  1052. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1053. WriteByte(FWasmSections[wsiImport],$01); { table }
  1054. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1055. WriteByte(FWasmSections[wsiImport],$00); { min }
  1056. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1057. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1058. NextFunctionIndex:=NextImportFunctionIndex;
  1059. for i:=0 to Data.ObjSymbolList.Count-1 do
  1060. begin
  1061. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1062. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1063. begin
  1064. objsym.FuncIndex:=NextFunctionIndex;
  1065. Inc(NextFunctionIndex);
  1066. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1067. end;
  1068. end;
  1069. for i:=0 to Data.ObjSymbolList.Count-1 do
  1070. begin
  1071. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1072. if IsExternalFunction(objsym) then
  1073. begin
  1074. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1075. Inc(FWasmSymbolTableEntriesCount);
  1076. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1077. if objsym.ExtraData.ImportModule<>'' then
  1078. begin
  1079. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1080. WriteUleb(FWasmSymbolTable,objsym.ImportIndex);
  1081. WriteName(FWasmSymbolTable,objsym.Name);
  1082. end
  1083. else
  1084. begin
  1085. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1086. WriteUleb(FWasmSymbolTable,objsym.ImportIndex);
  1087. end;
  1088. end
  1089. else if objsym.typ=AT_FUNCTION then
  1090. begin
  1091. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1092. Inc(FWasmSymbolTableEntriesCount);
  1093. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1094. if objsym.IsAlias then
  1095. begin
  1096. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1097. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1098. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1099. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1100. end
  1101. else
  1102. begin
  1103. WriteUleb(FWasmSymbolTable,0);
  1104. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1105. end;
  1106. WriteName(FWasmSymbolTable,objsym.Name);
  1107. end
  1108. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1109. begin
  1110. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1111. Inc(FWasmSymbolTableEntriesCount);
  1112. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1113. if objsym.bind=AB_GLOBAL then
  1114. WriteUleb(FWasmSymbolTable,0)
  1115. else if objsym.bind=AB_LOCAL then
  1116. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1117. else if objsym.bind=AB_EXTERNAL then
  1118. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1119. else
  1120. internalerror(2021092506);
  1121. WriteName(FWasmSymbolTable,objsym.Name);
  1122. if objsym.bind<>AB_EXTERNAL then
  1123. begin
  1124. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1125. WriteUleb(FWasmSymbolTable,objsym.offset);
  1126. WriteUleb(FWasmSymbolTable,objsym.size);
  1127. end;
  1128. end;
  1129. end;
  1130. DoRelocations;
  1131. WriteUleb(FWasmSections[wsiCode],functions_count);
  1132. for i:=0 to Data.ObjSymbolList.Count-1 do
  1133. begin
  1134. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1135. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1136. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  1137. end;
  1138. WriteRelocations;
  1139. WriteSymbolTable;
  1140. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  1141. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  1142. WriteRelocationCodeTable(4); { code section is section #4 }
  1143. WriteRelocationDataTable(5); { code section is section #5 }
  1144. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1145. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1146. WriteWasmSection(wsiType); { section #0 }
  1147. WriteWasmSection(wsiImport); { section #1 }
  1148. WriteWasmSection(wsiFunction); { section #2 }
  1149. WriteWasmSection(wsiDataCount); { section #3 }
  1150. WriteWasmSection(wsiCode); { section #4 }
  1151. WriteWasmSection(wsiData); { section #5 }
  1152. WriteWasmCustomSection(wcstLinking); { section #6 }
  1153. WriteWasmCustomSection(wcstRelocCode); { section #7 }
  1154. WriteWasmCustomSection(wcstRelocData); { section #8 }
  1155. Writeln('ObjSymbolList:');
  1156. for i:=0 to Data.ObjSymbolList.Count-1 do
  1157. begin
  1158. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1159. Write(objsym.Name, ' bind=', objsym.Bind, ' typ=', objsym.typ, ' address=', objsym.address, ' objsection=');
  1160. if assigned(objsym.objsection) then
  1161. Write(objsym.objsection.Name)
  1162. else
  1163. Write('nil');
  1164. Writeln;
  1165. end;
  1166. Writeln('ObjSectionList:');
  1167. for i:=0 to Data.ObjSectionList.Count-1 do
  1168. begin
  1169. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1170. Writeln(objsec.Name, ' IsCode=', objsec.IsCode, ' IsData=', objsec.IsData, ' Size=', objsec.Size, ' MemPos=', objsec.MemPos, ' DataPos=', objsec.DataPos, ' SegIdx=', objsec.SegIdx);
  1171. end;
  1172. result:=true;
  1173. end;
  1174. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  1175. var
  1176. i: TWasmSectionID;
  1177. j: TWasmCustomSectionType;
  1178. k: TWasmLinkingSubsectionType;
  1179. begin
  1180. inherited;
  1181. cobjdata:=TWasmObjData;
  1182. for i in TWasmSectionID do
  1183. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  1184. for j in TWasmCustomSectionType do
  1185. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  1186. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1187. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  1188. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  1189. FWasmSymbolTableEntriesCount:=0;
  1190. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  1191. FWasmRelocationCodeTableEntriesCount:=0;
  1192. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  1193. FWasmRelocationDataTableEntriesCount:=0;
  1194. end;
  1195. destructor TWasmObjOutput.destroy;
  1196. var
  1197. i: TWasmSectionID;
  1198. j: TWasmCustomSectionType;
  1199. k: TWasmLinkingSubsectionType;
  1200. begin
  1201. for i in TWasmSectionID do
  1202. FWasmSections[i].Free;
  1203. for j in TWasmCustomSectionType do
  1204. FWasmCustomSections[j].Free;
  1205. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1206. FWasmLinkingSubsections[k].Free;
  1207. FWasmSymbolTable.Free;
  1208. FWasmRelocationCodeTable.Free;
  1209. FWasmRelocationDataTable.Free;
  1210. inherited destroy;
  1211. end;
  1212. {****************************************************************************
  1213. TWasmAssembler
  1214. ****************************************************************************}
  1215. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  1216. begin
  1217. inherited;
  1218. CObjOutput:=TWasmObjOutput;
  1219. end;
  1220. {*****************************************************************************
  1221. Initialize
  1222. *****************************************************************************}
  1223. {$ifdef wasm32}
  1224. const
  1225. as_wasm32_wasm_info : tasminfo =
  1226. (
  1227. id : as_wasm32_wasm;
  1228. idtxt : 'OMF';
  1229. asmbin : '';
  1230. asmcmd : '';
  1231. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  1232. flags : [af_outputbinary,af_smartlink_sections];
  1233. labelprefix : '..@';
  1234. labelmaxlen : -1;
  1235. comment : '; ';
  1236. dollarsign: '$';
  1237. );
  1238. {$endif wasm32}
  1239. initialization
  1240. {$ifdef wasm32}
  1241. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  1242. {$endif wasm32}
  1243. end.