ogwasm.pas 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872
  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. TagIndex: Integer;
  40. AliasOf: string;
  41. ExtraData: TWasmObjSymbolExtraData;
  42. constructor create(AList:TFPHashObjectList;const AName:string);override;
  43. function IsAlias: Boolean;
  44. end;
  45. { TWasmObjRelocation }
  46. TWasmObjRelocation = class(TObjRelocation)
  47. public
  48. TypeIndex: Integer;
  49. Addend: LongInt;
  50. constructor CreateTypeIndex(ADataOffset:TObjSectionOfs; ATypeIndex: Integer);
  51. end;
  52. { TWasmObjSymbolExtraData }
  53. TWasmObjSymbolExtraData = class(TFPHashObject)
  54. TypeIdx: Integer;
  55. ExceptionTagTypeIdx: Integer;
  56. ImportModule: string;
  57. ImportName: string;
  58. ExportName: string;
  59. GlobalType: TWasmBasicType;
  60. GlobalIsImmutable: Boolean;
  61. Locals: array of TWasmBasicType;
  62. constructor Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  63. procedure AddLocal(bastyp: TWasmBasicType);
  64. end;
  65. { TWasmObjSection }
  66. TWasmObjSection = class(TObjSection)
  67. public
  68. SegIdx: Integer;
  69. SegSymIdx: Integer;
  70. SegOfs: qword;
  71. FileSectionOfs: qword;
  72. MainFuncSymbol: TWasmObjSymbol;
  73. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:longint;Aoptions:TObjSectionOptions);override;
  74. function IsCode: Boolean;
  75. function IsData: Boolean;
  76. function IsDebug: Boolean;
  77. end;
  78. { TWasmObjData }
  79. TWasmObjData = class(TObjData)
  80. private
  81. FFuncTypes: array of TWasmFuncType;
  82. FObjSymbolsExtraDataList: TFPHashObjectList;
  83. FLastFuncName: string;
  84. function is_smart_section(atype:TAsmSectiontype):boolean;
  85. function sectionname_gas(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  86. public
  87. constructor create(const n:string);override;
  88. destructor destroy; override;
  89. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  90. procedure writeReloc(Data:TRelocDataInt;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);override;
  91. function AddOrCreateObjSymbolExtraData(const symname:TSymStr): TWasmObjSymbolExtraData;
  92. function AddFuncType(wft: TWasmFuncType): integer;
  93. function globalref(asmsym:TAsmSymbol):TObjSymbol;
  94. function ExceptionTagRef(asmsym:TAsmSymbol):TObjSymbol;
  95. procedure DeclareGlobalType(gt: tai_globaltype);
  96. procedure DeclareFuncType(ft: tai_functype);
  97. procedure DeclareTagType(tt: tai_tagtype);
  98. procedure DeclareExportName(en: tai_export_name);
  99. procedure DeclareImportModule(aim: tai_import_module);
  100. procedure DeclareImportName(ain: tai_import_name);
  101. procedure DeclareLocal(al: tai_local);
  102. procedure symbolpairdefine(akind: TSymbolPairKind;const asym, avalue: string);override;
  103. end;
  104. { TWasmObjOutput }
  105. TWasmObjOutput = class(tObjOutput)
  106. private
  107. FData: TWasmObjData;
  108. FWasmRelocationCodeTable: tdynamicarray;
  109. FWasmRelocationCodeTableEntriesCount: Integer;
  110. FWasmRelocationDataTable: tdynamicarray;
  111. FWasmRelocationDataTableEntriesCount: Integer;
  112. FWasmRelocationDebugFrameTable: tdynamicarray;
  113. FWasmRelocationDebugFrameTableEntriesCount: Integer;
  114. FWasmRelocationDebugInfoTable: tdynamicarray;
  115. FWasmRelocationDebugInfoTableEntriesCount: Integer;
  116. FWasmRelocationDebugLineTable: tdynamicarray;
  117. FWasmRelocationDebugLineTableEntriesCount: Integer;
  118. FWasmRelocationDebugAbbrevTable: tdynamicarray;
  119. FWasmRelocationDebugAbbrevTableEntriesCount: Integer;
  120. FWasmRelocationDebugArangesTable: tdynamicarray;
  121. FWasmRelocationDebugArangesTableEntriesCount: Integer;
  122. FWasmRelocationDebugRangesTable: tdynamicarray;
  123. FWasmRelocationDebugRangesTableEntriesCount: Integer;
  124. FWasmRelocationDebugStrTable: tdynamicarray;
  125. FWasmRelocationDebugStrTableEntriesCount: Integer;
  126. FWasmSymbolTable: tdynamicarray;
  127. FWasmSymbolTableEntriesCount: Integer;
  128. FWasmSections: array [TWasmSectionID] of tdynamicarray;
  129. FWasmCustomSections: array [TWasmCustomSectionType] of tdynamicarray;
  130. FWasmLinkingSubsections: array [low(TWasmLinkingSubsectionType)..high(TWasmLinkingSubsectionType)] of tdynamicarray;
  131. procedure WriteUleb(d: tdynamicarray; v: uint64);
  132. procedure WriteUleb(w: TObjectWriter; v: uint64);
  133. procedure WriteSleb(d: tdynamicarray; v: int64);
  134. procedure WriteByte(d: tdynamicarray; b: byte);
  135. procedure WriteName(d: tdynamicarray; const s: string);
  136. procedure WriteWasmSection(wsid: TWasmSectionID);
  137. procedure WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  138. procedure CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  139. procedure WriteZeros(dest: tdynamicarray; size: QWord);
  140. procedure WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  141. procedure WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  142. function IsExternalFunction(sym: TObjSymbol): Boolean;
  143. function IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  144. procedure WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  145. procedure WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  146. procedure WriteSymbolTable;
  147. procedure WriteRelocationCodeTable(CodeSectionIndex: Integer);
  148. procedure WriteRelocationDataTable(DataSectionIndex: Integer);
  149. procedure MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  150. procedure WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  151. procedure DoRelocations;
  152. procedure WriteRelocations;
  153. function FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  154. protected
  155. function writeData(Data:TObjData):boolean;override;
  156. public
  157. constructor create(AWriter:TObjectWriter);override;
  158. destructor destroy;override;
  159. end;
  160. { TWasmObjInput }
  161. TWasmObjInput = class(TObjInput)
  162. private
  163. FFuncTypes: array of TWasmFuncType;
  164. public
  165. constructor create;override;
  166. destructor Destroy;override;
  167. class function CanReadObjData(AReader:TObjectreader):boolean;override;
  168. function ReadObjData(AReader:TObjectreader;out ObjData:TObjData):boolean;override;
  169. end;
  170. { TWasmExeOutput }
  171. TWasmExeOutput = class(TExeOutput)
  172. protected
  173. function writeData:boolean;override;
  174. procedure DoRelocationFixup(objsec:TObjSection);override;
  175. public
  176. constructor create;override;
  177. end;
  178. { TWasmAssembler }
  179. TWasmAssembler = class(tinternalassembler)
  180. constructor create(info: pasminfo; smart:boolean);override;
  181. end;
  182. implementation
  183. uses
  184. cutils,verbose,version,globals;
  185. procedure WriteUleb5(d: tdynamicarray; v: uint64);
  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:=v shr 7;
  194. if i<>5 then
  195. b:=b or 128;
  196. d.write(b,1);
  197. end;
  198. end;
  199. procedure WriteUleb5(d: tobjsection; v: uint64);
  200. var
  201. b: byte;
  202. i: Integer;
  203. begin
  204. for i:=1 to 5 do
  205. begin
  206. b:=byte(v) and 127;
  207. v:=v shr 7;
  208. if i<>5 then
  209. b:=b or 128;
  210. d.write(b,1);
  211. end;
  212. end;
  213. procedure WriteSleb5(d: tdynamicarray; v: int64);
  214. var
  215. b: byte;
  216. i: Integer;
  217. begin
  218. for i:=1 to 5 do
  219. begin
  220. b:=byte(v) and 127;
  221. v:=SarInt64(v,7);
  222. if i<>5 then
  223. b:=b or 128;
  224. d.write(b,1);
  225. end;
  226. end;
  227. procedure WriteSleb5(d: tobjsection; v: int64);
  228. var
  229. b: byte;
  230. i: Integer;
  231. begin
  232. for i:=1 to 5 do
  233. begin
  234. b:=byte(v) and 127;
  235. v:=SarInt64(v,7);
  236. if i<>5 then
  237. b:=b or 128;
  238. d.write(b,1);
  239. end;
  240. end;
  241. function ReadUleb(d: tdynamicarray): uint64;
  242. var
  243. b: byte;
  244. shift:integer;
  245. begin
  246. b:=0;
  247. result:=0;
  248. shift:=0;
  249. repeat
  250. d.read(b,1);
  251. result:=result or (uint64(b and 127) shl shift);
  252. inc(shift,7);
  253. until (b and 128)=0;
  254. end;
  255. function ReadSleb(d: tdynamicarray): int64;
  256. var
  257. b: byte;
  258. shift:integer;
  259. begin
  260. b:=0;
  261. result:=0;
  262. shift:=0;
  263. repeat
  264. d.read(b,1);
  265. result:=result or (uint64(b and 127) shl shift);
  266. inc(shift,7);
  267. until (b and 128)=0;
  268. {$ifopt Q+}
  269. {$define overflowon}
  270. {$Q-}
  271. {$endif}
  272. {$ifopt R+}
  273. {$define rangeon}
  274. {$R-}
  275. {$endif}
  276. if (b and 64)<>0 then
  277. result:=result or (high(uint64) shl shift);
  278. end;
  279. {$ifdef overflowon}
  280. {$Q+}
  281. {$undef overflowon}
  282. {$endif}
  283. {$ifdef rangeon}
  284. {$R+}
  285. {$undef rangeon}
  286. {$endif}
  287. procedure AddSleb5(d: tdynamicarray; v: int64);
  288. var
  289. q: Int64;
  290. p: LongWord;
  291. begin
  292. p:=d.Pos;
  293. q:=ReadSleb(d);
  294. q:=q+v;
  295. d.seek(p);
  296. WriteSleb5(d,q);
  297. end;
  298. procedure AddUleb5(d: tdynamicarray; v: int64);
  299. var
  300. q: UInt64;
  301. p: LongWord;
  302. begin
  303. p:=d.Pos;
  304. q:=ReadUleb(d);
  305. q:=q+v;
  306. d.seek(p);
  307. WriteUleb5(d,q);
  308. end;
  309. procedure AddInt32(d: tdynamicarray; v: int32);
  310. var
  311. q: int32;
  312. p: LongWord;
  313. begin
  314. p:=d.Pos;
  315. d.read(q,4);
  316. {$ifdef FPC_BIG_ENDIAN}
  317. q:=SwapEndian(q);
  318. {$endif FPC_BIG_ENDIAN}
  319. q:=q+v;
  320. {$ifdef FPC_BIG_ENDIAN}
  321. q:=SwapEndian(q);
  322. {$endif FPC_BIG_ENDIAN}
  323. d.seek(p);
  324. d.write(q,4);
  325. end;
  326. {****************************************************************************
  327. TWasmObjRelocation
  328. ****************************************************************************}
  329. constructor TWasmObjRelocation.CreateTypeIndex(ADataOffset: TObjSectionOfs; ATypeIndex: Integer);
  330. begin
  331. DataOffset:=ADataOffset;
  332. Symbol:=nil;
  333. OrgSize:=0;
  334. Group:=nil;
  335. ObjSection:=nil;
  336. ftype:=ord(RELOC_TYPE_INDEX_LEB);
  337. TypeIndex:=ATypeIndex;
  338. end;
  339. {****************************************************************************
  340. TWasmObjSymbol
  341. ****************************************************************************}
  342. constructor TWasmObjSymbol.create(AList: TFPHashObjectList; const AName: string);
  343. begin
  344. inherited create(AList,AName);
  345. FuncIndex:=-1;
  346. SymbolIndex:=-1;
  347. GlobalIndex:=-1;
  348. TagIndex:=-1;
  349. AliasOf:='';
  350. ExtraData:=nil;
  351. end;
  352. function TWasmObjSymbol.IsAlias: Boolean;
  353. begin
  354. result:=AliasOf<>'';
  355. end;
  356. {****************************************************************************
  357. TWasmObjSymbolExtraData
  358. ****************************************************************************}
  359. constructor TWasmObjSymbolExtraData.Create(HashObjectList: TFPHashObjectList; const s: TSymStr);
  360. begin
  361. inherited Create(HashObjectList,s);
  362. TypeIdx:=-1;
  363. ExceptionTagTypeIdx:=-1;
  364. end;
  365. procedure TWasmObjSymbolExtraData.AddLocal(bastyp: TWasmBasicType);
  366. begin
  367. SetLength(Locals,Length(Locals)+1);
  368. Locals[High(Locals)]:=bastyp;
  369. end;
  370. {****************************************************************************
  371. TWasmObjSection
  372. ****************************************************************************}
  373. constructor TWasmObjSection.create(AList: TFPHashObjectList; const Aname: string; Aalign: longint; Aoptions: TObjSectionOptions);
  374. begin
  375. inherited create(AList, Aname, Aalign, Aoptions);
  376. SegIdx:=-1;
  377. SegSymIdx:=-1;
  378. MainFuncSymbol:=nil;
  379. end;
  380. function TWasmObjSection.IsCode: Boolean;
  381. const
  382. CodePrefix = '.text';
  383. begin
  384. result:=(Length(Name)>=Length(CodePrefix)) and
  385. (Copy(Name,1,Length(CodePrefix))=CodePrefix);
  386. end;
  387. function TWasmObjSection.IsData: Boolean;
  388. begin
  389. result:=not (IsCode or IsDebug);
  390. end;
  391. function TWasmObjSection.IsDebug: Boolean;
  392. const
  393. DebugPrefix = '.debug';
  394. begin
  395. result:=(Length(Name)>=Length(DebugPrefix)) and
  396. (Copy(Name,1,Length(DebugPrefix))=DebugPrefix);
  397. end;
  398. {****************************************************************************
  399. TWasmObjData
  400. ****************************************************************************}
  401. function TWasmObjData.is_smart_section(atype: TAsmSectiontype): boolean;
  402. begin
  403. { For bss we need to set some flags that are target dependent,
  404. it is easier to disable it for smartlinking. It doesn't take up
  405. filespace }
  406. result:=not(target_info.system in systems_darwin) and
  407. create_smartlink_sections and
  408. (atype<>sec_toc) and
  409. (atype<>sec_user) and
  410. { on embedded systems every byte counts, so smartlink bss too }
  411. ((atype<>sec_bss) or (target_info.system in (systems_embedded+systems_freertos)));
  412. end;
  413. function TWasmObjData.sectionname_gas(atype: TAsmSectiontype;
  414. const aname: string; aorder: TAsmSectionOrder): string;
  415. const
  416. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  417. '.text',
  418. '.data',
  419. { why doesn't .rodata work? (FK) }
  420. { sometimes we have to create a data.rel.ro instead of .rodata, e.g. for }
  421. { vtables (and anything else containing relocations), otherwise those are }
  422. { not relocated properly on e.g. linux/ppc64. g++ generates there for a }
  423. { vtable for a class called Window: }
  424. { .section .data.rel.ro._ZTV6Window,"awG",@progbits,_ZTV6Window,comdat }
  425. { TODO: .data.ro not yet working}
  426. {$if defined(arm) or defined(riscv64) or defined(powerpc)}
  427. '.rodata',
  428. {$else defined(arm) or defined(riscv64) or defined(powerpc)}
  429. '.data',
  430. {$endif defined(arm) or defined(riscv64) or defined(powerpc)}
  431. '.rodata',
  432. '.bss',
  433. '.tbss',
  434. '.pdata',
  435. '', { stubs }
  436. '__DATA,__nl_symbol_ptr',
  437. '__DATA,__la_symbol_ptr',
  438. '__DATA,__mod_init_func',
  439. '__DATA,__mod_term_func',
  440. '.stab',
  441. '.stabstr',
  442. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  443. '.eh_frame',
  444. '.debug_frame','.debug_info','.debug_line','.debug_abbrev','.debug_aranges','.debug_ranges',
  445. '.fpc',
  446. '.toc',
  447. '.init',
  448. '.fini',
  449. '.objc_class',
  450. '.objc_meta_class',
  451. '.objc_cat_cls_meth',
  452. '.objc_cat_inst_meth',
  453. '.objc_protocol',
  454. '.objc_string_object',
  455. '.objc_cls_meth',
  456. '.objc_inst_meth',
  457. '.objc_cls_refs',
  458. '.objc_message_refs',
  459. '.objc_symbols',
  460. '.objc_category',
  461. '.objc_class_vars',
  462. '.objc_instance_vars',
  463. '.objc_module_info',
  464. '.objc_class_names',
  465. '.objc_meth_var_types',
  466. '.objc_meth_var_names',
  467. '.objc_selector_strs',
  468. '.objc_protocol_ext',
  469. '.objc_class_ext',
  470. '.objc_property',
  471. '.objc_image_info',
  472. '.objc_cstring_object',
  473. '.objc_sel_fixup',
  474. '__DATA,__objc_data',
  475. '__DATA,__objc_const',
  476. '.objc_superrefs',
  477. '__DATA, __datacoal_nt,coalesced',
  478. '.objc_classlist',
  479. '.objc_nlclasslist',
  480. '.objc_catlist',
  481. '.obcj_nlcatlist',
  482. '.objc_protolist',
  483. '.stack',
  484. '.heap',
  485. '.gcc_except_table',
  486. '.ARM.attributes'
  487. );
  488. var
  489. sep : string[3];
  490. secname : string;
  491. begin
  492. secname:=secnames[atype];
  493. if (atype=sec_fpc) and (Copy(aname,1,3)='res') then
  494. begin
  495. result:=secname+'.'+aname;
  496. exit;
  497. end;
  498. { go32v2 stub only loads .text and .data sections, and allocates space for .bss.
  499. Thus, data which normally goes into .rodata and .rodata_norel sections must
  500. end up in .data section }
  501. if (atype in [sec_rodata,sec_rodata_norel]) and
  502. (target_info.system in [system_i386_go32v2,system_m68k_palmos]) then
  503. secname:='.data';
  504. { Windows correctly handles reallocations in readonly sections }
  505. if (atype=sec_rodata) and
  506. (target_info.system in systems_all_windows+systems_nativent-[system_i8086_win16]) then
  507. secname:='.rodata';
  508. { section type user gives the user full controll on the section name }
  509. if atype=sec_user then
  510. secname:=aname;
  511. if is_smart_section(atype) and (aname<>'') then
  512. begin
  513. case aorder of
  514. secorder_begin :
  515. sep:='.b_';
  516. secorder_end :
  517. sep:='.z_';
  518. else
  519. sep:='.n_';
  520. end;
  521. result:=secname+sep+aname
  522. end
  523. else
  524. result:=secname;
  525. end;
  526. constructor TWasmObjData.create(const n: string);
  527. begin
  528. inherited;
  529. CObjSection:=TWasmObjSection;
  530. CObjSymbol:=TWasmObjSymbol;
  531. FObjSymbolsExtraDataList:=TFPHashObjectList.Create;
  532. end;
  533. destructor TWasmObjData.destroy;
  534. var
  535. i: Integer;
  536. begin
  537. FObjSymbolsExtraDataList.Free;
  538. for i:=low(FFuncTypes) to high(FFuncTypes) do
  539. begin
  540. FFuncTypes[i].free;
  541. FFuncTypes[i]:=nil;
  542. end;
  543. inherited destroy;
  544. end;
  545. function TWasmObjData.sectionname(atype: TAsmSectiontype;
  546. const aname: string; aorder: TAsmSectionOrder): string;
  547. begin
  548. if (atype=sec_fpc) or
  549. ((atype=sec_threadvar) and not (ts_wasm_threads in current_settings.targetswitches)) then
  550. atype:=sec_data;
  551. Result:=sectionname_gas(atype, aname, aorder);
  552. end;
  553. procedure TWasmObjData.writeReloc(Data: TRelocDataInt; len: aword;
  554. p: TObjSymbol; Reloctype: TObjRelocationType);
  555. const
  556. leb_zero: array[0..4] of byte=($80,$80,$80,$80,$00);
  557. var
  558. objreloc: TWasmObjRelocation;
  559. begin
  560. if CurrObjSec=nil then
  561. internalerror(200403072);
  562. { workaround crash, when generating debug info for threadvars, when multithreading is turned off.
  563. todo: ensure the debug info for threadvars is actually correct, once we've got WebAssembly debug info working in general }
  564. if (Reloctype=RELOC_DTPOFF) and not (ts_wasm_threads in current_settings.targetswitches) then
  565. Reloctype:=RELOC_ABSOLUTE;
  566. objreloc:=nil;
  567. case Reloctype of
  568. RELOC_FUNCTION_INDEX_LEB:
  569. begin
  570. if Data<>0 then
  571. internalerror(2021092502);
  572. if len<>5 then
  573. internalerror(2021092503);
  574. if not assigned(p) then
  575. internalerror(2021092504);
  576. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  577. CurrObjSec.ObjRelocations.Add(objreloc);
  578. writebytes(leb_zero,5);
  579. end;
  580. RELOC_MEMORY_ADDR_LEB,
  581. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  582. begin
  583. if (Reloctype=RELOC_MEMORY_ADDR_LEB) and (Data<0) then
  584. internalerror(2021092602);
  585. if len<>5 then
  586. internalerror(2021092503);
  587. if not assigned(p) then
  588. internalerror(2021092504);
  589. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  590. objreloc.Addend:=Data;
  591. CurrObjSec.ObjRelocations.Add(objreloc);
  592. if RelocType=RELOC_MEMORY_ADDR_LEB then
  593. WriteUleb5(CurrObjSec,Data)
  594. else
  595. WriteSleb5(CurrObjSec,Data);
  596. end;
  597. RELOC_ABSOLUTE:
  598. begin
  599. if len<>4 then
  600. internalerror(2021092607);
  601. if not assigned(p) then
  602. internalerror(2021092608);
  603. if (p.objsection<>nil) and TWasmObjSection(p.objsection).IsDebug and
  604. (p.bind<>AB_COMMON) and (p.bind<>AB_EXTERNAL) then
  605. begin
  606. objreloc:=TWasmObjRelocation.CreateSection(CurrObjSec.Size,p.objsection,RELOC_ABSOLUTE);
  607. objreloc.Addend:=Data+p.Address;
  608. CurrObjSec.ObjRelocations.Add(objreloc);
  609. {inc(data,p.address);}
  610. data:=0;
  611. Data:=NtoLE(Data);
  612. writebytes(Data,4);
  613. end
  614. else
  615. begin
  616. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  617. objreloc.Addend:=Data;
  618. CurrObjSec.ObjRelocations.Add(objreloc);
  619. Data:=NtoLE(Data);
  620. writebytes(Data,4);
  621. end;
  622. end;
  623. RELOC_TYPE_INDEX_LEB:
  624. begin
  625. if len<>5 then
  626. internalerror(2021092612);
  627. if assigned(p) then
  628. internalerror(2021092613);
  629. objreloc:=TWasmObjRelocation.CreateTypeIndex(CurrObjSec.Size,Data);
  630. CurrObjSec.ObjRelocations.Add(objreloc);
  631. WriteUleb5(CurrObjSec,Data);
  632. end;
  633. RELOC_GLOBAL_INDEX_LEB:
  634. begin
  635. if len<>5 then
  636. internalerror(2021092701);
  637. if Data<>0 then
  638. internalerror(2021092702);
  639. if not assigned(p) then
  640. internalerror(2021092703);
  641. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  642. CurrObjSec.ObjRelocations.Add(objreloc);
  643. WriteUleb5(CurrObjSec,0);
  644. end;
  645. RELOC_TAG_INDEX_LEB:
  646. begin
  647. if len<>5 then
  648. internalerror(2021092712);
  649. if Data<>0 then
  650. internalerror(2021092713);
  651. if not assigned(p) then
  652. internalerror(2021092714);
  653. objreloc:=TWasmObjRelocation.CreateSymbol(CurrObjSec.Size,p,Reloctype);
  654. CurrObjSec.ObjRelocations.Add(objreloc);
  655. WriteSleb5(CurrObjSec,0);
  656. end;
  657. else
  658. internalerror(2021092501);
  659. end;
  660. end;
  661. function TWasmObjData.AddOrCreateObjSymbolExtraData(const symname: TSymStr): TWasmObjSymbolExtraData;
  662. begin
  663. result:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(symname));
  664. if not assigned(result) then
  665. result:=TWasmObjSymbolExtraData.Create(FObjSymbolsExtraDataList,symname);
  666. end;
  667. function TWasmObjData.AddFuncType(wft: TWasmFuncType): integer;
  668. var
  669. i: Integer;
  670. begin
  671. for i:=low(FFuncTypes) to high(FFuncTypes) do
  672. if wft.Equals(FFuncTypes[i]) then
  673. exit(i);
  674. result:=Length(FFuncTypes);
  675. SetLength(FFuncTypes,result+1);
  676. FFuncTypes[result]:=TWasmFuncType.Create(wft);
  677. end;
  678. function TWasmObjData.globalref(asmsym: TAsmSymbol): TObjSymbol;
  679. begin
  680. if assigned(asmsym) then
  681. begin
  682. if (asmsym.typ<>AT_WASM_GLOBAL) and (asmsym.typ<>AT_TLS) then
  683. internalerror(2021092706);
  684. result:=symbolref(asmsym);
  685. result.typ:=asmsym.typ;
  686. end
  687. else
  688. result:=nil;
  689. end;
  690. function TWasmObjData.ExceptionTagRef(asmsym: TAsmSymbol): TObjSymbol;
  691. begin
  692. if assigned(asmsym) then
  693. begin
  694. if asmsym.typ<>AT_WASM_EXCEPTION_TAG then
  695. internalerror(2021092707);
  696. result:=symbolref(asmsym);
  697. result.typ:=AT_WASM_EXCEPTION_TAG;
  698. end
  699. else
  700. result:=nil;
  701. end;
  702. procedure TWasmObjData.DeclareGlobalType(gt: tai_globaltype);
  703. var
  704. ObjSymExtraData: TWasmObjSymbolExtraData;
  705. ObjSym: TObjSymbol;
  706. begin
  707. if not gt.is_external then
  708. begin
  709. ObjSym:=symboldefine(gt.sym);
  710. ObjSym.typ:=AT_WASM_GLOBAL;
  711. end;
  712. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(gt.globalname);
  713. ObjSymExtraData.GlobalType:=gt.gtype;
  714. ObjSymExtraData.GlobalIsImmutable:=gt.immutable;
  715. end;
  716. procedure TWasmObjData.DeclareFuncType(ft: tai_functype);
  717. var
  718. i: Integer;
  719. ObjSymExtraData: TWasmObjSymbolExtraData;
  720. begin
  721. FLastFuncName:=ft.funcname;
  722. i:=AddFuncType(ft.functype);
  723. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ft.funcname);
  724. ObjSymExtraData.TypeIdx:=i;
  725. end;
  726. procedure TWasmObjData.DeclareTagType(tt: tai_tagtype);
  727. var
  728. ObjSymExtraData: TWasmObjSymbolExtraData;
  729. ft: TWasmFuncType;
  730. i: Integer;
  731. begin
  732. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(tt.tagname);
  733. ft:=TWasmFuncType.Create([],tt.params);
  734. i:=AddFuncType(ft);
  735. ft.free;
  736. ObjSymExtraData.ExceptionTagTypeIdx:=i;
  737. end;
  738. procedure TWasmObjData.DeclareExportName(en: tai_export_name);
  739. var
  740. ObjSymExtraData: TWasmObjSymbolExtraData;
  741. begin
  742. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(en.intname);
  743. ObjSymExtraData.ExportName:=en.extname;
  744. end;
  745. procedure TWasmObjData.DeclareImportModule(aim: tai_import_module);
  746. var
  747. ObjSymExtraData: TWasmObjSymbolExtraData;
  748. begin
  749. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(aim.symname);
  750. ObjSymExtraData.ImportModule:=aim.importmodule;
  751. end;
  752. procedure TWasmObjData.DeclareImportName(ain: tai_import_name);
  753. var
  754. ObjSymExtraData: TWasmObjSymbolExtraData;
  755. begin
  756. ObjSymExtraData:=AddOrCreateObjSymbolExtraData(ain.symname);
  757. ObjSymExtraData.ImportName:=ain.importname;
  758. end;
  759. procedure TWasmObjData.DeclareLocal(al: tai_local);
  760. var
  761. ObjSymExtraData: TWasmObjSymbolExtraData;
  762. begin
  763. ObjSymExtraData:=TWasmObjSymbolExtraData(FObjSymbolsExtraDataList.Find(FLastFuncName));
  764. ObjSymExtraData.AddLocal(al.bastyp);
  765. end;
  766. procedure TWasmObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  767. var
  768. valsym: TObjSymbol;
  769. aliassym: TWasmObjSymbol;
  770. begin
  771. valsym:=CreateSymbol(avalue);
  772. aliassym:=TWasmObjSymbol(symboldefine(asym,valsym.bind,valsym.typ));
  773. aliassym.AliasOf:=valsym.Name;
  774. end;
  775. {****************************************************************************
  776. TWasmObjOutput
  777. ****************************************************************************}
  778. procedure TWasmObjOutput.WriteUleb(d: tdynamicarray; v: uint64);
  779. var
  780. b: byte;
  781. begin
  782. repeat
  783. b:=byte(v) and 127;
  784. v:=v shr 7;
  785. if v<>0 then
  786. b:=b or 128;
  787. d.write(b,1);
  788. until v=0;
  789. end;
  790. procedure TWasmObjOutput.WriteUleb(w: TObjectWriter; v: uint64);
  791. var
  792. b: byte;
  793. begin
  794. repeat
  795. b:=byte(v) and 127;
  796. v:=v shr 7;
  797. if v<>0 then
  798. b:=b or 128;
  799. w.write(b,1);
  800. until v=0;
  801. end;
  802. procedure TWasmObjOutput.WriteSleb(d: tdynamicarray; v: int64);
  803. var
  804. b: byte;
  805. Done: Boolean=false;
  806. begin
  807. repeat
  808. b:=byte(v) and 127;
  809. v:=SarInt64(v,7);
  810. if ((v=0) and ((b and 64)=0)) or ((v=-1) and ((b and 64)<>0)) then
  811. Done:=true
  812. else
  813. b:=b or 128;
  814. d.write(b,1);
  815. until Done;
  816. end;
  817. procedure TWasmObjOutput.WriteByte(d: tdynamicarray; b: byte);
  818. begin
  819. d.write(b,1);
  820. end;
  821. procedure TWasmObjOutput.WriteName(d: tdynamicarray; const s: string);
  822. begin
  823. WriteUleb(d,Length(s));
  824. d.writestr(s);
  825. end;
  826. procedure TWasmObjOutput.WriteWasmSection(wsid: TWasmSectionID);
  827. var
  828. b: byte;
  829. begin
  830. b:=ord(wsid);
  831. Writer.write(b,1);
  832. WriteUleb(Writer,FWasmSections[wsid].size);
  833. Writer.writearray(FWasmSections[wsid]);
  834. end;
  835. procedure TWasmObjOutput.WriteWasmCustomSection(wcst: TWasmCustomSectionType);
  836. var
  837. b: byte;
  838. begin
  839. b:=0;
  840. Writer.write(b,1);
  841. WriteUleb(Writer,FWasmCustomSections[wcst].size);
  842. Writer.writearray(FWasmCustomSections[wcst]);
  843. end;
  844. procedure TWasmObjOutput.CopyDynamicArray(src, dest: tdynamicarray; size: QWord);
  845. var
  846. buf: array [0..4095] of byte;
  847. bs: Integer;
  848. begin
  849. while size>0 do
  850. begin
  851. if size<SizeOf(buf) then
  852. bs:=Integer(size)
  853. else
  854. bs:=SizeOf(buf);
  855. src.read(buf,bs);
  856. dest.write(buf,bs);
  857. dec(size,bs);
  858. end;
  859. end;
  860. procedure TWasmObjOutput.WriteZeros(dest: tdynamicarray; size: QWord);
  861. var
  862. buf : array[0..1023] of byte;
  863. bs: Integer;
  864. begin
  865. fillchar(buf,sizeof(buf),0);
  866. while size>0 do
  867. begin
  868. if size<SizeOf(buf) then
  869. bs:=Integer(size)
  870. else
  871. bs:=SizeOf(buf);
  872. dest.write(buf,bs);
  873. dec(size,bs);
  874. end;
  875. end;
  876. procedure TWasmObjOutput.WriteWasmResultType(dest: tdynamicarray; wrt: TWasmResultType);
  877. var
  878. i: Integer;
  879. begin
  880. WriteUleb(dest,Length(wrt));
  881. for i:=low(wrt) to high(wrt) do
  882. WriteWasmBasicType(dest,wrt[i]);
  883. end;
  884. procedure TWasmObjOutput.WriteWasmBasicType(dest: tdynamicarray; wbt: TWasmBasicType);
  885. begin
  886. WriteByte(dest,encode_wasm_basic_type(wbt));
  887. end;
  888. function TWasmObjOutput.IsExternalFunction(sym: TObjSymbol): Boolean;
  889. var
  890. ExtraData: TWasmObjSymbolExtraData;
  891. begin
  892. if sym.bind=AB_EXTERNAL then
  893. begin
  894. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  895. result:=(ExtraData<>nil) and (ExtraData.TypeIdx<>-1);
  896. end
  897. else
  898. result:=false;
  899. end;
  900. function TWasmObjOutput.IsExportedFunction(sym: TWasmObjSymbol): Boolean;
  901. var
  902. ExtraData: TWasmObjSymbolExtraData;
  903. begin
  904. if (sym.typ=AT_FUNCTION) and not sym.IsAlias then
  905. begin
  906. ExtraData:=TWasmObjSymbolExtraData(TWasmObjData(sym.ObjData).FObjSymbolsExtraDataList.Find(sym.Name));
  907. result:=(ExtraData<>nil) and (ExtraData.ExportName<>'');
  908. end
  909. else
  910. result:=false;
  911. end;
  912. procedure TWasmObjOutput.WriteFunctionLocals(dest: tdynamicarray; ed: TWasmObjSymbolExtraData);
  913. var
  914. i,
  915. rle_entries,
  916. cnt: Integer;
  917. lasttype: TWasmBasicType;
  918. begin
  919. if Length(ed.Locals)=0 then
  920. begin
  921. WriteUleb(dest,0);
  922. exit;
  923. end;
  924. rle_entries:=1;
  925. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  926. if ed.Locals[i]<>ed.Locals[i-1] then
  927. inc(rle_entries);
  928. WriteUleb(dest,rle_entries);
  929. lasttype:=ed.Locals[Low(ed.Locals)];
  930. cnt:=1;
  931. for i:=low(ed.Locals)+1 to high(ed.Locals) do
  932. if ed.Locals[i]=ed.Locals[i-1] then
  933. inc(cnt)
  934. else
  935. begin
  936. WriteUleb(dest,cnt);
  937. WriteWasmBasicType(dest,lasttype);
  938. lasttype:=ed.Locals[i];
  939. cnt:=1;
  940. end;
  941. WriteUleb(dest,cnt);
  942. WriteWasmBasicType(dest,lasttype);
  943. end;
  944. procedure TWasmObjOutput.WriteFunctionCode(dest: tdynamicarray; objsym: TObjSymbol);
  945. var
  946. encoded_locals: tdynamicarray;
  947. ObjSymExtraData: TWasmObjSymbolExtraData;
  948. codelen: LongWord;
  949. ObjSection: TWasmObjSection;
  950. codeexprlen: QWord;
  951. begin
  952. ObjSymExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  953. ObjSection:=TWasmObjSection(objsym.objsection);
  954. ObjSection.Data.seek(objsym.address);
  955. codeexprlen:=objsym.size;
  956. encoded_locals:=tdynamicarray.Create(64);
  957. WriteFunctionLocals(encoded_locals,ObjSymExtraData);
  958. codelen:=encoded_locals.size+codeexprlen+1;
  959. WriteUleb(dest,codelen);
  960. encoded_locals.seek(0);
  961. CopyDynamicArray(encoded_locals,dest,encoded_locals.size);
  962. ObjSection.FileSectionOfs:=dest.size-objsym.offset;
  963. CopyDynamicArray(ObjSection.Data,dest,codeexprlen);
  964. WriteByte(dest,$0B);
  965. encoded_locals.Free;
  966. end;
  967. procedure TWasmObjOutput.WriteSymbolTable;
  968. begin
  969. WriteUleb(FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTableEntriesCount);
  970. FWasmSymbolTable.seek(0);
  971. CopyDynamicArray(FWasmSymbolTable,FWasmLinkingSubsections[WASM_SYMBOL_TABLE],FWasmSymbolTable.size);
  972. end;
  973. procedure TWasmObjOutput.WriteRelocationCodeTable(CodeSectionIndex: Integer);
  974. begin
  975. WriteUleb(FWasmCustomSections[wcstRelocCode],CodeSectionIndex);
  976. WriteUleb(FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTableEntriesCount);
  977. FWasmRelocationCodeTable.seek(0);
  978. CopyDynamicArray(FWasmRelocationCodeTable,FWasmCustomSections[wcstRelocCode],FWasmRelocationCodeTable.size);
  979. end;
  980. procedure TWasmObjOutput.WriteRelocationDataTable(DataSectionIndex: Integer);
  981. begin
  982. WriteUleb(FWasmCustomSections[wcstRelocData],DataSectionIndex);
  983. WriteUleb(FWasmCustomSections[wcstRelocData],FWasmRelocationDataTableEntriesCount);
  984. FWasmRelocationDataTable.seek(0);
  985. CopyDynamicArray(FWasmRelocationDataTable,FWasmCustomSections[wcstRelocData],FWasmRelocationDataTable.size);
  986. end;
  987. procedure TWasmObjOutput.MaybeWriteRelocationDebugTable(cst: TWasmCustomSectionType; SectionIndex: Integer; EntriesCount: Integer; Table: tdynamicarray);
  988. begin
  989. if EntriesCount>0 then
  990. begin
  991. WriteUleb(FWasmCustomSections[cst],SectionIndex);
  992. WriteUleb(FWasmCustomSections[cst],EntriesCount);
  993. Table.seek(0);
  994. CopyDynamicArray(Table,FWasmCustomSections[cst],Table.size);
  995. WriteWasmCustomSection(cst);
  996. end;
  997. end;
  998. procedure TWasmObjOutput.WriteLinkingSubsection(wlst: TWasmLinkingSubsectionType);
  999. begin
  1000. if FWasmLinkingSubsections[wlst].size>0 then
  1001. begin
  1002. WriteByte(FWasmCustomSections[wcstLinking],Ord(wlst));
  1003. WriteUleb(FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1004. FWasmLinkingSubsections[wlst].seek(0);
  1005. CopyDynamicArray(FWasmLinkingSubsections[wlst],FWasmCustomSections[wcstLinking],FWasmLinkingSubsections[wlst].size);
  1006. end;
  1007. end;
  1008. procedure TWasmObjOutput.DoRelocations;
  1009. var
  1010. si, ri: Integer;
  1011. objsec: TWasmObjSection;
  1012. objrel: TWasmObjRelocation;
  1013. begin
  1014. for si:=0 to FData.ObjSectionList.Count-1 do
  1015. begin
  1016. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1017. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1018. begin
  1019. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1020. case objrel.typ of
  1021. RELOC_FUNCTION_INDEX_LEB:
  1022. begin
  1023. if not assigned(objrel.symbol) then
  1024. internalerror(2021092509);
  1025. objsec.Data.seek(objrel.DataOffset);
  1026. if TWasmObjSymbol(objrel.symbol).FuncIndex<0 then
  1027. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1028. else
  1029. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).FuncIndex);
  1030. end;
  1031. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1032. begin
  1033. if not assigned(objrel.symbol) then
  1034. internalerror(2021092605);
  1035. if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1036. begin
  1037. objsec.Data.seek(objrel.DataOffset);
  1038. AddSleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1039. end;
  1040. end;
  1041. RELOC_MEMORY_ADDR_LEB:
  1042. begin
  1043. if not assigned(objrel.symbol) then
  1044. internalerror(2021092606);
  1045. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1046. internalerror(2021092628);
  1047. if objrel.symbol.bind<>AB_EXTERNAL then
  1048. begin
  1049. objsec.Data.seek(objrel.DataOffset);
  1050. AddUleb5(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1051. end;
  1052. end;
  1053. RELOC_ABSOLUTE:
  1054. begin
  1055. if assigned(objrel.ObjSection) then
  1056. begin
  1057. { todo: should we do something here? }
  1058. //Writeln('todo: section relocation');
  1059. end
  1060. else if not (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) or (objrel.symbol.bind=AB_EXTERNAL)) then
  1061. begin
  1062. objsec.Data.seek(objrel.DataOffset);
  1063. AddInt32(objsec.Data,objrel.symbol.offset+TWasmObjSection(objrel.symbol.objsection).SegOfs);
  1064. end;
  1065. end;
  1066. RELOC_TYPE_INDEX_LEB:
  1067. ;
  1068. RELOC_GLOBAL_INDEX_LEB:
  1069. begin
  1070. if not assigned(objrel.symbol) then
  1071. internalerror(2021092509);
  1072. objsec.Data.seek(objrel.DataOffset);
  1073. if TWasmObjSymbol(objrel.symbol).GlobalIndex<0 then
  1074. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1075. else
  1076. WriteUleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).GlobalIndex);
  1077. end;
  1078. RELOC_TAG_INDEX_LEB:
  1079. begin
  1080. if not assigned(objrel.symbol) then
  1081. internalerror(2021092716);
  1082. objsec.Data.seek(objrel.DataOffset);
  1083. if TWasmObjSymbol(objrel.symbol).TagIndex<0 then
  1084. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1085. else
  1086. WriteSleb5(objsec.Data,TWasmObjSymbol(objrel.symbol).TagIndex);
  1087. end;
  1088. else
  1089. internalerror(2021092510);
  1090. end;
  1091. end;
  1092. end;
  1093. end;
  1094. procedure TWasmObjOutput.WriteRelocations;
  1095. var
  1096. si, ri: Integer;
  1097. objsec: TWasmObjSection;
  1098. objrel: TWasmObjRelocation;
  1099. relout: tdynamicarray;
  1100. relcount: PInteger;
  1101. FuncSym: TWasmObjSymbol;
  1102. begin
  1103. for si:=0 to FData.ObjSectionList.Count-1 do
  1104. begin
  1105. objsec:=TWasmObjSection(FData.ObjSectionList[si]);
  1106. if objsec.IsCode then
  1107. begin
  1108. relout:=FWasmRelocationCodeTable;
  1109. relcount:=@FWasmRelocationCodeTableEntriesCount;
  1110. end
  1111. else if objsec.IsData then
  1112. begin
  1113. relout:=FWasmRelocationDataTable;
  1114. relcount:=@FWasmRelocationDataTableEntriesCount;
  1115. end
  1116. else if objsec.IsDebug then
  1117. begin
  1118. case objsec.Name of
  1119. '.debug_frame':
  1120. begin
  1121. relout:=FWasmRelocationDebugFrameTable;
  1122. relcount:=@FWasmRelocationDebugFrameTableEntriesCount;
  1123. end;
  1124. '.debug_info':
  1125. begin
  1126. relout:=FWasmRelocationDebugInfoTable;
  1127. relcount:=@FWasmRelocationDebugInfoTableEntriesCount;
  1128. end;
  1129. '.debug_line':
  1130. begin
  1131. relout:=FWasmRelocationDebugLineTable;
  1132. relcount:=@FWasmRelocationDebugLineTableEntriesCount;
  1133. end;
  1134. '.debug_abbrev':
  1135. begin
  1136. relout:=FWasmRelocationDebugAbbrevTable;
  1137. relcount:=@FWasmRelocationDebugAbbrevTableEntriesCount;
  1138. end;
  1139. '.debug_aranges':
  1140. begin
  1141. relout:=FWasmRelocationDebugArangesTable;
  1142. relcount:=@FWasmRelocationDebugArangesTableEntriesCount;
  1143. end;
  1144. '.debug_ranges':
  1145. begin
  1146. relout:=FWasmRelocationDebugRangesTable;
  1147. relcount:=@FWasmRelocationDebugRangesTableEntriesCount;
  1148. end;
  1149. '.debug_str':
  1150. begin
  1151. relout:=FWasmRelocationDebugStrTable;
  1152. relcount:=@FWasmRelocationDebugStrTableEntriesCount;
  1153. end;
  1154. else
  1155. internalerror(2022071601);
  1156. end;
  1157. end
  1158. else
  1159. continue;
  1160. for ri:=0 to objsec.ObjRelocations.Count-1 do
  1161. begin
  1162. objrel:=TWasmObjRelocation(objsec.ObjRelocations[ri]);
  1163. case objrel.typ of
  1164. RELOC_FUNCTION_INDEX_LEB:
  1165. begin
  1166. if not assigned(objrel.symbol) then
  1167. internalerror(2021092508);
  1168. Inc(relcount^);
  1169. WriteByte(relout,Ord(R_WASM_FUNCTION_INDEX_LEB));
  1170. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1171. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1172. end;
  1173. RELOC_MEMORY_ADDR_LEB:
  1174. begin
  1175. if not assigned(objrel.symbol) then
  1176. internalerror(2021092603);
  1177. Inc(relcount^);
  1178. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1179. internalerror(2021092628);
  1180. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_LEB));
  1181. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1182. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1183. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1184. end;
  1185. RELOC_MEMORY_ADDR_OR_TABLE_INDEX_SLEB:
  1186. begin
  1187. if not assigned(objrel.symbol) then
  1188. internalerror(2021092604);
  1189. Inc(relcount^);
  1190. if IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION) then
  1191. begin
  1192. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_SLEB));
  1193. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1194. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1195. end
  1196. else
  1197. begin
  1198. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_SLEB));
  1199. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1200. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1201. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1202. end;
  1203. end;
  1204. RELOC_ABSOLUTE:
  1205. begin
  1206. // todo: figure this out, why do these exist?
  1207. //if assigned(objrel.symbol) and not assigned(objrel.symbol.objsection) then
  1208. // Writeln('!!! ', objrel.symbol.name);
  1209. if assigned(objrel.objsection) then
  1210. begin
  1211. Inc(relcount^);
  1212. WriteByte(relout,Ord(R_WASM_SECTION_OFFSET_I32));
  1213. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1214. if (TWasmObjSection(objrel.objsection).SegSymIdx<0) then
  1215. message1(asmw_e_illegal_unset_index,objrel.objsection.name)
  1216. else
  1217. WriteUleb(relout,TWasmObjSection(objrel.objsection).SegSymIdx);
  1218. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1219. end
  1220. else if (IsExternalFunction(objrel.symbol) or (objrel.symbol.typ=AT_FUNCTION)) and not objsec.IsDebug then
  1221. begin
  1222. Inc(relcount^);
  1223. WriteByte(relout,Ord(R_WASM_TABLE_INDEX_I32));
  1224. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1225. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1226. end
  1227. else if assigned(objrel.symbol) and assigned(objrel.symbol.objsection) and TWasmObjSection(objrel.symbol.objsection).IsCode then
  1228. begin
  1229. Inc(relcount^);
  1230. WriteByte(relout,Ord(R_WASM_FUNCTION_OFFSET_I32));
  1231. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1232. FuncSym:=FindFunctionSymbol(TWasmObjSymbol(objrel.Symbol));
  1233. if FuncSym.SymbolIndex<0 then
  1234. message1(asmw_e_illegal_unset_index,FuncSym.Name)
  1235. else
  1236. WriteUleb(relout,FuncSym.SymbolIndex);
  1237. WriteSleb(relout,objrel.Addend+objrel.symbol.address); { addend to add to the address }
  1238. end
  1239. else
  1240. begin
  1241. Inc(relcount^);
  1242. WriteByte(relout,Ord(R_WASM_MEMORY_ADDR_I32));
  1243. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1244. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1245. begin
  1246. Writeln(objrel.symbol.objsection.Name, ' ', objrel.symbol.name, ' ', objsec.Name);
  1247. message1(asmw_e_illegal_unset_index,objrel.symbol.name);
  1248. end
  1249. else
  1250. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1251. WriteSleb(relout,objrel.Addend); { addend to add to the address }
  1252. end;
  1253. end;
  1254. RELOC_TYPE_INDEX_LEB:
  1255. begin
  1256. Inc(relcount^);
  1257. WriteByte(relout,Ord(R_WASM_TYPE_INDEX_LEB));
  1258. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1259. WriteUleb(relout,objrel.TypeIndex);
  1260. end;
  1261. RELOC_GLOBAL_INDEX_LEB:
  1262. begin
  1263. if not assigned(objrel.symbol) then
  1264. internalerror(2021092704);
  1265. Inc(relcount^);
  1266. WriteByte(relout,Ord(R_WASM_GLOBAL_INDEX_LEB));
  1267. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1268. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1269. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1270. else
  1271. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1272. end;
  1273. RELOC_TAG_INDEX_LEB:
  1274. begin
  1275. if not assigned(objrel.symbol) then
  1276. internalerror(2021092717);
  1277. Inc(relcount^);
  1278. WriteByte(relout,Ord(R_WASM_TAG_INDEX_LEB));
  1279. WriteUleb(relout,objrel.DataOffset+objsec.FileSectionOfs);
  1280. if (TWasmObjSymbol(objrel.symbol).SymbolIndex<0) then
  1281. message1(asmw_e_illegal_unset_index,objrel.symbol.name)
  1282. else
  1283. WriteUleb(relout,TWasmObjSymbol(objrel.symbol).SymbolIndex);
  1284. end;
  1285. else
  1286. internalerror(2021092507);
  1287. end;
  1288. end;
  1289. end;
  1290. end;
  1291. function TWasmObjOutput.FindFunctionSymbol(Symbol: TWasmObjSymbol): TWasmObjSymbol;
  1292. begin
  1293. Result:=TWasmObjSection(Symbol.objsection).MainFuncSymbol;
  1294. end;
  1295. function TWasmObjOutput.writeData(Data:TObjData):boolean;
  1296. var
  1297. section_nr: Integer;
  1298. procedure MaybeAddDebugSectionToSymbolTable(st: TWasmCustomDebugSectionType; var debug_section_nr: Integer);
  1299. var
  1300. objsec: TWasmObjSection;
  1301. begin
  1302. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1303. if Assigned(objsec) then
  1304. begin
  1305. debug_section_nr:=section_nr;
  1306. Inc(section_nr);
  1307. objsec.SegSymIdx:=FWasmSymbolTableEntriesCount;
  1308. Inc(FWasmSymbolTableEntriesCount);
  1309. WriteByte(FWasmSymbolTable,Ord(SYMTAB_SECTION));
  1310. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL);
  1311. WriteUleb(FWasmSymbolTable,debug_section_nr);
  1312. end;
  1313. end;
  1314. procedure MaybeWriteDebugSection(st: TWasmCustomDebugSectionType);
  1315. var
  1316. objsec: TWasmObjSection;
  1317. begin
  1318. objsec:=TWasmObjSection(Data.ObjSectionList.Find(WasmCustomSectionName[st]));
  1319. if Assigned(objsec) then
  1320. begin
  1321. if oso_Data in objsec.SecOptions then
  1322. begin
  1323. objsec.Data.seek(0);
  1324. CopyDynamicArray(objsec.Data,FWasmCustomSections[st],objsec.Size);
  1325. end
  1326. else
  1327. WriteZeros(FWasmCustomSections[st],objsec.Size);
  1328. WriteWasmCustomSection(st);
  1329. end;
  1330. end;
  1331. var
  1332. i: Integer;
  1333. objsec: TWasmObjSection;
  1334. segment_count: Integer = 0;
  1335. cur_seg_ofs: qword = 0;
  1336. types_count,
  1337. imports_count, NextImportFunctionIndex, NextFunctionIndex,
  1338. code_section_nr, data_section_nr,
  1339. debug_abbrev_section_nr,debug_info_section_nr,debug_str_section_nr,
  1340. debug_line_section_nr,debug_frame_section_nr,debug_aranges_section_nr,
  1341. debug_ranges_section_nr,
  1342. NextGlobalIndex, NextTagIndex: Integer;
  1343. import_globals_count: Integer = 0;
  1344. globals_count: Integer = 0;
  1345. import_functions_count: Integer = 0;
  1346. export_functions_count: Integer = 0;
  1347. functions_count: Integer = 0;
  1348. import_exception_tags_count: Integer = 0;
  1349. exception_tags_count: Integer = 0;
  1350. objsym, ObjSymAlias: TWasmObjSymbol;
  1351. cust_sec: TWasmCustomSectionType;
  1352. SegmentFlags, SymbolFlags: UInt64;
  1353. begin
  1354. FData:=TWasmObjData(Data);
  1355. { each custom sections starts with its name }
  1356. for cust_sec in TWasmCustomSectionType do
  1357. WriteName(FWasmCustomSections[cust_sec],WasmCustomSectionName[cust_sec]);
  1358. WriteUleb(FWasmCustomSections[wcstLinking],2); { linking metadata version }
  1359. for i:=0 to Data.ObjSymbolList.Count-1 do
  1360. begin
  1361. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1362. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1363. if objsym.bind=AB_EXTERNAL then
  1364. Inc(import_exception_tags_count)
  1365. else
  1366. Inc(exception_tags_count);
  1367. if objsym.typ=AT_WASM_GLOBAL then
  1368. if objsym.bind=AB_EXTERNAL then
  1369. Inc(import_globals_count)
  1370. else
  1371. Inc(globals_count);
  1372. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1373. Inc(import_globals_count);
  1374. if IsExternalFunction(objsym) then
  1375. Inc(import_functions_count);
  1376. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1377. begin
  1378. TWasmObjSection(objsym.objsection).MainFuncSymbol:=objsym;
  1379. Inc(functions_count);
  1380. end;
  1381. if IsExportedFunction(objsym) then
  1382. Inc(export_functions_count);
  1383. end;
  1384. types_count:=Length(FData.FFuncTypes);
  1385. WriteUleb(FWasmSections[wsiType],types_count);
  1386. for i:=0 to types_count-1 do
  1387. with FData.FFuncTypes[i] do
  1388. begin
  1389. WriteByte(FWasmSections[wsiType],$60);
  1390. WriteWasmResultType(FWasmSections[wsiType],params);
  1391. WriteWasmResultType(FWasmSections[wsiType],results);
  1392. end;
  1393. for i:=0 to Data.ObjSectionList.Count-1 do
  1394. begin
  1395. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1396. if objsec.IsCode then
  1397. objsec.SegIdx:=-1
  1398. else if objsec.IsData then
  1399. begin
  1400. objsec.SegIdx:=segment_count;
  1401. objsec.SegOfs:=cur_seg_ofs;
  1402. Inc(segment_count);
  1403. Inc(cur_seg_ofs,objsec.Size);
  1404. end;
  1405. end;
  1406. imports_count:=2+import_globals_count+import_functions_count+import_exception_tags_count;
  1407. WriteUleb(FWasmSections[wsiImport],imports_count);
  1408. { import memories }
  1409. WriteName(FWasmSections[wsiImport],'env');
  1410. WriteName(FWasmSections[wsiImport],'__linear_memory');
  1411. WriteByte(FWasmSections[wsiImport],$02); { mem }
  1412. WriteByte(FWasmSections[wsiImport],$00); { min }
  1413. WriteUleb(FWasmSections[wsiImport],1); { 1 page }
  1414. { import globals }
  1415. NextGlobalIndex:=0;
  1416. for i:=0 to Data.ObjSymbolList.Count-1 do
  1417. begin
  1418. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1419. if (objsym.bind=AB_EXTERNAL) and (objsym.typ=AT_WASM_GLOBAL) then
  1420. begin
  1421. objsym.GlobalIndex:=NextGlobalIndex;
  1422. Inc(NextGlobalIndex);
  1423. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1424. if objsym.ExtraData.ImportModule<>'' then
  1425. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1426. else
  1427. WriteName(FWasmSections[wsiImport],'env');
  1428. WriteName(FWasmSections[wsiImport],objsym.Name);
  1429. WriteByte(FWasmSections[wsiImport],$03); { global }
  1430. WriteWasmBasicType(FWasmSections[wsiImport],objsym.ExtraData.GlobalType);
  1431. if objsym.ExtraData.GlobalIsImmutable then
  1432. WriteByte(FWasmSections[wsiImport],$00) { const }
  1433. else
  1434. WriteByte(FWasmSections[wsiImport],$01); { var }
  1435. end
  1436. else if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1437. begin
  1438. objsym.GlobalIndex:=NextGlobalIndex;
  1439. Inc(NextGlobalIndex);
  1440. objsym.ExtraData:=nil;
  1441. WriteName(FWasmSections[wsiImport],'GOT.mem');
  1442. WriteName(FWasmSections[wsiImport],objsym.Name);
  1443. WriteByte(FWasmSections[wsiImport],$03); { global }
  1444. WriteWasmBasicType(FWasmSections[wsiImport],wbt_i32); { i32 }
  1445. WriteByte(FWasmSections[wsiImport],$01); { var }
  1446. end;
  1447. end;
  1448. { import functions }
  1449. NextImportFunctionIndex:=0;
  1450. for i:=0 to Data.ObjSymbolList.Count-1 do
  1451. begin
  1452. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1453. if IsExternalFunction(objsym) then
  1454. begin
  1455. objsym.FuncIndex:=NextImportFunctionIndex;
  1456. Inc(NextImportFunctionIndex);
  1457. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1458. if objsym.ExtraData.ImportModule<>'' then
  1459. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1460. else
  1461. WriteName(FWasmSections[wsiImport],'env');
  1462. WriteName(FWasmSections[wsiImport],objsym.Name);
  1463. WriteByte(FWasmSections[wsiImport],$00); { func }
  1464. WriteUleb(FWasmSections[wsiImport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1465. end;
  1466. end;
  1467. { import tables }
  1468. WriteName(FWasmSections[wsiImport],'env');
  1469. WriteName(FWasmSections[wsiImport],'__indirect_function_table');
  1470. WriteByte(FWasmSections[wsiImport],$01); { table }
  1471. WriteByte(FWasmSections[wsiImport],$70); { funcref }
  1472. WriteByte(FWasmSections[wsiImport],$00); { min }
  1473. WriteUleb(FWasmSections[wsiImport],1); { 1 }
  1474. { import tags }
  1475. NextTagIndex:=0;
  1476. for i:=0 to Data.ObjSymbolList.Count-1 do
  1477. begin
  1478. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1479. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind=AB_EXTERNAL) then
  1480. begin
  1481. objsym.TagIndex:=NextTagIndex;
  1482. Inc(NextTagIndex);
  1483. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1484. if objsym.ExtraData.ImportModule<>'' then
  1485. WriteName(FWasmSections[wsiImport],objsym.ExtraData.ImportModule)
  1486. else
  1487. WriteName(FWasmSections[wsiImport],'env');
  1488. WriteName(FWasmSections[wsiImport],objsym.Name);
  1489. WriteByte(FWasmSections[wsiImport],$04); { tag }
  1490. WriteByte(FWasmSections[wsiImport],$00); { exception }
  1491. WriteUleb(FWasmSections[wsiImport],objsym.ExtraData.ExceptionTagTypeIdx);
  1492. end;
  1493. end;
  1494. WriteUleb(FWasmSections[wsiFunction],functions_count);
  1495. NextFunctionIndex:=NextImportFunctionIndex;
  1496. for i:=0 to Data.ObjSymbolList.Count-1 do
  1497. begin
  1498. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1499. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1500. begin
  1501. objsym.FuncIndex:=NextFunctionIndex;
  1502. Inc(NextFunctionIndex);
  1503. WriteUleb(FWasmSections[wsiFunction],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).TypeIdx);
  1504. end;
  1505. end;
  1506. if exception_tags_count>0 then
  1507. begin
  1508. WriteUleb(FWasmSections[wsiTag],exception_tags_count);
  1509. for i:=0 to Data.ObjSymbolList.Count-1 do
  1510. begin
  1511. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1512. if (objsym.typ=AT_WASM_EXCEPTION_TAG) and (objsym.bind<>AB_EXTERNAL) then
  1513. begin
  1514. objsym.TagIndex:=NextTagIndex;
  1515. Inc(NextTagIndex);
  1516. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1517. WriteByte(FWasmSections[wsiTag],$00); { exception }
  1518. WriteUleb(FWasmSections[wsiTag],objsym.ExtraData.ExceptionTagTypeIdx);
  1519. end;
  1520. end;
  1521. end;
  1522. if globals_count>0 then
  1523. begin
  1524. WriteUleb(FWasmSections[wsiGlobal],globals_count);
  1525. for i:=0 to Data.ObjSymbolList.Count-1 do
  1526. begin
  1527. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1528. if (objsym.typ=AT_WASM_GLOBAL) and (objsym.bind<>AB_EXTERNAL) then
  1529. begin
  1530. objsym.GlobalIndex:=NextGlobalIndex;
  1531. Inc(NextGlobalIndex);
  1532. objsym.ExtraData:=TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name));
  1533. WriteWasmBasicType(FWasmSections[wsiGlobal],objsym.ExtraData.GlobalType);
  1534. if objsym.ExtraData.GlobalIsImmutable then
  1535. WriteByte(FWasmSections[wsiGlobal],$00) { const }
  1536. else
  1537. WriteByte(FWasmSections[wsiGlobal],$01); { var }
  1538. { init expr }
  1539. case objsym.ExtraData.GlobalType of
  1540. wbt_i32:
  1541. begin
  1542. WriteByte(FWasmSections[wsiGlobal],$41); { i32.const }
  1543. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1544. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1545. end;
  1546. wbt_i64:
  1547. begin
  1548. WriteByte(FWasmSections[wsiGlobal],$42); { i64.const }
  1549. WriteByte(FWasmSections[wsiGlobal],0); { 0 (in signed LEB128 format) }
  1550. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1551. end;
  1552. wbt_f32:
  1553. begin
  1554. WriteByte(FWasmSections[wsiGlobal],$43); { f32.const }
  1555. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE single precision floating point format) }
  1556. WriteByte(FWasmSections[wsiGlobal],$00);
  1557. WriteByte(FWasmSections[wsiGlobal],$00);
  1558. WriteByte(FWasmSections[wsiGlobal],$00);
  1559. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1560. end;
  1561. wbt_f64:
  1562. begin
  1563. WriteByte(FWasmSections[wsiGlobal],$44); { f64.const }
  1564. WriteByte(FWasmSections[wsiGlobal],$00); { 0 (in little endian IEEE double precision floating point format) }
  1565. WriteByte(FWasmSections[wsiGlobal],$00);
  1566. WriteByte(FWasmSections[wsiGlobal],$00);
  1567. WriteByte(FWasmSections[wsiGlobal],$00);
  1568. WriteByte(FWasmSections[wsiGlobal],$00);
  1569. WriteByte(FWasmSections[wsiGlobal],$00);
  1570. WriteByte(FWasmSections[wsiGlobal],$00);
  1571. WriteByte(FWasmSections[wsiGlobal],$00);
  1572. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1573. end;
  1574. wbt_externref:
  1575. begin
  1576. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null extern }
  1577. WriteByte(FWasmSections[wsiGlobal],$6F);
  1578. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1579. end;
  1580. wbt_funcref:
  1581. begin
  1582. WriteByte(FWasmSections[wsiGlobal],$D0); { ref.null func }
  1583. WriteByte(FWasmSections[wsiGlobal],$70);
  1584. WriteByte(FWasmSections[wsiGlobal],$0B); { end }
  1585. end;
  1586. else
  1587. internalerror(2022052801);
  1588. end;
  1589. end;
  1590. end;
  1591. end;
  1592. if export_functions_count>0 then
  1593. begin
  1594. WriteUleb(FWasmSections[wsiExport],export_functions_count);
  1595. for i:=0 to Data.ObjSymbolList.Count-1 do
  1596. begin
  1597. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1598. if IsExportedFunction(objsym) then
  1599. begin
  1600. WriteName(FWasmSections[wsiExport],TWasmObjSymbolExtraData(FData.FObjSymbolsExtraDataList.Find(objsym.Name)).ExportName);
  1601. WriteByte(FWasmSections[wsiExport],0); { func }
  1602. if (objsym.FuncIndex<0) then
  1603. message1(asmw_e_illegal_unset_index,objsym.name)
  1604. else
  1605. WriteUleb(FWasmSections[wsiExport],objsym.FuncIndex);
  1606. end;
  1607. end;
  1608. end;
  1609. for i:=0 to Data.ObjSymbolList.Count-1 do
  1610. begin
  1611. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1612. if objsym.typ=AT_WASM_EXCEPTION_TAG then
  1613. begin
  1614. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1615. Inc(FWasmSymbolTableEntriesCount);
  1616. WriteByte(FWasmSymbolTable,Ord(SYMTAB_EVENT));
  1617. if objsym.bind=AB_GLOBAL then
  1618. WriteUleb(FWasmSymbolTable,0)
  1619. else if objsym.bind=AB_LOCAL then
  1620. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_LOCAL)
  1621. else if objsym.bind=AB_EXTERNAL then
  1622. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED)
  1623. else if objsym.bind=AB_WEAK then
  1624. WriteUleb(FWasmSymbolTable,WASM_SYM_BINDING_WEAK)
  1625. else
  1626. internalerror(2021092715);
  1627. if (objsym.TagIndex<0) then
  1628. message1(asmw_e_illegal_unset_index,objsym.name)
  1629. else
  1630. WriteUleb(FWasmSymbolTable,objsym.TagIndex);
  1631. if objsym.bind<>AB_EXTERNAL then
  1632. WriteName(FWasmSymbolTable,objsym.Name);
  1633. end
  1634. else if objsym.typ=AT_WASM_GLOBAL then
  1635. begin
  1636. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1637. Inc(FWasmSymbolTableEntriesCount);
  1638. WriteByte(FWasmSymbolTable,Ord(SYMTAB_GLOBAL));
  1639. if objsym.bind=AB_EXTERNAL then
  1640. begin
  1641. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1642. if (objsym.GlobalIndex<0) then
  1643. message1(asmw_e_illegal_unset_index,objsym.name)
  1644. else
  1645. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1646. end
  1647. else
  1648. begin
  1649. WriteUleb(FWasmSymbolTable,0);
  1650. if (objsym.GlobalIndex<0) then
  1651. message1(asmw_e_illegal_unset_index,objsym.name)
  1652. else
  1653. WriteUleb(FWasmSymbolTable,objsym.GlobalIndex);
  1654. WriteName(FWasmSymbolTable,objsym.Name);
  1655. end;
  1656. end
  1657. else if IsExternalFunction(objsym) then
  1658. begin
  1659. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1660. Inc(FWasmSymbolTableEntriesCount);
  1661. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1662. if objsym.ExtraData.ImportModule<>'' then
  1663. begin
  1664. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED or WASM_SYM_EXPLICIT_NAME);
  1665. if (objsym.FuncIndex<0) then
  1666. message1(asmw_e_illegal_unset_index,objsym.name)
  1667. else
  1668. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1669. WriteName(FWasmSymbolTable,objsym.Name);
  1670. end
  1671. else
  1672. begin
  1673. WriteUleb(FWasmSymbolTable,WASM_SYM_UNDEFINED);
  1674. if (objsym.FuncIndex<0) then
  1675. message1(asmw_e_illegal_unset_index,objsym.name)
  1676. else
  1677. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1678. end;
  1679. end
  1680. else if objsym.typ=AT_FUNCTION then
  1681. begin
  1682. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1683. Inc(FWasmSymbolTableEntriesCount);
  1684. WriteByte(FWasmSymbolTable,Ord(SYMTAB_FUNCTION));
  1685. if objsym.IsAlias then
  1686. begin
  1687. ObjSymAlias:=TWasmObjSymbol(Data.ObjSymbolList.Find(objsym.AliasOf));
  1688. ObjSym.FuncIndex:=ObjSymAlias.FuncIndex;
  1689. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPLICIT_NAME or WASM_SYM_NO_STRIP);
  1690. WriteUleb(FWasmSymbolTable,ObjSymAlias.FuncIndex);
  1691. end
  1692. else
  1693. begin
  1694. if IsExportedFunction(objsym) then
  1695. WriteUleb(FWasmSymbolTable,WASM_SYM_EXPORTED)
  1696. else
  1697. WriteUleb(FWasmSymbolTable,0);
  1698. if (objsym.FuncIndex<0) then
  1699. message1(asmw_e_illegal_unset_index,objsym.name)
  1700. else
  1701. WriteUleb(FWasmSymbolTable,objsym.FuncIndex);
  1702. end;
  1703. WriteName(FWasmSymbolTable,objsym.Name);
  1704. end
  1705. else if (objsym.typ in [AT_DATA,AT_TLS]) or ((objsym.typ=AT_NONE) and (objsym.bind=AB_EXTERNAL)) then
  1706. begin
  1707. if (objsym.bind<>AB_EXTERNAL) and TWasmObjSection(objsym.objsection).IsDebug then
  1708. begin
  1709. {todo: debug symbols}
  1710. end
  1711. else
  1712. begin
  1713. objsym.SymbolIndex:=FWasmSymbolTableEntriesCount;
  1714. Inc(FWasmSymbolTableEntriesCount);
  1715. WriteByte(FWasmSymbolTable,Ord(SYMTAB_DATA));
  1716. if objsym.bind=AB_GLOBAL then
  1717. SymbolFlags:=0
  1718. else if objsym.bind=AB_LOCAL then
  1719. SymbolFlags:=WASM_SYM_BINDING_LOCAL
  1720. else if objsym.bind=AB_EXTERNAL then
  1721. SymbolFlags:=WASM_SYM_UNDEFINED
  1722. else
  1723. internalerror(2021092506);
  1724. if (objsym.typ=AT_TLS) and (ts_wasm_threads in current_settings.targetswitches) then
  1725. SymbolFlags:=(SymbolFlags and not WASM_SYM_BINDING_LOCAL) or WASM_SYM_TLS;
  1726. WriteUleb(FWasmSymbolTable,SymbolFlags);
  1727. WriteName(FWasmSymbolTable,objsym.Name);
  1728. if objsym.bind<>AB_EXTERNAL then
  1729. begin
  1730. WriteUleb(FWasmSymbolTable,TWasmObjSection(objsym.objsection).SegIdx);
  1731. WriteUleb(FWasmSymbolTable,objsym.offset);
  1732. WriteUleb(FWasmSymbolTable,objsym.size);
  1733. end;
  1734. end;
  1735. end;
  1736. end;
  1737. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  1738. Writer.write(WasmVersion,SizeOf(WasmVersion));
  1739. if ts_wasm_threads in current_settings.targetswitches then
  1740. begin
  1741. WriteUleb(FWasmCustomSections[wcstTargetFeatures],4);
  1742. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1743. WriteName(FWasmCustomSections[wcstTargetFeatures],'atomics');
  1744. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1745. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1746. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1747. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1748. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1749. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1750. end
  1751. else
  1752. begin
  1753. WriteUleb(FWasmCustomSections[wcstTargetFeatures],3);
  1754. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1755. WriteName(FWasmCustomSections[wcstTargetFeatures],'bulk-memory');
  1756. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1757. WriteName(FWasmCustomSections[wcstTargetFeatures],'mutable-globals');
  1758. WriteUleb(FWasmCustomSections[wcstTargetFeatures],$2B);
  1759. WriteName(FWasmCustomSections[wcstTargetFeatures],'sign-ext');
  1760. end;
  1761. { Write the producers section:
  1762. https://github.com/WebAssembly/tool-conventions/blob/main/ProducersSection.md }
  1763. WriteUleb(FWasmCustomSections[wcstProducers],2);
  1764. WriteName(FWasmCustomSections[wcstProducers],'language');
  1765. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1766. WriteName(FWasmCustomSections[wcstProducers],'Pascal');
  1767. WriteName(FWasmCustomSections[wcstProducers],'');
  1768. WriteName(FWasmCustomSections[wcstProducers],'processed-by');
  1769. WriteUleb(FWasmCustomSections[wcstProducers],1);
  1770. WriteName(FWasmCustomSections[wcstProducers],'Free Pascal Compiler (FPC)');
  1771. WriteName(FWasmCustomSections[wcstProducers],full_version_string+' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname);
  1772. code_section_nr:=-1;
  1773. data_section_nr:=-1;
  1774. debug_abbrev_section_nr:=-1;
  1775. debug_info_section_nr:=-1;
  1776. debug_str_section_nr:=-1;
  1777. debug_line_section_nr:=-1;
  1778. debug_frame_section_nr:=-1;
  1779. debug_aranges_section_nr:=-1;
  1780. debug_ranges_section_nr:=-1;
  1781. section_nr:=0;
  1782. WriteWasmSection(wsiType);
  1783. Inc(section_nr);
  1784. WriteWasmSection(wsiImport);
  1785. Inc(section_nr);
  1786. WriteWasmSection(wsiFunction);
  1787. Inc(section_nr);
  1788. if exception_tags_count>0 then
  1789. begin
  1790. WriteWasmSection(wsiTag);
  1791. Inc(section_nr);
  1792. end;
  1793. if globals_count>0 then
  1794. begin
  1795. WriteWasmSection(wsiGlobal);
  1796. Inc(section_nr);
  1797. end;
  1798. if export_functions_count>0 then
  1799. begin
  1800. WriteWasmSection(wsiExport);
  1801. Inc(section_nr);
  1802. end;
  1803. { determine the section numbers for the datacount, code, data and debug sections ahead of time }
  1804. if segment_count>0 then
  1805. Inc(section_nr); { the DataCount section }
  1806. code_section_nr:=section_nr; { the Code section }
  1807. Inc(section_nr);
  1808. if segment_count>0 then
  1809. begin
  1810. data_section_nr:=section_nr; { the Data section }
  1811. Inc(section_nr);
  1812. end;
  1813. { the debug sections }
  1814. MaybeAddDebugSectionToSymbolTable(wcstDebugAbbrev,debug_abbrev_section_nr);
  1815. MaybeAddDebugSectionToSymbolTable(wcstDebugInfo,debug_info_section_nr);
  1816. MaybeAddDebugSectionToSymbolTable(wcstDebugStr,debug_str_section_nr);
  1817. MaybeAddDebugSectionToSymbolTable(wcstDebugLine,debug_line_section_nr);
  1818. MaybeAddDebugSectionToSymbolTable(wcstDebugFrame,debug_frame_section_nr);
  1819. MaybeAddDebugSectionToSymbolTable(wcstDebugAranges,debug_aranges_section_nr);
  1820. MaybeAddDebugSectionToSymbolTable(wcstDebugRanges,debug_ranges_section_nr);
  1821. DoRelocations;
  1822. if segment_count>0 then
  1823. begin
  1824. WriteUleb(FWasmSections[wsiData],segment_count);
  1825. WriteUleb(FWasmSections[wsiDataCount],segment_count);
  1826. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],segment_count);
  1827. for i:=0 to Data.ObjSectionList.Count-1 do
  1828. begin
  1829. objsec:=TWasmObjSection(Data.ObjSectionList[i]);
  1830. if objsec.IsData then
  1831. begin
  1832. WriteName(FWasmLinkingSubsections[WASM_SEGMENT_INFO],objsec.Name);
  1833. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],BsrQWord(objsec.SecAlign));
  1834. SegmentFlags:=0;
  1835. if (ts_wasm_threads in current_settings.targetswitches) and
  1836. (oso_threadvar in objsec.SecOptions) then
  1837. SegmentFlags:=SegmentFlags or WASM_SEG_FLAG_TLS;
  1838. WriteUleb(FWasmLinkingSubsections[WASM_SEGMENT_INFO],SegmentFlags); { flags }
  1839. WriteByte(FWasmSections[wsiData],0);
  1840. WriteByte(FWasmSections[wsiData],$41);
  1841. WriteSleb(FWasmSections[wsiData],objsec.SegOfs);
  1842. WriteByte(FWasmSections[wsiData],$0b);
  1843. WriteUleb(FWasmSections[wsiData],objsec.Size);
  1844. objsec.FileSectionOfs:=FWasmSections[wsiData].size;
  1845. if oso_Data in objsec.SecOptions then
  1846. begin
  1847. objsec.Data.seek(0);
  1848. CopyDynamicArray(objsec.Data,FWasmSections[wsiData],objsec.Size);
  1849. end
  1850. else
  1851. begin
  1852. WriteZeros(FWasmSections[wsiData],objsec.Size);
  1853. end;
  1854. end;
  1855. end;
  1856. end;
  1857. WriteUleb(FWasmSections[wsiCode],functions_count);
  1858. for i:=0 to Data.ObjSymbolList.Count-1 do
  1859. begin
  1860. objsym:=TWasmObjSymbol(Data.ObjSymbolList[i]);
  1861. if (objsym.typ=AT_FUNCTION) and not objsym.IsAlias then
  1862. WriteFunctionCode(FWasmSections[wsiCode],objsym);
  1863. end;
  1864. if segment_count>0 then
  1865. WriteWasmSection(wsiDataCount);
  1866. WriteWasmSection(wsiCode);
  1867. if segment_count>0 then
  1868. WriteWasmSection(wsiData);
  1869. MaybeWriteDebugSection(wcstDebugAbbrev);
  1870. MaybeWriteDebugSection(wcstDebugInfo);
  1871. MaybeWriteDebugSection(wcstDebugStr);
  1872. MaybeWriteDebugSection(wcstDebugLine);
  1873. MaybeWriteDebugSection(wcstDebugFrame);
  1874. MaybeWriteDebugSection(wcstDebugAranges);
  1875. MaybeWriteDebugSection(wcstDebugRanges);
  1876. WriteRelocations;
  1877. WriteSymbolTable;
  1878. WriteLinkingSubsection(WASM_SYMBOL_TABLE);
  1879. if segment_count>0 then
  1880. WriteLinkingSubsection(WASM_SEGMENT_INFO);
  1881. WriteRelocationCodeTable(code_section_nr);
  1882. if segment_count>0 then
  1883. WriteRelocationDataTable(data_section_nr);
  1884. WriteWasmCustomSection(wcstLinking);
  1885. Inc(section_nr);
  1886. WriteWasmCustomSection(wcstRelocCode);
  1887. Inc(section_nr);
  1888. if segment_count>0 then
  1889. begin
  1890. WriteWasmCustomSection(wcstRelocData);
  1891. Inc(section_nr);
  1892. end;
  1893. MaybeWriteRelocationDebugTable(wcstRelocDebugAbbrev,debug_abbrev_section_nr,FWasmRelocationDebugAbbrevTableEntriesCount,FWasmRelocationDebugAbbrevTable);
  1894. MaybeWriteRelocationDebugTable(wcstRelocDebugInfo,debug_info_section_nr,FWasmRelocationDebugInfoTableEntriesCount,FWasmRelocationDebugInfoTable);
  1895. MaybeWriteRelocationDebugTable(wcstRelocDebugStr,debug_str_section_nr,FWasmRelocationDebugStrTableEntriesCount,FWasmRelocationDebugStrTable);
  1896. MaybeWriteRelocationDebugTable(wcstRelocDebugLine,debug_line_section_nr,FWasmRelocationDebugLineTableEntriesCount,FWasmRelocationDebugLineTable);
  1897. MaybeWriteRelocationDebugTable(wcstRelocDebugFrame,debug_frame_section_nr,FWasmRelocationDebugFrameTableEntriesCount,FWasmRelocationDebugFrameTable);
  1898. MaybeWriteRelocationDebugTable(wcstRelocDebugAranges,debug_aranges_section_nr,FWasmRelocationDebugArangesTableEntriesCount,FWasmRelocationDebugArangesTable);
  1899. MaybeWriteRelocationDebugTable(wcstRelocDebugRanges,debug_ranges_section_nr,FWasmRelocationDebugRangesTableEntriesCount,FWasmRelocationDebugRangesTable);
  1900. WriteWasmCustomSection(wcstProducers);
  1901. Inc(section_nr);
  1902. WriteWasmCustomSection(wcstTargetFeatures);
  1903. Inc(section_nr);
  1904. result:=true;
  1905. end;
  1906. constructor TWasmObjOutput.create(AWriter: TObjectWriter);
  1907. var
  1908. i: TWasmSectionID;
  1909. j: TWasmCustomSectionType;
  1910. k: TWasmLinkingSubsectionType;
  1911. begin
  1912. inherited;
  1913. cobjdata:=TWasmObjData;
  1914. for i in TWasmSectionID do
  1915. FWasmSections[i] := tdynamicarray.create(SectionDataMaxGrow);
  1916. for j in TWasmCustomSectionType do
  1917. FWasmCustomSections[j] := tdynamicarray.create(SectionDataMaxGrow);
  1918. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1919. FWasmLinkingSubsections[k] := tdynamicarray.create(SectionDataMaxGrow);
  1920. FWasmSymbolTable:=tdynamicarray.create(SectionDataMaxGrow);
  1921. FWasmSymbolTableEntriesCount:=0;
  1922. FWasmRelocationCodeTable:=tdynamicarray.create(SectionDataMaxGrow);
  1923. FWasmRelocationCodeTableEntriesCount:=0;
  1924. FWasmRelocationDataTable:=tdynamicarray.create(SectionDataMaxGrow);
  1925. FWasmRelocationDataTableEntriesCount:=0;
  1926. FWasmRelocationDebugFrameTable:=tdynamicarray.create(SectionDataMaxGrow);
  1927. FWasmRelocationDebugFrameTableEntriesCount:=0;
  1928. FWasmRelocationDebugInfoTable:=tdynamicarray.create(SectionDataMaxGrow);
  1929. FWasmRelocationDebugInfoTableEntriesCount:=0;
  1930. FWasmRelocationDebugLineTable:=tdynamicarray.create(SectionDataMaxGrow);
  1931. FWasmRelocationDebugLineTableEntriesCount:=0;
  1932. FWasmRelocationDebugAbbrevTable:=tdynamicarray.create(SectionDataMaxGrow);
  1933. FWasmRelocationDebugAbbrevTableEntriesCount:=0;
  1934. FWasmRelocationDebugArangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  1935. FWasmRelocationDebugArangesTableEntriesCount:=0;
  1936. FWasmRelocationDebugRangesTable:=tdynamicarray.create(SectionDataMaxGrow);
  1937. FWasmRelocationDebugRangesTableEntriesCount:=0;
  1938. FWasmRelocationDebugStrTable:=tdynamicarray.create(SectionDataMaxGrow);
  1939. FWasmRelocationDebugStrTableEntriesCount:=0;
  1940. end;
  1941. destructor TWasmObjOutput.destroy;
  1942. var
  1943. i: TWasmSectionID;
  1944. j: TWasmCustomSectionType;
  1945. k: TWasmLinkingSubsectionType;
  1946. begin
  1947. for i in TWasmSectionID do
  1948. FWasmSections[i].Free;
  1949. for j in TWasmCustomSectionType do
  1950. FWasmCustomSections[j].Free;
  1951. for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
  1952. FWasmLinkingSubsections[k].Free;
  1953. FWasmSymbolTable.Free;
  1954. FWasmRelocationCodeTable.Free;
  1955. FWasmRelocationDataTable.Free;
  1956. FWasmRelocationDebugFrameTable.Free;
  1957. FWasmRelocationDebugInfoTable.Free;
  1958. FWasmRelocationDebugLineTable.Free;
  1959. FWasmRelocationDebugAbbrevTable.Free;
  1960. FWasmRelocationDebugArangesTable.Free;
  1961. FWasmRelocationDebugRangesTable.Free;
  1962. FWasmRelocationDebugStrTable.Free;
  1963. inherited destroy;
  1964. end;
  1965. {****************************************************************************
  1966. TWasmObjInput
  1967. ****************************************************************************}
  1968. constructor TWasmObjInput.create;
  1969. begin
  1970. inherited create;
  1971. cobjdata:=TWasmObjData;
  1972. end;
  1973. destructor TWasmObjInput.Destroy;
  1974. var
  1975. i: Integer;
  1976. begin
  1977. for i:=low(FFuncTypes) to high(FFuncTypes) do
  1978. begin
  1979. FFuncTypes[i].free;
  1980. FFuncTypes[i]:=nil;
  1981. end;
  1982. inherited Destroy;
  1983. end;
  1984. class function TWasmObjInput.CanReadObjData(AReader: TObjectreader): boolean;
  1985. var
  1986. ModuleMagic: array [0..3] of Byte;
  1987. ModuleVersion: array [0..3] of Byte;
  1988. i: Integer;
  1989. begin
  1990. Writeln('CanReadObjData');
  1991. result:=false;
  1992. if not AReader.read(ModuleMagic,4) then
  1993. exit;
  1994. for i:=0 to 3 do
  1995. if ModuleMagic[i]<>WasmModuleMagic[i] then
  1996. exit;
  1997. if not AReader.read(ModuleVersion,4) then
  1998. exit;
  1999. for i:=0 to 3 do
  2000. if ModuleVersion[i]<>WasmVersion[i] then
  2001. exit;
  2002. result:=true;
  2003. end;
  2004. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2005. function ReadSection: Boolean;
  2006. var
  2007. SectionId: Byte;
  2008. SectionSize: uint32;
  2009. SectionStart: LongInt;
  2010. CheckSectionBounds: Boolean;
  2011. function read(out b;len:longint):boolean;
  2012. begin
  2013. result:=false;
  2014. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2015. result:=AReader.read(b,len)
  2016. else
  2017. begin
  2018. { trying to read beyond the end of the section }
  2019. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2020. result:=false;
  2021. end;
  2022. end;
  2023. function ReadUleb(out v: uint64): boolean;
  2024. var
  2025. b: byte;
  2026. shift:integer;
  2027. begin
  2028. result:=false;
  2029. b:=0;
  2030. v:=0;
  2031. shift:=0;
  2032. repeat
  2033. if not read(b,1) then
  2034. exit;
  2035. v:=v or (uint64(b and 127) shl shift);
  2036. inc(shift,7);
  2037. until (b and 128)=0;
  2038. result:=true;
  2039. end;
  2040. function ReadUleb32(out v: uint32): boolean;
  2041. var
  2042. vv: uint64;
  2043. begin
  2044. result:=false;
  2045. v:=default(uint32);
  2046. if not ReadUleb(vv) then
  2047. exit;
  2048. if vv>high(uint32) then
  2049. exit;
  2050. v:=vv;
  2051. result:=true;
  2052. end;
  2053. function ReadName(out v: ansistring): boolean;
  2054. var
  2055. len: uint32;
  2056. begin
  2057. result:=false;
  2058. if not ReadUleb32(len) then
  2059. exit;
  2060. SetLength(v,len);
  2061. if len>0 then
  2062. result:=read(v[1],len)
  2063. else
  2064. result:=true;
  2065. end;
  2066. var
  2067. TypeSectionRead: Boolean = false;
  2068. ImportSectionRead: Boolean = false;
  2069. FunctionSectionRead: Boolean = false;
  2070. CodeSectionRead: Boolean = false;
  2071. DataCountSectionRead: Boolean = false;
  2072. DataCount: uint32;
  2073. function ReadCustomSection: Boolean;
  2074. function ReadRelocationSection: Boolean;
  2075. begin
  2076. Result:=False;
  2077. end;
  2078. function ReadLinkingSection: Boolean;
  2079. function ReadSegmentInfo: Boolean;
  2080. begin
  2081. Result:=False;
  2082. end;
  2083. function ReadSymbolTable: Boolean;
  2084. begin
  2085. Result:=False;
  2086. end;
  2087. const
  2088. ExpectedVersion = 2;
  2089. var
  2090. Version, SubsectionSize, SaveSectionSize: uint32;
  2091. SubsectionType: Byte;
  2092. SaveSectionStart: LongInt;
  2093. begin
  2094. Result:=False;
  2095. if not ReadUleb32(Version) then
  2096. begin
  2097. InputError('Error reading the version of the ''linking'' section');
  2098. exit;
  2099. end;
  2100. if Version<>ExpectedVersion then
  2101. begin
  2102. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2103. exit;
  2104. end;
  2105. while AReader.Pos<(SectionStart+SectionSize) do
  2106. begin
  2107. if not read(SubsectionType, 1) then
  2108. begin
  2109. InputError('Error reading subsection type in the ''linking'' section');
  2110. exit;
  2111. end;
  2112. if not ReadUleb32(SubsectionSize) then
  2113. begin
  2114. InputError('Error reading subsection size in the ''linking'' section');
  2115. exit;
  2116. end;
  2117. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2118. begin
  2119. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2120. exit;
  2121. end;
  2122. SaveSectionStart:=SectionStart;
  2123. SaveSectionSize:=SectionSize;
  2124. SectionStart:=AReader.Pos;
  2125. SectionSize:=SubsectionSize;
  2126. case SubsectionType of
  2127. Byte(WASM_SEGMENT_INFO):
  2128. result:=ReadSegmentInfo;
  2129. Byte(WASM_SYMBOL_TABLE):
  2130. result:=ReadSymbolTable;
  2131. else
  2132. begin
  2133. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2134. exit;
  2135. end;
  2136. end;
  2137. AReader.Seek(SectionStart+SectionSize);
  2138. SectionStart:=SaveSectionStart;
  2139. SectionSize:=SaveSectionSize;
  2140. end;
  2141. result:=True;
  2142. end;
  2143. function ReadProducersSection: Boolean;
  2144. begin
  2145. Result:=False;
  2146. end;
  2147. function ReadTargetFeaturesSection: Boolean;
  2148. begin
  2149. Result:=False;
  2150. end;
  2151. const
  2152. RelocationSectionPrefix = 'reloc.';
  2153. var
  2154. SectionName: ansistring;
  2155. begin
  2156. Result:=False;
  2157. ReadName(SectionName);
  2158. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2159. Result:=ReadRelocationSection
  2160. else
  2161. case SectionName of
  2162. 'linking':
  2163. if not ReadLinkingSection then
  2164. begin
  2165. InputError('Error reading the ''linking'' section');
  2166. exit;
  2167. end;
  2168. 'producers':
  2169. Result:=ReadProducersSection;
  2170. 'target_features':
  2171. Result:=ReadTargetFeaturesSection;
  2172. else
  2173. InputError('Unsupported custom section: ''' + SectionName + '''');
  2174. end;
  2175. Result:=True;
  2176. end;
  2177. function ReadTypeSection: Boolean;
  2178. var
  2179. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2180. FuncTypeId, WasmTypeId: Byte;
  2181. i, j: Integer;
  2182. wbt: TWasmBasicType;
  2183. begin
  2184. Result:=False;
  2185. if TypeSectionRead then
  2186. begin
  2187. InputError('Type section is duplicated');
  2188. exit;
  2189. end;
  2190. TypeSectionRead:=True;
  2191. if not ReadUleb32(FuncTypesCount) then
  2192. begin
  2193. InputError('Error reading the func types count');
  2194. exit;
  2195. end;
  2196. SetLength(FFuncTypes,FuncTypesCount);
  2197. for i:=0 to FuncTypesCount - 1 do
  2198. begin
  2199. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2200. if not AReader.read(FuncTypeId,1) then
  2201. begin
  2202. InputError('Error reading the function type identifier');
  2203. exit;
  2204. end;
  2205. if FuncTypeId<>$60 then
  2206. begin
  2207. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2208. exit;
  2209. end;
  2210. if not ReadUleb32(ParamsCount) then
  2211. begin
  2212. InputError('Error reading the function parameters count');
  2213. exit;
  2214. end;
  2215. for j:=0 to ParamsCount-1 do
  2216. begin
  2217. if not AReader.read(WasmTypeId,1) then
  2218. begin
  2219. InputError('Error reading a function parameter basic type');
  2220. exit;
  2221. end;
  2222. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2223. begin
  2224. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2225. exit;
  2226. end;
  2227. FFuncTypes[i].add_param(wbt);
  2228. end;
  2229. if not ReadUleb32(ResultsCount) then
  2230. begin
  2231. InputError('Error reading the function results count');
  2232. exit;
  2233. end;
  2234. for j:=0 to ResultsCount-1 do
  2235. begin
  2236. if not AReader.read(WasmTypeId,1) then
  2237. begin
  2238. InputError('Error reading a function result basic type');
  2239. exit;
  2240. end;
  2241. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2242. begin
  2243. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2244. exit;
  2245. end;
  2246. FFuncTypes[i].add_result(wbt);
  2247. end;
  2248. end;
  2249. if AReader.Pos<>(SectionStart+SectionSize) then
  2250. begin
  2251. InputError('Unexpected type section size');
  2252. exit;
  2253. end;
  2254. Result:=true;
  2255. end;
  2256. function ReadImportSection: Boolean;
  2257. var
  2258. ImportsCount, typidx, TableLimitsMin, TableLimitsMax,
  2259. MemoryLimitsMin, MemoryLimitsMax: uint32;
  2260. i: Integer;
  2261. ModName, Name: ansistring;
  2262. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2263. GlobalType, GlobalMutabilityType: Byte;
  2264. TableElemWBT, GlobalTypeWBT: TWasmBasicType;
  2265. begin
  2266. Result:=False;
  2267. if ImportSectionRead then
  2268. begin
  2269. InputError('Import section is duplicated');
  2270. exit;
  2271. end;
  2272. ImportSectionRead:=True;
  2273. if not ReadUleb32(ImportsCount) then
  2274. begin
  2275. InputError('Error reading the imports count');
  2276. exit;
  2277. end;
  2278. for i:=0 to ImportsCount-1 do
  2279. begin
  2280. if not ReadName(ModName) then
  2281. begin
  2282. InputError('Error reading import module name');
  2283. exit;
  2284. end;
  2285. if not ReadName(Name) then
  2286. begin
  2287. InputError('Error import name');
  2288. exit;
  2289. end;
  2290. if not AReader.Read(ImportType,1) then
  2291. begin
  2292. InputError('Error reading import type');
  2293. exit;
  2294. end;
  2295. case ImportType of
  2296. $00: { func }
  2297. begin
  2298. if not ReadUleb32(typidx) then
  2299. begin
  2300. InputError('Error reading type index for func import');
  2301. exit;
  2302. end;
  2303. if typidx>high(FFuncTypes) then
  2304. begin
  2305. InputError('Type index in func import exceeds bounds of the types table');
  2306. exit;
  2307. end;
  2308. end;
  2309. $01: { table }
  2310. begin
  2311. if not AReader.read(TableElemTyp,1) then
  2312. begin
  2313. InputError('Error reading table element type for table import');
  2314. exit;
  2315. end;
  2316. if not decode_wasm_basic_type(TableElemTyp,TableElemWBT) then
  2317. begin
  2318. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2319. exit;
  2320. end;
  2321. if not (TableElemWBT in WasmReferenceTypes) then
  2322. begin
  2323. InputError('Table element type for table import must be a reference type');
  2324. exit;
  2325. end;
  2326. if not AReader.read(TableLimitsKind,1) then
  2327. begin
  2328. InputError('Error reading table limits kind for table import');
  2329. exit;
  2330. end;
  2331. case TableLimitsKind of
  2332. $00:
  2333. begin
  2334. if not ReadUleb32(TableLimitsMin) then
  2335. begin
  2336. InputError('Error reading table limits min for table import');
  2337. exit;
  2338. end;
  2339. end;
  2340. $01:
  2341. begin
  2342. if not ReadUleb32(TableLimitsMin) then
  2343. begin
  2344. InputError('Error reading table limits min for table import');
  2345. exit;
  2346. end;
  2347. if not ReadUleb32(TableLimitsMax) then
  2348. begin
  2349. InputError('Error reading table limits max for table import');
  2350. exit;
  2351. end;
  2352. if TableLimitsMin>TableLimitsMax then
  2353. begin
  2354. InputError('Table limits min exceed table limits max in table import');
  2355. exit;
  2356. end;
  2357. end;
  2358. else
  2359. begin
  2360. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2361. exit;
  2362. end;
  2363. end;
  2364. end;
  2365. $02: { mem }
  2366. begin
  2367. if not AReader.read(MemoryLimitsKind,1) then
  2368. begin
  2369. InputError('Error reading memory limits kind for memory import');
  2370. exit;
  2371. end;
  2372. case MemoryLimitsKind of
  2373. $00:
  2374. begin
  2375. if not ReadUleb32(MemoryLimitsMin) then
  2376. begin
  2377. InputError('Error reading memory limits min for memory import');
  2378. exit;
  2379. end;
  2380. end;
  2381. $01:
  2382. begin
  2383. if not ReadUleb32(MemoryLimitsMin) then
  2384. begin
  2385. InputError('Error reading memory limits min for memory import');
  2386. exit;
  2387. end;
  2388. if not ReadUleb32(MemoryLimitsMax) then
  2389. begin
  2390. InputError('Error reading memory limits max for memory import');
  2391. exit;
  2392. end;
  2393. if MemoryLimitsMin>MemoryLimitsMax then
  2394. begin
  2395. InputError('Memory limits min exceed memory limits max in memory import');
  2396. exit;
  2397. end;
  2398. end;
  2399. else
  2400. begin
  2401. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2402. exit;
  2403. end;
  2404. end;
  2405. end;
  2406. $03: { global }
  2407. begin
  2408. if not AReader.read(GlobalType,1) then
  2409. begin
  2410. InputError('Error reading global type for global import');
  2411. exit;
  2412. end;
  2413. if not decode_wasm_basic_type(GlobalType,GlobalTypeWBT) then
  2414. begin
  2415. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  2416. exit;
  2417. end;
  2418. if not AReader.read(GlobalMutabilityType,1) then
  2419. begin
  2420. InputError('Error reading global mutability flag for global import');
  2421. exit;
  2422. end;
  2423. case GlobalMutabilityType of
  2424. $00:
  2425. {const};
  2426. $01:
  2427. {var};
  2428. else
  2429. begin
  2430. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  2431. exit;
  2432. end;
  2433. end;
  2434. end;
  2435. else
  2436. begin
  2437. InputError('Unknown import type: $' + HexStr(ImportType,2));
  2438. exit;
  2439. end;
  2440. end;
  2441. end;
  2442. if AReader.Pos<>(SectionStart+SectionSize) then
  2443. begin
  2444. InputError('Unexpected import section size');
  2445. exit;
  2446. end;
  2447. Result:=true;
  2448. end;
  2449. function ReadFunctionSection: Boolean;
  2450. var
  2451. FunctionsCount, typidx: uint32;
  2452. i: Integer;
  2453. begin
  2454. Result:=False;
  2455. if FunctionSectionRead then
  2456. begin
  2457. InputError('Function section is duplicated');
  2458. exit;
  2459. end;
  2460. FunctionSectionRead:=True;
  2461. if not ReadUleb32(FunctionsCount) then
  2462. begin
  2463. InputError('Error reading the functions count');
  2464. exit;
  2465. end;
  2466. for i:=0 to FunctionsCount-1 do
  2467. begin
  2468. if not ReadUleb32(typidx) then
  2469. begin
  2470. InputError('Error reading type index for function');
  2471. exit;
  2472. end;
  2473. if typidx>high(FFuncTypes) then
  2474. begin
  2475. InputError('Type index in the function section exceeds bounds of the types table');
  2476. exit;
  2477. end;
  2478. end;
  2479. if AReader.Pos<>(SectionStart+SectionSize) then
  2480. begin
  2481. InputError('Unexpected function section size');
  2482. exit;
  2483. end;
  2484. Result:=true;
  2485. end;
  2486. function ReadGlobalSection: Boolean;
  2487. begin
  2488. Result:=False;
  2489. end;
  2490. function ReadExportSection: Boolean;
  2491. begin
  2492. Result:=False;
  2493. end;
  2494. function ReadCodeSection: Boolean;
  2495. var
  2496. CodeEntriesCount: uint32;
  2497. i: Integer;
  2498. begin
  2499. Result:=False;
  2500. if CodeSectionRead then
  2501. begin
  2502. InputError('Code section is duplicated');
  2503. exit;
  2504. end;
  2505. CodeSectionRead:=True;
  2506. if not ReadUleb32(CodeEntriesCount) then
  2507. begin
  2508. InputError('Error reading the code entries cound from the code section');
  2509. exit;
  2510. end;
  2511. for i:=0 to CodeEntriesCount-1 do
  2512. begin
  2513. {TODO}
  2514. end;
  2515. end;
  2516. function ReadDataSection: Boolean;
  2517. begin
  2518. Result:=False;
  2519. end;
  2520. function ReadDataCountSection: Boolean;
  2521. var
  2522. v: uint32;
  2523. begin
  2524. Result:=False;
  2525. if DataCountSectionRead then
  2526. begin
  2527. InputError('Data count section is duplicated');
  2528. exit;
  2529. end;
  2530. DataCountSectionRead:=True;
  2531. if not ReadUleb32(v) then
  2532. begin
  2533. InputError('Error reading the data count from the data count section');
  2534. exit;
  2535. end;
  2536. DataCount:=v;
  2537. if AReader.Pos<>(SectionStart+SectionSize) then
  2538. begin
  2539. InputError('Unexpected data count section size');
  2540. exit;
  2541. end;
  2542. Result:=true;
  2543. end;
  2544. begin
  2545. Result:=False;
  2546. if not AReader.read(SectionId,1) then
  2547. begin
  2548. InputError('Error reading section ID');
  2549. exit;
  2550. end;
  2551. CheckSectionBounds:=false;
  2552. if not ReadUleb32(SectionSize) then
  2553. begin
  2554. InputError('Error reading section size');
  2555. exit;
  2556. end;
  2557. if (AReader.Pos+SectionSize)>AReader.size then
  2558. begin
  2559. InputError('Section exceeds beyond the end of file');
  2560. exit;
  2561. end;
  2562. SectionStart:=AReader.Pos;
  2563. CheckSectionBounds:=true;
  2564. case SectionId of
  2565. Byte(wsiCustom):
  2566. if not ReadCustomSection then
  2567. begin
  2568. InputError('Error encountered, while reading a custom section');
  2569. exit;
  2570. end;
  2571. Byte(wsiType):
  2572. if not ReadTypeSection then
  2573. begin
  2574. InputError('Error reading the type section');
  2575. exit;
  2576. end;
  2577. Byte(wsiImport):
  2578. if not ReadImportSection then
  2579. begin
  2580. InputError('Error reading the import section');
  2581. exit;
  2582. end;
  2583. Byte(wsiFunction):
  2584. if not ReadFunctionSection then
  2585. begin
  2586. InputError('Error reading the function section');
  2587. exit;
  2588. end;
  2589. Byte(wsiGlobal):
  2590. Result := ReadGlobalSection;
  2591. Byte(wsiExport):
  2592. Result := ReadExportSection;
  2593. Byte(wsiCode):
  2594. Result := ReadCodeSection;
  2595. Byte(wsiData):
  2596. Result := ReadDataSection;
  2597. Byte(wsiDataCount):
  2598. begin
  2599. if not ReadDataCountSection then
  2600. begin
  2601. InputError('Error reading the data count section');
  2602. exit;
  2603. end;
  2604. end
  2605. else
  2606. begin
  2607. InputError('Unknown section: ' + ToStr(SectionId));
  2608. exit;
  2609. end;
  2610. end;
  2611. if SectionSize>0 then
  2612. AReader.seek(SectionStart+SectionSize);
  2613. Result:=True;
  2614. end;
  2615. var
  2616. ModuleMagic: array [0..3] of Byte;
  2617. ModuleVersion: array [0..3] of Byte;
  2618. i: Integer;
  2619. begin
  2620. objdata:=CObjData.Create(InputFileName);
  2621. result:=false;
  2622. if not AReader.read(ModuleMagic,4) then
  2623. exit;
  2624. for i:=0 to 3 do
  2625. if ModuleMagic[i]<>WasmModuleMagic[i] then
  2626. exit;
  2627. if not AReader.read(ModuleVersion,4) then
  2628. exit;
  2629. for i:=0 to 3 do
  2630. if ModuleVersion[i]<>WasmVersion[i] then
  2631. exit;
  2632. while AReader.Pos<AReader.size do
  2633. if not ReadSection then
  2634. exit;
  2635. Result:=True;
  2636. end;
  2637. {****************************************************************************
  2638. TWasmExeOutput
  2639. ****************************************************************************}
  2640. function TWasmExeOutput.writeData: boolean;
  2641. begin
  2642. result:=false;
  2643. {TODO: implement}
  2644. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  2645. Writer.write(WasmVersion,SizeOf(WasmVersion));
  2646. result := true;
  2647. end;
  2648. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  2649. begin
  2650. {TODO: implement}
  2651. end;
  2652. constructor TWasmExeOutput.create;
  2653. begin
  2654. inherited create;
  2655. CObjData:=TWasmObjData;
  2656. end;
  2657. {****************************************************************************
  2658. TWasmAssembler
  2659. ****************************************************************************}
  2660. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  2661. begin
  2662. inherited;
  2663. CObjOutput:=TWasmObjOutput;
  2664. end;
  2665. {*****************************************************************************
  2666. Initialize
  2667. *****************************************************************************}
  2668. {$ifdef wasm32}
  2669. const
  2670. as_wasm32_wasm_info : tasminfo =
  2671. (
  2672. id : as_wasm32_wasm;
  2673. idtxt : 'WASM';
  2674. asmbin : '';
  2675. asmcmd : '';
  2676. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  2677. flags : [af_outputbinary,af_smartlink_sections];
  2678. labelprefix : '..@';
  2679. labelmaxlen : -1;
  2680. comment : '; ';
  2681. dollarsign: '$';
  2682. );
  2683. {$endif wasm32}
  2684. initialization
  2685. {$ifdef wasm32}
  2686. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  2687. {$endif wasm32}
  2688. end.