ogwasm.pas 58 KB

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