ogwasm.pas 32 KB

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