ogwasm.pas 26 KB

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