ogwasm.pas 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. { TWasmObjSymbol }
  34. TWasmObjSymbol = class(TObjSymbol)
  35. ImportIndex: Integer;
  36. constructor create(AList:TFPHashObjectList;const AName:string);
  37. end;
  38. { TWasmObjRelocation }
  39. TWasmObjRelocation = class(TObjRelocation)
  40. end;
  41. { TWasmObjSymbolExtraData }
  42. TWasmObjSymbolExtraData = class(TFPHashObject)
  43. TypeIdx: Integer;
  44. ImportModule: string;
  45. ImportName: string;
  46. Locals: array of TWasmBasicType;
  47. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  48. procedure AddLocal(bastyp: TWasmBasicType);
  49. end;
  50. { TWasmObjSection }
  51. TWasmObjSection = class(TObjSection)
  52. public
  53. SegIdx: Integer;
  54. SegOfs: qword;
  55. function IsCode: Boolean;
  56. function IsData: Boolean;
  57. end;
  58. { TWasmObjData }
  59. TWasmObjData = class(TObjData)
  60. private
  61. FFuncTypes: array of TWasmFuncType;
  62. FObjSymbolsExtraDataList: TFPHashObjectList;
  63. FLastFuncName: string;
  64. function is_smart_section(atype:TAsmSectiontype):boolean;
  65. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  66. public
  67. constructor create(const n:string);override;
  68. destructor destroy; override;
  69. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  70. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  71. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  72. function AddFuncType(wft: TWasmFuncType): integer;
  73. procedure DeclareFuncType(ft: tai_functype);
  74. procedure DeclareImportModule(aim: tai_import_module);
  75. procedure DeclareImportName(ain: tai_import_name);
  76. procedure DeclareLocal(al: tai_local);
  77. end;
  78. { TWasmObjOutput }
  79. TWasmObjOutput = class(tObjOutput)
  80. private
  81. FData: TWasmObjData;
  82. FWasmSymbolTable: tdynamicarray;
  83. FWasmSymbolTableEntriesCount: Integer;
  84. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  85. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  86. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  87. procedure WriteUleb(d: tdynamicarray; v: uint64);
  88. procedure WriteUleb(w: TObjectWriter; v: uint64);
  89. procedure WriteSleb(d: tdynamicarray; v: int64);
  90. procedure WriteByte(d: tdynamicarray; b: byte);
  91. procedure WriteName(d: tdynamicarray; const s: string);
  92. procedure WriteWasmSection(wsid: TWasmSectionID);
  93. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  94. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  95. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  96. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  97. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  98. function IsExternalFunction(sym: TObjSymbol): Boolean;
  99. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  100. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  101. procedure WriteSymbolTable;
  102. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  103. protected
  104. function writeData(Data:TObjData):boolean;override;
  105. public
  106. constructor create(AWriter:TObjectWriter);override;
  107. destructor destroy;override;
  108. end;
  109. { TWasmAssembler }
  110. TWasmAssembler = class(tinternalassembler)
  111. constructor create(info: pasminfo; smart:boolean);override;
  112. end;
  113. implementation
  114. uses
  115. verbose;
  116. {****************************************************************************
  117. TWasmObjSymbol
  118. ****************************************************************************}
  119. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  120. begin
  121. inherited create(AList,AName);
  122. ImportIndex:=-1;
  123. end;
  124. {****************************************************************************
  125. TWasmObjSymbolExtraData
  126. ****************************************************************************}
  127. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  128. begin
  129. inherited Create(HashObjectList,s);
  130. TypeIdx:=-1;
  131. end;
  132. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  133. begin
  134. SetLength(Locals,Length(Locals)+1);
  135. Locals[High(Locals)]:=bastyp;
  136. end;
  137. {****************************************************************************
  138. TWasmObjSection
  139. ****************************************************************************}
  140. function TWasmObjSection.IsCode: Boolean;
  141. const
  142. CodePrefix = '.text';
  143. begin
  144. result:=(Length(Name)>=Length(CodePrefix)) and
  145. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  146. end;
  147. function TWasmObjSection.IsData: Boolean;
  148. begin
  149. result:=not IsCode;
  150. end;
  151. {****************************************************************************
  152. TWasmObjData
  153. ****************************************************************************}
  154. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  155. begin
  156. { For bss we need to set some flags that are target dependent,
  157. it is easier to disable it for smartlinking. It doesn't take up
  158. filespace }
  159. result:=not(target_info.system in systems_darwin) and
  160. create_smartlink_sections and
  161. (atype<>sec_toc) and
  162. (atype<>sec_user) and
  163. { on embedded systems every byte counts, so smartlink bss too }
  164. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  165. end;
  166. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  167. const aname: string; aorder: TAsmSectionOrder): string;
  168. const
  169. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  170. '.text',
  171. '.data',
  172. { why doesn't .rodata work? (FK) }
  173. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  174. { vtables (and anything else containing relocations), otherwise those are }
  175. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  176. { vtable for a class called Window: }
  177. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  178. { TODO: .data.ro not yet working}
  179. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  180. '.rodata',
  181. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  182. '.data',
  183. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  184. '.rodata',
  185. '.bss',
  186. '.threadvar',
  187. '.pdata',
  188. '', { stubs }
  189. '__DATA,__nl_symbol_ptr',
  190. '__DATA,__la_symbol_ptr',
  191. '__DATA,__mod_init_func',
  192. '__DATA,__mod_term_func',
  193. '.stab',
  194. '.stabstr',
  195. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  196. '.eh_frame',
  197. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  198. '.fpc',
  199. '.toc',
  200. '.init',
  201. '.fini',
  202. '.objc_class',
  203. '.objc_meta_class',
  204. '.objc_cat_cls_meth',
  205. '.objc_cat_inst_meth',
  206. '.objc_protocol',
  207. '.objc_string_object',
  208. '.objc_cls_meth',
  209. '.objc_inst_meth',
  210. '.objc_cls_refs',
  211. '.objc_message_refs',
  212. '.objc_symbols',
  213. '.objc_category',
  214. '.objc_class_vars',
  215. '.objc_instance_vars',
  216. '.objc_module_info',
  217. '.objc_class_names',
  218. '.objc_meth_var_types',
  219. '.objc_meth_var_names',
  220. '.objc_selector_strs',
  221. '.objc_protocol_ext',
  222. '.objc_class_ext',
  223. '.objc_property',
  224. '.objc_image_info',
  225. '.objc_cstring_object',
  226. '.objc_sel_fixup',
  227. '__DATA,__objc_data',
  228. '__DATA,__objc_const',
  229. '.objc_superrefs',
  230. '__DATA, __datacoal_nt,coalesced',
  231. '.objc_classlist',
  232. '.objc_nlclasslist',
  233. '.objc_catlist',
  234. '.obcj_nlcatlist',
  235. '.objc_protolist',
  236. '.stack',
  237. '.heap',
  238. '.gcc_except_table',
  239. '.ARM.attributes'
  240. );
  241. var
  242. sep : string[3];
  243. secname : string;
  244. begin
  245. secname:=secnames[atype];
  246. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  247. begin
  248. result:=secname+'.'+aname;
  249. exit;
  250. end;
  251. if atype=sec_threadvar then
  252. begin
  253. if (target_info.system in (systems_windows+systems_wince)) then
  254. secname:='.tls'
  255. else if (target_info.system in systems_linux) then
  256. secname:='.tbss';
  257. end;
  258. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  259. Thus, data which normally goes into .rodata and .rodata_norel sections must
  260. end up in .data section }
  261. if (atype in [sec_rodata,sec_rodata_norel]) and
  262. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  263. secname:='.data';
  264. { Windows correctly handles reallocations in readonly sections }
  265. if (atype=sec_rodata) and
  266. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  267. secname:='.rodata';
  268. { section type user gives the user full controll on the section name }
  269. if atype=sec_user then
  270. secname:=aname;
  271. if is_smart_section(atype) and (aname<>'') then
  272. begin
  273. case aorder of
  274. secorder_begin :
  275. sep:='.b_';
  276. secorder_end :
  277. sep:='.z_';
  278. else
  279. sep:='.n_';
  280. end;
  281. result:=secname+sep+aname
  282. end
  283. else
  284. result:=secname;
  285. end;
  286. constructor TWasmObjData.create(const n: string);
  287. begin
  288. inherited;
  289. CObjSection:=TWasmObjSection;
  290. CObjSymbol:=TWasmObjSymbol;
  291. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  292. end;
  293. destructor TWasmObjData.destroy;
  294. var
  295. i: Integer;
  296. begin
  297. FObjSymbolsExtraDataList.Free;
  298. for i:=low(FFuncTypes) to high(FFuncTypes) do
  299. begin
  300. FFuncTypes[i].free;
  301. FFuncTypes[i]:=nil;
  302. end;
  303. inherited destroy;
  304. end;
  305. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  306. const aname: string; aorder: TAsmSectionOrder): string;
  307. begin
  308. if (atype=sec_fpc) or (atype=sec_threadvar) then
  309. atype:=sec_data;
  310. Result:=sectionname_gas(atype, aname, aorder);
  311. end;
  312. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  313. p: TObjSymbol; Reloctype: TObjRelocationType);
  314. const
  315. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  316. var
  317. objreloc: TWasmObjRelocation;
  318. begin
  319. if CurrObjSec=nil then
  320. internalerror(200403072);
  321. objreloc:=nil;
  322. case Reloctype of
  323. RELOC_FUNCTION_INDEX_LEB:
  324. begin
  325. if Data<>0 then
  326. internalerror(2021092502);
  327. if len<>5 then
  328. internalerror(2021092503);
  329. if not assigned(p) then
  330. internalerror(2021092504);
  331. if p.bind<>AB_EXTERNAL then
  332. internalerror(2021092505);
  333. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  334. CurrObjSec.ObjRelocations.Add(objreloc);
  335. writebytes(leb_zero,5);
  336. end;
  337. RELOC_ABSOLUTE:
  338. begin
  339. { todo... }
  340. end;
  341. else
  342. internalerror(2021092501);
  343. end;
  344. end;
  345. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  346. begin
  347. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  348. if not assigned(result) then
  349. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  350. end;
  351. function TWasmObjData.AddFuncType(wft: TWasmFuncType): integer;
  352. var
  353. i: Integer;
  354. begin
  355. for i:=low(FFuncTypes) to high(FFuncTypes) do
  356. if wft.Equals(FFuncTypes[i]) then
  357. exit(i);
  358. result:=Length(FFuncTypes);
  359. SetLength(FFuncTypes,result+1);
  360. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  361. end;
  362. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  363. var
  364. i: Integer;
  365. ObjSymExtraData: TWasmObjSymbolExtraData;
  366. begin
  367. FLastFuncName:=ft.funcname;
  368. i:=AddFuncType(ft.functype);
  369. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  370. ObjSymExtraData.TypeIdx:=i;
  371. end;
  372. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  373. var
  374. ObjSymExtraData: TWasmObjSymbolExtraData;
  375. begin
  376. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  377. ObjSymExtraData.ImportModule:=aim.importmodule;
  378. end;
  379. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  380. var
  381. ObjSymExtraData: TWasmObjSymbolExtraData;
  382. begin
  383. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  384. ObjSymExtraData.ImportName:=ain.importname;
  385. end;
  386. procedure TWasmObjData.DeclareLocal(al: tai_local);
  387. var
  388. ObjSymExtraData: TWasmObjSymbolExtraData;
  389. begin
  390. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  391. ObjSymExtraData.AddLocal(al.bastyp);
  392. end;
  393. {****************************************************************************
  394. TWasmObjOutput
  395. ****************************************************************************}
  396. procedure TWasmObjOutput.WriteUleb(d: tdynamicarray; v: uint64);
  397. var
  398. b: byte;
  399. begin
  400. repeat
  401. b:=byte(v) and 127;
  402. v:=v shr 7;
  403. if v<>0 then
  404. b:=b or 128;
  405. d.write(b,1);
  406. until v=0;
  407. end;
  408. procedure TWasmObjOutput.WriteUleb(w: TObjectWriter; v: uint64);
  409. var
  410. b: byte;
  411. begin
  412. repeat
  413. b:=byte(v) and 127;
  414. v:=v shr 7;
  415. if v<>0 then
  416. b:=b or 128;
  417. w.write(b,1);
  418. until v=0;
  419. end;
  420. procedure TWasmObjOutput.WriteSleb(d: tdynamicarray; v: int64);
  421. var
  422. b: byte;
  423. Done: Boolean=false;
  424. begin
  425. repeat
  426. b:=byte(v) and 127;
  427. v:=SarInt64(v,7);
  428. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  429. Done:=true
  430. else
  431. b:=b or 128;
  432. d.write(b,1);
  433. until Done;
  434. end;
  435. procedure TWasmObjOutput.WriteByte(d: tdynamicarray; b: byte);
  436. begin
  437. d.write(b,1);
  438. end;
  439. procedure TWasmObjOutput.WriteName(d: tdynamicarray; const s: string);
  440. begin
  441. WriteUleb(d,Length(s));
  442. d.writestr(s);
  443. end;
  444. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  445. var
  446. b: byte;
  447. begin
  448. b:=ord(wsid);
  449. Writer.write(b,1);
  450. WriteUleb(Writer,FWasmSections[wsid].size);
  451. Writer.writearray(FWasmSections[wsid]);
  452. end;
  453. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  454. var
  455. b: byte;
  456. begin
  457. b:=0;
  458. Writer.write(b,1);
  459. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  460. Writer.writearray(FWasmCustomSections[wcst]);
  461. end;
  462. procedure TWasmObjOutput.CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  463. var
  464. buf: array [0..4095] of byte;
  465. bs: Integer;
  466. begin
  467. while size>0 do
  468. begin
  469. if size<SizeOf(buf) then
  470. bs:=Integer(size)
  471. else
  472. bs:=SizeOf(buf);
  473. src.read(buf,bs);
  474. dest.write(buf,bs);
  475. dec(size,bs);
  476. end;
  477. end;
  478. procedure TWasmObjOutput.WriteZeros(dest: tdynamicarray; size: QWord);
  479. var
  480. buf : array[0..1023] of byte;
  481. bs: Integer;
  482. begin
  483. fillchar(buf,sizeof(buf),0);
  484. while size>0 do
  485. begin
  486. if size<SizeOf(buf) then
  487. bs:=Integer(size)
  488. else
  489. bs:=SizeOf(buf);
  490. dest.write(buf,bs);
  491. dec(size,bs);
  492. end;
  493. end;
  494. procedure TWasmObjOutput.WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  495. var
  496. i: Integer;
  497. begin
  498. WriteUleb(dest,Length(wrt));
  499. for i:=low(wrt) to high(wrt) do
  500. WriteWasmBasicType(dest,wrt[i]);
  501. end;
  502. procedure TWasmObjOutput.WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  503. begin
  504. case wbt of
  505. wbt_i32:
  506. WriteByte(dest,$7F);
  507. wbt_i64:
  508. WriteByte(dest,$7E);
  509. wbt_f32:
  510. WriteByte(dest,$7D);
  511. wbt_f64:
  512. WriteByte(dest,$7C);
  513. end;
  514. end;
  515. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  516. begin
  517. result:=(sym.bind=AB_EXTERNAL) and (TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name)<>nil);
  518. end;
  519. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  520. var
  521. i,
  522. rle_entries,
  523. cnt: Integer;
  524. lasttype: TWasmBasicType;
  525. begin
  526. if Length(ed.Locals)=0 then
  527. begin
  528. WriteUleb(dest,0);
  529. exit;
  530. end;
  531. rle_entries:=1;
  532. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  533. if ed.Locals[i]<>ed.Locals[i-1] then
  534. inc(rle_entries);
  535. WriteUleb(dest,rle_entries);
  536. lasttype:=ed.Locals[Low(ed.Locals)];
  537. cnt:=1;
  538. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  539. if ed.Locals[i]=ed.Locals[i-1] then
  540. inc(cnt)
  541. else
  542. begin
  543. WriteUleb(dest,cnt);
  544. WriteWasmBasicType(dest,lasttype);
  545. lasttype:=ed.Locals[i];
  546. cnt:=1;
  547. end;
  548. WriteUleb(dest,cnt);
  549. WriteWasmBasicType(dest,lasttype);
  550. end;
  551. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  552. var
  553. encoded_locals: tdynamicarray;
  554. ObjSymExtraData: TWasmObjSymbolExtraData;
  555. codelen: LongWord;
  556. ObjSection: TObjSection;
  557. codeexprlen: QWord;
  558. begin
  559. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  560. ObjSection:=objsym.objsection;
  561. ObjSection.Data.seek(objsym.address);
  562. codeexprlen:=ObjSection.Size-objsym.address;
  563. encoded_locals:=tdynamicarray.Create(64);
  564. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  565. codelen:=encoded_locals.size+codeexprlen+1;
  566. WriteUleb(dest,codelen);
  567. encoded_locals.seek(0);
  568. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  569. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  570. WriteByte(dest,$0B);
  571. encoded_locals.Free;
  572. end;
  573. procedure TWasmObjOutput.WriteSymbolTable;
  574. begin
  575. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  576. FWasmSymbolTable.seek(0);
  577. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  578. end;
  579. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  580. begin
  581. if FWasmLinkingSubsections[wlst].size>0 then
  582. begin
  583. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  584. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  585. FWasmLinkingSubsections[wlst].seek(0);
  586. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  587. end;
  588. end;
  589. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  590. var
  591. i: Integer;
  592. objsec: TWasmObjSection;
  593. segment_count: Integer = 0;
  594. cur_seg_ofs: qword = 0;
  595. types_count,
  596. imports_count, NextImportFunctionIndex: Integer;
  597. import_functions_count: Integer = 0;
  598. functions_count: Integer = 0;
  599. objsym: TWasmObjSymbol;
  600. cust_sec: TWasmCustomSectionType;
  601. begin
  602. FData:=TWasmObjData(Data);
  603. { each custom sections starts with its name }
  604. for cust_sec in TWasmCustomSectionType do
  605. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  606. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  607. for i:=0 to Data.ObjSymbolList.Count-1 do
  608. begin
  609. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  610. if IsExternalFunction(objsym) then
  611. Inc(import_functions_count);
  612. if objsym.typ=AT_FUNCTION then
  613. Inc(functions_count);
  614. end;
  615. types_count:=Length(FData.FFuncTypes);
  616. WriteUleb(FWasmSections[wsiType],types_count);
  617. for i:=0 to types_count-1 do
  618. with FData.FFuncTypes[i] do
  619. begin
  620. WriteByte(FWasmSections[wsiType],$60);
  621. WriteWasmResultType(FWasmSections[wsiType],params);
  622. WriteWasmResultType(FWasmSections[wsiType],results);
  623. end;
  624. for i:=0 to Data.ObjSectionList.Count-1 do
  625. begin
  626. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  627. if objsec.IsCode then
  628. objsec.SegIdx:=-1
  629. else
  630. begin
  631. objsec.SegIdx:=segment_count;
  632. objsec.SegOfs:=cur_seg_ofs;
  633. Inc(segment_count);
  634. Inc(cur_seg_ofs,objsec.Size);
  635. end;
  636. end;
  637. WriteUleb(FWasmSections[wsiData],segment_count);
  638. for i:=0 to Data.ObjSectionList.Count-1 do
  639. begin
  640. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  641. if objsec.IsData then
  642. begin
  643. WriteByte(FWasmSections[wsiData],0);
  644. WriteByte(FWasmSections[wsiData],$41);
  645. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  646. WriteByte(FWasmSections[wsiData],$0b);
  647. WriteUleb(FWasmSections[wsiData],objsec.Size);
  648. if oso_Data in objsec.SecOptions then
  649. begin
  650. objsec.Data.seek(0);
  651. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  652. end
  653. else
  654. begin
  655. WriteZeros(FWasmSections[wsiData],objsec.Size);
  656. end;
  657. end;
  658. end;
  659. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  660. imports_count:=3+import_functions_count;
  661. WriteUleb(FWasmSections[wsiImport],imports_count);
  662. { import[0] }
  663. WriteName(FWasmSections[wsiImport],'env');
  664. WriteName(FWasmSections[wsiImport],'__linear_memory');
  665. WriteByte(FWasmSections[wsiImport],$02); { mem }
  666. WriteByte(FWasmSections[wsiImport],$00); { min }
  667. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  668. { import[1] }
  669. WriteName(FWasmSections[wsiImport],'env');
  670. WriteName(FWasmSections[wsiImport],'__stack_pointer');
  671. WriteByte(FWasmSections[wsiImport],$03); { global }
  672. WriteByte(FWasmSections[wsiImport],$7F); { i32 }
  673. WriteByte(FWasmSections[wsiImport],$01); { var }
  674. { import[2]..import[imports_count-2] }
  675. NextImportFunctionIndex:=0;
  676. for i:=0 to Data.ObjSymbolList.Count-1 do
  677. begin
  678. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  679. if IsExternalFunction(objsym) then
  680. begin
  681. objsym.ImportIndex:=NextImportFunctionIndex;
  682. Inc(NextImportFunctionIndex);
  683. WriteName(FWasmSections[wsiImport],'env');
  684. WriteName(FWasmSections[wsiImport],objsym.Name);
  685. WriteByte(FWasmSections[wsiImport],$00); { func }
  686. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  687. end;
  688. end;
  689. { import[imports_count-1] }
  690. WriteName(FWasmSections[wsiImport],'env');
  691. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  692. WriteByte(FWasmSections[wsiImport],$01); { table }
  693. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  694. WriteByte(FWasmSections[wsiImport],$00); { min }
  695. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  696. WriteUleb(FWasmSections[wsiFunction],functions_count);
  697. WriteUleb(FWasmSections[wsiCode],functions_count);
  698. for i:=0 to Data.ObjSymbolList.Count-1 do
  699. begin
  700. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  701. if objsym.typ=AT_FUNCTION then
  702. begin
  703. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  704. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  705. end;
  706. end;
  707. for i:=0 to Data.ObjSymbolList.Count-1 do
  708. begin
  709. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  710. if IsExternalFunction(objsym) then
  711. begin
  712. Inc(FWasmSymbolTableEntriesCount);
  713. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  714. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  715. WriteUleb(FWasmSymbolTable,objsym.ImportIndex);
  716. end
  717. else if objsym.typ=AT_FUNCTION then
  718. begin
  719. end;
  720. end;
  721. WriteSymbolTable;
  722. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  723. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  724. Writer.write(WasmVersion,SizeOf(WasmVersion));
  725. WriteWasmSection(wsiType);
  726. WriteWasmSection(wsiImport);
  727. WriteWasmSection(wsiFunction);
  728. WriteWasmSection(wsiDataCount);
  729. WriteWasmSection(wsiCode);
  730. WriteWasmSection(wsiData);
  731. WriteWasmCustomSection(wcstLinking);
  732. Writeln('ObjSymbolList:');
  733. for i:=0 to Data.ObjSymbolList.Count-1 do
  734. begin
  735. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  736. Write(objsym.Name, ' bind=', objsym.Bind, ' typ=', objsym.typ, ' address=', objsym.address, ' objsection=');
  737. if assigned(objsym.objsection) then
  738. Write(objsym.objsection.Name)
  739. else
  740. Write('nil');
  741. Writeln;
  742. end;
  743. Writeln('ObjSectionList:');
  744. for i:=0 to Data.ObjSectionList.Count-1 do
  745. begin
  746. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  747. Writeln(objsec.Name, ' IsCode=', objsec.IsCode, ' IsData=', objsec.IsData, ' Size=', objsec.Size, ' MemPos=', objsec.MemPos, ' DataPos=', objsec.DataPos, ' SegIdx=', objsec.SegIdx);
  748. end;
  749. result:=true;
  750. end;
  751. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  752. var
  753. i: TWasmSectionID;
  754. j: TWasmCustomSectionType;
  755. k: TWasmLinkingSubsectionType;
  756. begin
  757. inherited;
  758. cobjdata:=TWasmObjData;
  759. for i in TWasmSectionID do
  760. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  761. for j in TWasmCustomSectionType do
  762. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  763. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  764. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  765. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  766. FWasmSymbolTableEntriesCount:=0;
  767. end;
  768. destructor TWasmObjOutput.destroy;
  769. var
  770. i: TWasmSectionID;
  771. j: TWasmCustomSectionType;
  772. k: TWasmLinkingSubsectionType;
  773. begin
  774. for i in TWasmSectionID do
  775. FWasmSections[i].Free;
  776. for j in TWasmCustomSectionType do
  777. FWasmCustomSections[j].Free;
  778. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  779. FWasmLinkingSubsections[k].Free;
  780. FWasmSymbolTable.Free;
  781. inherited destroy;
  782. end;
  783. {****************************************************************************
  784. TWasmAssembler
  785. ****************************************************************************}
  786. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  787. begin
  788. inherited;
  789. CObjOutput:=TWasmObjOutput;
  790. end;
  791. {*****************************************************************************
  792. Initialize
  793. *****************************************************************************}
  794. {$ifdef wasm32}
  795. const
  796. as_wasm32_wasm_info : tasminfo =
  797. (
  798. id : as_wasm32_wasm;
  799. idtxt : 'OMF';
  800. asmbin : '';
  801. asmcmd : '';
  802. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  803. flags : [af_outputbinary,af_smartlink_sections];
  804. labelprefix : '..@';
  805. labelmaxlen : -1;
  806. comment : '; ';
  807. dollarsign: '$';
  808. );
  809. {$endif wasm32}
  810. initialization
  811. {$ifdef wasm32}
  812. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  813. {$endif wasm32}
  814. end.