ogwasm.pas 58 KB

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