ogwasm.pas 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509
  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. result:=false;
  1991. if not AReader.read(ModuleMagic,4) then
  1992. exit;
  1993. for i:=0 to 3 do
  1994. if ModuleMagic[i]<>WasmModuleMagic[i] then
  1995. exit;
  1996. if not AReader.read(ModuleVersion,4) then
  1997. exit;
  1998. for i:=0 to 3 do
  1999. if ModuleVersion[i]<>WasmVersion[i] then
  2000. exit;
  2001. result:=true;
  2002. end;
  2003. function TWasmObjInput.ReadObjData(AReader: TObjectreader; out ObjData: TObjData): boolean;
  2004. type
  2005. TLimits = record
  2006. Min, Max: uint32;
  2007. HasMax: Boolean;
  2008. end;
  2009. var
  2010. SectionId: Byte;
  2011. SectionSize: uint32;
  2012. SectionStart: LongInt;
  2013. CheckSectionBounds: Boolean;
  2014. TypeSectionRead: Boolean = false;
  2015. ImportSectionRead: Boolean = false;
  2016. FunctionSectionRead: Boolean = false;
  2017. GlobalSectionRead: Boolean = false;
  2018. CodeSectionRead: Boolean = false;
  2019. DataSectionRead: Boolean = false;
  2020. DataCountSectionRead: Boolean = false;
  2021. SegmentInfoSectionRead: Boolean = false;
  2022. SymbolTableSectionRead: Boolean = false;
  2023. FuncTypes: array of record
  2024. IsImport: Boolean;
  2025. ImportName: ansistring;
  2026. ImportModName: ansistring;
  2027. typidx: uint32;
  2028. end;
  2029. FuncTypeImportsCount: uint32;
  2030. TableTypes: array of record
  2031. IsImport: Boolean;
  2032. ImportName: ansistring;
  2033. ImportModName: ansistring;
  2034. reftype: TWasmBAsicType;
  2035. limits: TLimits;
  2036. end;
  2037. TableTypeImportsCount: uint32;
  2038. MemTypes: array of record
  2039. IsImport: Boolean;
  2040. ImportName: ansistring;
  2041. ImportModName: ansistring;
  2042. limits: TLimits;
  2043. end;
  2044. MemTypeImportsCount: uint32;
  2045. GlobalTypes: array of record
  2046. IsImport: Boolean;
  2047. ImportName: ansistring;
  2048. ImportModName: ansistring;
  2049. valtype: TWasmBasicType;
  2050. IsMutable: Boolean;
  2051. end;
  2052. GlobalTypeImportsCount: uint32;
  2053. DataSegments: array of record
  2054. Active: Boolean;
  2055. MemIdx: uint32;
  2056. Len: uint32;
  2057. Offset: int32;
  2058. DataPos: LongInt;
  2059. SegName: ansistring;
  2060. SegAlignment: uint32;
  2061. SegFlags: uint32;
  2062. end;
  2063. SymbolTable: array of record
  2064. SymFlags: uint32;
  2065. TargetSection: uint32;
  2066. SymIndex: uint32;
  2067. SymOffset: uint32;
  2068. SymSize: uint32;
  2069. SymKind: Byte;
  2070. SymName: ansistring;
  2071. end;
  2072. function ReadSection: Boolean;
  2073. function read(out b;len:longint):boolean;
  2074. begin
  2075. result:=false;
  2076. if not CheckSectionBounds or ((AReader.Pos+len)<=(SectionStart+SectionSize)) then
  2077. result:=AReader.read(b,len)
  2078. else
  2079. begin
  2080. { trying to read beyond the end of the section }
  2081. AReader.read(b,SectionStart+SectionSize-AReader.Pos);
  2082. result:=false;
  2083. end;
  2084. end;
  2085. function ReadUleb(out v: uint64): boolean;
  2086. var
  2087. b: byte;
  2088. shift:integer;
  2089. begin
  2090. result:=false;
  2091. b:=0;
  2092. v:=0;
  2093. shift:=0;
  2094. repeat
  2095. if not read(b,1) then
  2096. exit;
  2097. v:=v or (uint64(b and 127) shl shift);
  2098. inc(shift,7);
  2099. until (b and 128)=0;
  2100. result:=true;
  2101. end;
  2102. function ReadUleb32(out v: uint32): boolean;
  2103. var
  2104. vv: uint64;
  2105. begin
  2106. result:=false;
  2107. v:=default(uint32);
  2108. if not ReadUleb(vv) then
  2109. exit;
  2110. if vv>high(uint32) then
  2111. exit;
  2112. v:=vv;
  2113. result:=true;
  2114. end;
  2115. function ReadSleb(out v: int64): boolean;
  2116. var
  2117. b: byte;
  2118. shift:integer;
  2119. begin
  2120. result:=false;
  2121. b:=0;
  2122. v:=0;
  2123. shift:=0;
  2124. repeat
  2125. if not read(b,1) then
  2126. exit;
  2127. v:=v or (uint64(b and 127) shl shift);
  2128. inc(shift,7);
  2129. until (b and 128)=0;
  2130. {$ifopt Q+}
  2131. {$define overflowon}
  2132. {$Q-}
  2133. {$endif}
  2134. {$ifopt R+}
  2135. {$define rangeon}
  2136. {$R-}
  2137. {$endif}
  2138. if (b and 64)<>0 then
  2139. v:=v or (high(uint64) shl shift);
  2140. result:=true;
  2141. end;
  2142. {$ifdef overflowon}
  2143. {$Q+}
  2144. {$undef overflowon}
  2145. {$endif}
  2146. {$ifdef rangeon}
  2147. {$R+}
  2148. {$undef rangeon}
  2149. {$endif}
  2150. function ReadSleb32(out v: int32): boolean;
  2151. var
  2152. vv: int64;
  2153. begin
  2154. result:=false;
  2155. v:=default(int32);
  2156. if not ReadSleb(vv) then
  2157. exit;
  2158. if (vv>high(int32)) or (vv<low(int32)) then
  2159. exit;
  2160. v:=vv;
  2161. result:=true;
  2162. end;
  2163. function ReadName(out v: ansistring): boolean;
  2164. var
  2165. len: uint32;
  2166. begin
  2167. result:=false;
  2168. if not ReadUleb32(len) then
  2169. exit;
  2170. SetLength(v,len);
  2171. if len>0 then
  2172. result:=read(v[1],len)
  2173. else
  2174. result:=true;
  2175. end;
  2176. function ReadCustomSection: Boolean;
  2177. function ReadRelocationSection: Boolean;
  2178. begin
  2179. Result:=False;
  2180. end;
  2181. function ReadLinkingSection: Boolean;
  2182. function ReadSegmentInfo: Boolean;
  2183. var
  2184. SegmentCount: uint32;
  2185. i: Integer;
  2186. begin
  2187. Result:=False;
  2188. if SegmentInfoSectionRead then
  2189. begin
  2190. InputError('The WASM_SEGMENT_INFO subsection is duplicated');
  2191. exit;
  2192. end;
  2193. SegmentInfoSectionRead:=True;
  2194. if not ReadUleb32(SegmentCount) then
  2195. begin
  2196. InputError('Error reading the segment count from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2197. exit;
  2198. end;
  2199. if SegmentCount<>Length(DataSegments) then
  2200. begin
  2201. InputError('Segment count in the WASM_SEGMENT_INFO subsection does not match the data count in the data section');
  2202. exit;
  2203. end;
  2204. for i:=0 to SegmentCount-1 do
  2205. with DataSegments[i] do
  2206. begin
  2207. if not ReadName(SegName) then
  2208. begin
  2209. InputError('Error reading segment name from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2210. exit;
  2211. end;
  2212. if not ReadUleb32(SegAlignment) then
  2213. begin
  2214. InputError('Error reading segment alignment from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2215. exit;
  2216. end;
  2217. if not ReadUleb32(SegFlags) then
  2218. begin
  2219. InputError('Error reading segment flags from the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2220. exit;
  2221. end;
  2222. end;
  2223. if AReader.Pos<>(SectionStart+SectionSize) then
  2224. begin
  2225. InputError('Unexpected WASM_SEGMENT_INFO section size');
  2226. exit;
  2227. end;
  2228. Result:=True;
  2229. end;
  2230. function ReadSymbolTable: Boolean;
  2231. var
  2232. SymCount: uint32;
  2233. i: Integer;
  2234. SymKindName: string;
  2235. begin
  2236. Result:=False;
  2237. if SymbolTableSectionRead then
  2238. begin
  2239. InputError('The WASM_SYMBOL_TABLE subsection is duplicated');
  2240. exit;
  2241. end;
  2242. SymbolTableSectionRead:=True;
  2243. if not ReadUleb32(SymCount) then
  2244. begin
  2245. InputError('Error reading the symbol count from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2246. exit;
  2247. end;
  2248. SetLength(SymbolTable,SymCount);
  2249. for i:=0 to SymCount-1 do
  2250. with SymbolTable[i] do
  2251. begin
  2252. if not Read(SymKind,1) then
  2253. begin
  2254. InputError('Error reading symbol type from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2255. exit;
  2256. end;
  2257. if not ReadUleb32(SymFlags) then
  2258. begin
  2259. InputError('Error reading symbol flags from the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2260. exit;
  2261. end;
  2262. case SymKind of
  2263. byte(SYMTAB_FUNCTION),
  2264. byte(SYMTAB_GLOBAL),
  2265. byte(SYMTAB_EVENT),
  2266. byte(SYMTAB_TABLE):
  2267. begin
  2268. WriteStr(SymKindName, TWasmSymbolType(SymKind));
  2269. if not ReadUleb32(SymIndex) then
  2270. begin
  2271. InputError('Error reading the index of a ' + SymKindName + ' symbol');
  2272. exit;
  2273. end;
  2274. if ((SymKind=byte(SYMTAB_FUNCTION)) and (SymIndex>high(FuncTypes))) then
  2275. begin
  2276. InputError('Symbol index too high');
  2277. exit;
  2278. end;
  2279. if ((SymFlags and WASM_SYM_EXPLICIT_NAME)<>0) or
  2280. ((SymFlags and WASM_SYM_UNDEFINED)=0) then
  2281. begin
  2282. if not ReadName(SymName) then
  2283. begin
  2284. InputError('Error reading symbol name of a ' + SymKindName + ' symbol');
  2285. exit;
  2286. end;
  2287. end;
  2288. end;
  2289. byte(SYMTAB_DATA):
  2290. begin
  2291. if not ReadName(SymName) then
  2292. begin
  2293. InputError('Error reading symbol name of a SYMTAB_DATA symbol');
  2294. exit;
  2295. end;
  2296. if (SymFlags and WASM_SYM_UNDEFINED)=0 then
  2297. begin
  2298. if not ReadUleb32(SymIndex) then
  2299. begin
  2300. InputError('Error reading the data segment index of a SYMTAB_DATA symbol');
  2301. exit;
  2302. end;
  2303. if SymIndex>high(DataSegments) then
  2304. begin
  2305. InputError('Data segment index of SYMTAB_DATA symbol out of bounds');
  2306. exit;
  2307. end;
  2308. if not ReadUleb32(SymOffset) then
  2309. begin
  2310. InputError('Error reading the offset of a SYMTAB_DATA symbol');
  2311. exit;
  2312. end;
  2313. if not ReadUleb32(SymSize) then
  2314. begin
  2315. InputError('Error reading the size of a SYMTAB_DATA symbol');
  2316. exit;
  2317. end;
  2318. end;
  2319. end;
  2320. byte(SYMTAB_SECTION):
  2321. begin
  2322. if not ReadUleb32(TargetSection) then
  2323. begin
  2324. InputError('Error reading the target section of a SYMTAB_SECTION symbol');
  2325. exit;
  2326. end;
  2327. end;
  2328. else
  2329. begin
  2330. InputError('Unsupported symbol kind: ' + tostr(SymKind));
  2331. exit;
  2332. end;
  2333. end;
  2334. end;
  2335. if AReader.Pos<>(SectionStart+SectionSize) then
  2336. begin
  2337. InputError('Unexpected WASM_SYMBOL_TABLE section size');
  2338. exit;
  2339. end;
  2340. Result:=True;
  2341. end;
  2342. const
  2343. ExpectedVersion = 2;
  2344. var
  2345. Version, SubsectionSize, SaveSectionSize: uint32;
  2346. SubsectionType: Byte;
  2347. SaveSectionStart: LongInt;
  2348. begin
  2349. Result:=False;
  2350. if not ReadUleb32(Version) then
  2351. begin
  2352. InputError('Error reading the version of the ''linking'' section');
  2353. exit;
  2354. end;
  2355. if Version<>ExpectedVersion then
  2356. begin
  2357. InputError('The ''linking'' section has an unsupported version (expected version ' + tostr(ExpectedVersion) + ', got version ' + tostr(Version) + ')');
  2358. exit;
  2359. end;
  2360. while AReader.Pos<(SectionStart+SectionSize) do
  2361. begin
  2362. if not read(SubsectionType, 1) then
  2363. begin
  2364. InputError('Error reading subsection type in the ''linking'' section');
  2365. exit;
  2366. end;
  2367. if not ReadUleb32(SubsectionSize) then
  2368. begin
  2369. InputError('Error reading subsection size in the ''linking'' section');
  2370. exit;
  2371. end;
  2372. if (AReader.Pos+SubsectionSize)>(SectionStart+SectionSize) then
  2373. begin
  2374. InputError('Subsection size exceeds bounds of its parent ''linking'' section');
  2375. exit;
  2376. end;
  2377. SaveSectionStart:=SectionStart;
  2378. SaveSectionSize:=SectionSize;
  2379. SectionStart:=AReader.Pos;
  2380. SectionSize:=SubsectionSize;
  2381. case SubsectionType of
  2382. Byte(WASM_SEGMENT_INFO):
  2383. if not ReadSegmentInfo then
  2384. begin
  2385. InputError('Error reading the WASM_SEGMENT_INFO subsection of the ''linking'' section');
  2386. exit;
  2387. end;
  2388. Byte(WASM_SYMBOL_TABLE):
  2389. if not ReadSymbolTable then
  2390. begin
  2391. InputError('Error reading the WASM_SYMBOL_TABLE subsection of the ''linking'' section');
  2392. exit;
  2393. end;
  2394. else
  2395. begin
  2396. InputError('Unsupported ''linking'' section subsection type ' + tostr(SubsectionType));
  2397. exit;
  2398. end;
  2399. end;
  2400. AReader.Seek(SectionStart+SectionSize);
  2401. SectionStart:=SaveSectionStart;
  2402. SectionSize:=SaveSectionSize;
  2403. end;
  2404. result:=True;
  2405. end;
  2406. function ReadProducersSection: Boolean;
  2407. begin
  2408. Result:=False;
  2409. end;
  2410. function ReadTargetFeaturesSection: Boolean;
  2411. begin
  2412. Result:=False;
  2413. end;
  2414. const
  2415. RelocationSectionPrefix = 'reloc.';
  2416. var
  2417. SectionName: ansistring;
  2418. begin
  2419. Result:=False;
  2420. ReadName(SectionName);
  2421. if Copy(SectionName,1,Length(RelocationSectionPrefix)) = RelocationSectionPrefix then
  2422. Result:=ReadRelocationSection
  2423. else
  2424. case SectionName of
  2425. 'linking':
  2426. if not ReadLinkingSection then
  2427. begin
  2428. InputError('Error reading the ''linking'' section');
  2429. exit;
  2430. end;
  2431. 'producers':
  2432. Result:=ReadProducersSection;
  2433. 'target_features':
  2434. Result:=ReadTargetFeaturesSection;
  2435. else
  2436. InputError('Unsupported custom section: ''' + SectionName + '''');
  2437. end;
  2438. Result:=True;
  2439. end;
  2440. function ReadTypeSection: Boolean;
  2441. var
  2442. FuncTypesCount, ParamsCount, ResultsCount: uint32;
  2443. FuncTypeId, WasmTypeId: Byte;
  2444. i, j: Integer;
  2445. wbt: TWasmBasicType;
  2446. begin
  2447. Result:=False;
  2448. if TypeSectionRead then
  2449. begin
  2450. InputError('Type section is duplicated');
  2451. exit;
  2452. end;
  2453. TypeSectionRead:=True;
  2454. if not ReadUleb32(FuncTypesCount) then
  2455. begin
  2456. InputError('Error reading the func types count');
  2457. exit;
  2458. end;
  2459. SetLength(FFuncTypes,FuncTypesCount);
  2460. for i:=0 to FuncTypesCount - 1 do
  2461. begin
  2462. FFuncTypes[i]:=TWasmFuncType.Create([],[]);
  2463. if not AReader.read(FuncTypeId,1) then
  2464. begin
  2465. InputError('Error reading the function type identifier');
  2466. exit;
  2467. end;
  2468. if FuncTypeId<>$60 then
  2469. begin
  2470. InputError('Incorrect function type identifier (expected $60, got $' + HexStr(FuncTypeId,2) + ')');
  2471. exit;
  2472. end;
  2473. if not ReadUleb32(ParamsCount) then
  2474. begin
  2475. InputError('Error reading the function parameters count');
  2476. exit;
  2477. end;
  2478. for j:=0 to ParamsCount-1 do
  2479. begin
  2480. if not AReader.read(WasmTypeId,1) then
  2481. begin
  2482. InputError('Error reading a function parameter basic type');
  2483. exit;
  2484. end;
  2485. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2486. begin
  2487. InputError('Unknown function parameter basic type: $' + HexStr(WasmTypeId,2));
  2488. exit;
  2489. end;
  2490. FFuncTypes[i].add_param(wbt);
  2491. end;
  2492. if not ReadUleb32(ResultsCount) then
  2493. begin
  2494. InputError('Error reading the function results count');
  2495. exit;
  2496. end;
  2497. for j:=0 to ResultsCount-1 do
  2498. begin
  2499. if not AReader.read(WasmTypeId,1) then
  2500. begin
  2501. InputError('Error reading a function result basic type');
  2502. exit;
  2503. end;
  2504. if not decode_wasm_basic_type(WasmTypeId,wbt) then
  2505. begin
  2506. InputError('Unknown function result basic type: $' + HexStr(WasmTypeId,2));
  2507. exit;
  2508. end;
  2509. FFuncTypes[i].add_result(wbt);
  2510. end;
  2511. end;
  2512. if AReader.Pos<>(SectionStart+SectionSize) then
  2513. begin
  2514. InputError('Unexpected type section size');
  2515. exit;
  2516. end;
  2517. Result:=true;
  2518. end;
  2519. function ReadImportSection: Boolean;
  2520. var
  2521. ImportsCount: uint32;
  2522. i: Integer;
  2523. ModName, Name: ansistring;
  2524. ImportType, TableElemTyp, TableLimitsKind, MemoryLimitsKind,
  2525. GlobalType, GlobalMutabilityType: Byte;
  2526. begin
  2527. Result:=False;
  2528. if ImportSectionRead then
  2529. begin
  2530. InputError('Import section is duplicated');
  2531. exit;
  2532. end;
  2533. ImportSectionRead:=True;
  2534. if not ReadUleb32(ImportsCount) then
  2535. begin
  2536. InputError('Error reading the imports count');
  2537. exit;
  2538. end;
  2539. for i:=0 to ImportsCount-1 do
  2540. begin
  2541. if not ReadName(ModName) then
  2542. begin
  2543. InputError('Error reading import module name');
  2544. exit;
  2545. end;
  2546. if not ReadName(Name) then
  2547. begin
  2548. InputError('Error import name');
  2549. exit;
  2550. end;
  2551. if not AReader.Read(ImportType,1) then
  2552. begin
  2553. InputError('Error reading import type');
  2554. exit;
  2555. end;
  2556. case ImportType of
  2557. $00: { func }
  2558. begin
  2559. Inc(FuncTypeImportsCount);
  2560. SetLength(FuncTypes,FuncTypeImportsCount);
  2561. with FuncTypes[FuncTypeImportsCount-1] do
  2562. begin
  2563. IsImport:=True;
  2564. ImportName:=Name;
  2565. ImportModName:=ModName;
  2566. if not ReadUleb32(typidx) then
  2567. begin
  2568. InputError('Error reading type index for func import');
  2569. exit;
  2570. end;
  2571. if typidx>high(FFuncTypes) then
  2572. begin
  2573. InputError('Type index in func import exceeds bounds of the types table');
  2574. exit;
  2575. end;
  2576. end;
  2577. end;
  2578. $01: { table }
  2579. begin
  2580. Inc(TableTypeImportsCount);
  2581. SetLength(TableTypes,TableTypeImportsCount);
  2582. with TableTypes[TableTypeImportsCount-1] do
  2583. begin
  2584. IsImport:=True;
  2585. ImportName:=Name;
  2586. ImportModName:=ModName;
  2587. if not AReader.read(TableElemTyp,1) then
  2588. begin
  2589. InputError('Error reading table element type for table import');
  2590. exit;
  2591. end;
  2592. if not decode_wasm_basic_type(TableElemTyp,reftype) then
  2593. begin
  2594. InputError('Invalid table element type for table import: $' + HexStr(TableElemTyp,2));
  2595. exit;
  2596. end;
  2597. if not (reftype in WasmReferenceTypes) then
  2598. begin
  2599. InputError('Table element type for table import must be a reference type');
  2600. exit;
  2601. end;
  2602. if not AReader.read(TableLimitsKind,1) then
  2603. begin
  2604. InputError('Error reading table limits kind for table import');
  2605. exit;
  2606. end;
  2607. case TableLimitsKind of
  2608. $00:
  2609. begin
  2610. limits.HasMax:=False;
  2611. limits.Max:=high(limits.Max);
  2612. if not ReadUleb32(limits.min) then
  2613. begin
  2614. InputError('Error reading table limits min for table import');
  2615. exit;
  2616. end;
  2617. end;
  2618. $01:
  2619. begin
  2620. limits.HasMax:=True;
  2621. if not ReadUleb32(limits.min) then
  2622. begin
  2623. InputError('Error reading table limits min for table import');
  2624. exit;
  2625. end;
  2626. if not ReadUleb32(limits.max) then
  2627. begin
  2628. InputError('Error reading table limits max for table import');
  2629. exit;
  2630. end;
  2631. if limits.min>limits.max then
  2632. begin
  2633. InputError('Table limits min exceed table limits max in table import');
  2634. exit;
  2635. end;
  2636. end;
  2637. else
  2638. begin
  2639. InputError('Unsupported table limits kind for table import: $' + HexStr(TableLimitsKind,2));
  2640. exit;
  2641. end;
  2642. end;
  2643. end;
  2644. end;
  2645. $02: { mem }
  2646. begin
  2647. Inc(MemTypeImportsCount);
  2648. SetLength(MemTypes,MemTypeImportsCount);
  2649. with MemTypes[MemTypeImportsCount-1] do
  2650. begin
  2651. IsImport:=True;
  2652. ImportName:=Name;
  2653. ImportModName:=ModName;
  2654. if not AReader.read(MemoryLimitsKind,1) then
  2655. begin
  2656. InputError('Error reading memory limits kind for memory import');
  2657. exit;
  2658. end;
  2659. case MemoryLimitsKind of
  2660. $00:
  2661. begin
  2662. limits.HasMax:=False;
  2663. limits.Max:=high(limits.Max);
  2664. if not ReadUleb32(limits.min) then
  2665. begin
  2666. InputError('Error reading memory limits min for memory import');
  2667. exit;
  2668. end;
  2669. end;
  2670. $01:
  2671. begin
  2672. limits.HasMax:=True;
  2673. if not ReadUleb32(limits.min) then
  2674. begin
  2675. InputError('Error reading memory limits min for memory import');
  2676. exit;
  2677. end;
  2678. if not ReadUleb32(limits.max) then
  2679. begin
  2680. InputError('Error reading memory limits max for memory import');
  2681. exit;
  2682. end;
  2683. if limits.Min>limits.Max then
  2684. begin
  2685. InputError('Memory limits min exceed memory limits max in memory import');
  2686. exit;
  2687. end;
  2688. end;
  2689. else
  2690. begin
  2691. InputError('Unsupported memory limits kind for memory import: $' + HexStr(MemoryLimitsKind,2));
  2692. exit;
  2693. end;
  2694. end;
  2695. end;
  2696. end;
  2697. $03: { global }
  2698. begin
  2699. Inc(GlobalTypeImportsCount);
  2700. SetLength(GlobalTypes,GlobalTypeImportsCount);
  2701. with GlobalTypes[GlobalTypeImportsCount-1] do
  2702. begin
  2703. IsImport:=True;
  2704. ImportName:=Name;
  2705. ImportModName:=ModName;
  2706. if not AReader.read(GlobalType,1) then
  2707. begin
  2708. InputError('Error reading global type for global import');
  2709. exit;
  2710. end;
  2711. if not decode_wasm_basic_type(GlobalType,valtype) then
  2712. begin
  2713. InputError('Unsupported global type for global import: ' + HexStr(GlobalType,2));
  2714. exit;
  2715. end;
  2716. if not AReader.read(GlobalMutabilityType,1) then
  2717. begin
  2718. InputError('Error reading global mutability flag for global import');
  2719. exit;
  2720. end;
  2721. case GlobalMutabilityType of
  2722. $00:
  2723. IsMutable:=False;
  2724. $01:
  2725. IsMutable:=True;
  2726. else
  2727. begin
  2728. InputError('Unknown global mutability flag for global import: $' + HexStr(GlobalMutabilityType,2));
  2729. exit;
  2730. end;
  2731. end;
  2732. end;
  2733. end;
  2734. else
  2735. begin
  2736. InputError('Unknown import type: $' + HexStr(ImportType,2));
  2737. exit;
  2738. end;
  2739. end;
  2740. end;
  2741. if AReader.Pos<>(SectionStart+SectionSize) then
  2742. begin
  2743. InputError('Unexpected import section size');
  2744. exit;
  2745. end;
  2746. Result:=true;
  2747. end;
  2748. function ReadFunctionSection: Boolean;
  2749. var
  2750. FunctionsCount: uint32;
  2751. i: Integer;
  2752. begin
  2753. Result:=False;
  2754. if FunctionSectionRead then
  2755. begin
  2756. InputError('Function section is duplicated');
  2757. exit;
  2758. end;
  2759. FunctionSectionRead:=True;
  2760. if not ReadUleb32(FunctionsCount) then
  2761. begin
  2762. InputError('Error reading the functions count');
  2763. exit;
  2764. end;
  2765. SetLength(FuncTypes, FuncTypeImportsCount + FunctionsCount);
  2766. for i:=0 to FunctionsCount-1 do
  2767. with FuncTypes[i + FuncTypeImportsCount] do
  2768. begin
  2769. IsImport:=False;
  2770. if not ReadUleb32(typidx) then
  2771. begin
  2772. InputError('Error reading type index for function');
  2773. exit;
  2774. end;
  2775. if typidx>high(FFuncTypes) then
  2776. begin
  2777. InputError('Type index in the function section exceeds bounds of the types table');
  2778. exit;
  2779. end;
  2780. end;
  2781. if AReader.Pos<>(SectionStart+SectionSize) then
  2782. begin
  2783. InputError('Unexpected function section size');
  2784. exit;
  2785. end;
  2786. Result:=true;
  2787. end;
  2788. function ReadGlobalSection: Boolean;
  2789. function ParseExpr: Boolean;
  2790. var
  2791. B: Byte;
  2792. tmpbuf: array [1..8] of Byte;
  2793. tmpInt32: int32;
  2794. tmpInt64: int64;
  2795. begin
  2796. Result:=False;
  2797. repeat
  2798. if not Read(B, 1) then
  2799. exit;
  2800. case B of
  2801. $0B: { end }
  2802. ;
  2803. $41: { i32.const }
  2804. if not ReadSleb32(tmpInt32) then
  2805. exit;
  2806. $42: { i64.const }
  2807. if not ReadSleb(tmpInt64) then
  2808. exit;
  2809. $43: { f32.const }
  2810. if not Read(tmpbuf, 4) then
  2811. exit;
  2812. $44: { f64.const }
  2813. if not Read(tmpbuf, 8) then
  2814. exit;
  2815. $D0: { ref.null }
  2816. if not Read(tmpbuf, 1) then
  2817. exit;
  2818. else
  2819. begin
  2820. InputError('Unsupported opcode in global initializer');
  2821. exit;
  2822. end;
  2823. end;
  2824. until b = $0B;
  2825. Result:=True;
  2826. end;
  2827. var
  2828. GlobalsCount: uint32;
  2829. i: Integer;
  2830. vt: Byte;
  2831. mut: Byte;
  2832. begin
  2833. Result:=False;
  2834. if GlobalSectionRead then
  2835. begin
  2836. InputError('Global section is duplicated');
  2837. exit;
  2838. end;
  2839. GlobalSectionRead:=True;
  2840. if not ReadUleb32(GlobalsCount) then
  2841. begin
  2842. InputError('Error reading the globals count from the global section');
  2843. exit;
  2844. end;
  2845. SetLength(GlobalTypes,Length(GlobalTypes)+GlobalsCount);
  2846. for i:=0 to GlobalsCount-1 do
  2847. with GlobalTypes[i + GlobalTypeImportsCount] do
  2848. begin
  2849. if not read(vt,1) then
  2850. begin
  2851. InputError('Error reading the type of a global from the global section');
  2852. exit;
  2853. end;
  2854. if not decode_wasm_basic_type(vt,valtype) then
  2855. begin
  2856. InputError('Unsupported type of global in the global section');
  2857. exit;
  2858. end;
  2859. if not read(mut,1) then
  2860. begin
  2861. InputError('Error reading the mutability flag of a global in the global section');
  2862. exit;
  2863. end;
  2864. case mut of
  2865. $00:
  2866. IsMutable:=False;
  2867. $01:
  2868. IsMutable:=True;
  2869. else
  2870. begin
  2871. InputError('Unsupported value (' + tostr(mut) + ') for the mutability flag of a global in the global section');
  2872. exit;
  2873. end;
  2874. end;
  2875. if not ParseExpr then
  2876. begin
  2877. InputError('Error parsing the global initializer expression in the global section');
  2878. exit;
  2879. end;
  2880. end;
  2881. if AReader.Pos<>(SectionStart+SectionSize) then
  2882. begin
  2883. InputError('Unexpected global section size');
  2884. exit;
  2885. end;
  2886. Result:=True;
  2887. end;
  2888. function ReadExportSection: Boolean;
  2889. begin
  2890. Result:=False;
  2891. end;
  2892. function ReadCodeSection: Boolean;
  2893. var
  2894. CodeEntriesCount: uint32;
  2895. i: Integer;
  2896. begin
  2897. Result:=False;
  2898. if CodeSectionRead then
  2899. begin
  2900. InputError('Code section is duplicated');
  2901. exit;
  2902. end;
  2903. CodeSectionRead:=True;
  2904. if not ReadUleb32(CodeEntriesCount) then
  2905. begin
  2906. InputError('Error reading the code entries cound from the code section');
  2907. exit;
  2908. end;
  2909. for i:=0 to CodeEntriesCount-1 do
  2910. begin
  2911. {TODO}
  2912. end;
  2913. end;
  2914. function ReadDataSection: Boolean;
  2915. function ReadExpr(out ExprV: int32): Boolean;
  2916. var
  2917. b: Byte;
  2918. begin
  2919. Result:=False;
  2920. if not Read(b,1) then
  2921. exit;
  2922. if b<>$41 then
  2923. begin
  2924. InputError('Only i32.const expressions supported');
  2925. exit;
  2926. end;
  2927. if not ReadSleb32(ExprV) then
  2928. exit;
  2929. if not Read(b,1) then
  2930. exit;
  2931. if b<>$0B then
  2932. begin
  2933. InputError('Only single const expressions supported');
  2934. exit;
  2935. end;
  2936. Result:=True;
  2937. end;
  2938. var
  2939. DataCount: uint32;
  2940. DataType: Byte;
  2941. i: Integer;
  2942. begin
  2943. Result:=False;
  2944. if DataSectionRead then
  2945. begin
  2946. InputError('Data section is duplicated');
  2947. exit;
  2948. end;
  2949. DataSectionRead:=True;
  2950. if not ReadUleb32(DataCount) then
  2951. begin
  2952. InputError('Error reading the data entries count from the data section');
  2953. exit;
  2954. end;
  2955. if DataCountSectionRead then
  2956. begin
  2957. if Length(DataSegments)<>DataCount then
  2958. begin
  2959. InputError('Data entries count in the data section do not match the number, specified in the data count section');
  2960. exit;
  2961. end;
  2962. end
  2963. else
  2964. SetLength(DataSegments,DataCount);
  2965. for i:=0 to DataCount-1 do
  2966. with DataSegments[i] do
  2967. begin
  2968. if not read(DataType, 1) then
  2969. begin
  2970. InputError('Error reading data type of segment from the data section');
  2971. exit;
  2972. end;
  2973. case DataType of
  2974. 0:
  2975. begin
  2976. Active:=True;
  2977. MemIdx:=0;
  2978. if not ReadExpr(Offset) then
  2979. begin
  2980. InputError('Error reading memory offset of segment from the data section');
  2981. exit;
  2982. end;
  2983. end;
  2984. 1:
  2985. Active:=False;
  2986. 2:
  2987. begin
  2988. Active:=True;
  2989. if not ReadUleb32(MemIdx) then
  2990. begin
  2991. InputError('Error reading MemIdx of segment from the data section');
  2992. exit;
  2993. end;
  2994. if not ReadExpr(Offset) then
  2995. begin
  2996. InputError('Error reading memory offset of segment from the data section');
  2997. exit;
  2998. end;
  2999. end;
  3000. else
  3001. begin
  3002. InputError('Unsupported data type of segment in the data section: ' + tostr(DataType));
  3003. exit;
  3004. end;
  3005. end;
  3006. if MemIdx<>0 then
  3007. begin
  3008. InputError('Memory index other than 0 not supported (got ' + tostr(MemIdx) + ')');
  3009. exit;
  3010. end;
  3011. if not Active then
  3012. begin
  3013. InputError('Passive memory segments not supported');
  3014. exit;
  3015. end;
  3016. if not ReadUleb32(Len) then
  3017. begin
  3018. InputError('Error reading data segment length');
  3019. exit;
  3020. end;
  3021. if (AReader.Pos+Len)>(SectionStart+SectionSize) then
  3022. begin
  3023. InputError('Data segment exceeds the bounds of the data section');
  3024. exit;
  3025. end;
  3026. DataPos:=AReader.Pos;
  3027. AReader.Seek(AReader.Pos+Len);
  3028. end;
  3029. if AReader.Pos<>(SectionStart+SectionSize) then
  3030. begin
  3031. InputError('Unexpected data section size');
  3032. exit;
  3033. end;
  3034. Result:=true;
  3035. end;
  3036. function ReadDataCountSection: Boolean;
  3037. var
  3038. DataCount: uint32;
  3039. begin
  3040. Result:=False;
  3041. if DataCountSectionRead then
  3042. begin
  3043. InputError('Data count section is duplicated');
  3044. exit;
  3045. end;
  3046. DataCountSectionRead:=True;
  3047. if DataSectionRead then
  3048. begin
  3049. InputError('The data count section must occur before the data section');
  3050. exit;
  3051. end;
  3052. if not ReadUleb32(DataCount) then
  3053. begin
  3054. InputError('Error reading the data count from the data count section');
  3055. exit;
  3056. end;
  3057. if AReader.Pos<>(SectionStart+SectionSize) then
  3058. begin
  3059. InputError('Unexpected data count section size');
  3060. exit;
  3061. end;
  3062. SetLength(DataSegments, DataCount);
  3063. Result:=true;
  3064. end;
  3065. begin
  3066. Result:=False;
  3067. if not AReader.read(SectionId,1) then
  3068. begin
  3069. InputError('Error reading section ID');
  3070. exit;
  3071. end;
  3072. CheckSectionBounds:=false;
  3073. if not ReadUleb32(SectionSize) then
  3074. begin
  3075. InputError('Error reading section size');
  3076. exit;
  3077. end;
  3078. if (AReader.Pos+SectionSize)>AReader.size then
  3079. begin
  3080. InputError('Section exceeds beyond the end of file');
  3081. exit;
  3082. end;
  3083. SectionStart:=AReader.Pos;
  3084. CheckSectionBounds:=true;
  3085. case SectionId of
  3086. Byte(wsiCustom):
  3087. if not ReadCustomSection then
  3088. begin
  3089. InputError('Error encountered, while reading a custom section');
  3090. exit;
  3091. end;
  3092. Byte(wsiType):
  3093. if not ReadTypeSection then
  3094. begin
  3095. InputError('Error reading the type section');
  3096. exit;
  3097. end;
  3098. Byte(wsiImport):
  3099. if not ReadImportSection then
  3100. begin
  3101. InputError('Error reading the import section');
  3102. exit;
  3103. end;
  3104. Byte(wsiFunction):
  3105. if not ReadFunctionSection then
  3106. begin
  3107. InputError('Error reading the function section');
  3108. exit;
  3109. end;
  3110. Byte(wsiGlobal):
  3111. if not ReadGlobalSection then
  3112. begin
  3113. InputError('Error reading the global section');
  3114. exit;
  3115. end;
  3116. Byte(wsiExport):
  3117. Result := ReadExportSection;
  3118. Byte(wsiCode):
  3119. Result := ReadCodeSection;
  3120. Byte(wsiData):
  3121. if not ReadDataSection then
  3122. begin
  3123. InputError('Error reading the data section');
  3124. exit;
  3125. end;
  3126. Byte(wsiDataCount):
  3127. begin
  3128. if not ReadDataCountSection then
  3129. begin
  3130. InputError('Error reading the data count section');
  3131. exit;
  3132. end;
  3133. end
  3134. else
  3135. begin
  3136. InputError('Unknown section: ' + ToStr(SectionId));
  3137. exit;
  3138. end;
  3139. end;
  3140. if SectionSize>0 then
  3141. AReader.seek(SectionStart+SectionSize);
  3142. Result:=True;
  3143. end;
  3144. var
  3145. ModuleMagic: array [0..3] of Byte;
  3146. ModuleVersion: array [0..3] of Byte;
  3147. i: Integer;
  3148. CurrSec: TObjSection;
  3149. objsym: TObjSymbol;
  3150. begin
  3151. FReader:=AReader;
  3152. InputFileName:=AReader.FileName;
  3153. objdata:=CObjData.Create(InputFileName);
  3154. result:=false;
  3155. DataSegments:=nil;
  3156. SymbolTable:=nil;
  3157. FuncTypes:=nil;
  3158. FuncTypeImportsCount:=0;
  3159. TableTypes:=nil;
  3160. TableTypeImportsCount:=0;
  3161. MemTypes:=nil;
  3162. MemTypeImportsCount:=0;
  3163. GlobalTypes:=nil;
  3164. GlobalTypeImportsCount:=0;
  3165. if not AReader.read(ModuleMagic,4) then
  3166. exit;
  3167. for i:=0 to 3 do
  3168. if ModuleMagic[i]<>WasmModuleMagic[i] then
  3169. exit;
  3170. if not AReader.read(ModuleVersion,4) then
  3171. exit;
  3172. for i:=0 to 3 do
  3173. if ModuleVersion[i]<>WasmVersion[i] then
  3174. exit;
  3175. while AReader.Pos<AReader.size do
  3176. if not ReadSection then
  3177. exit;
  3178. for i:=low(DataSegments) to high(DataSegments) do
  3179. with DataSegments[i] do
  3180. if Active then
  3181. begin
  3182. CurrSec:=ObjData.createsection(SegName,1 shl SegAlignment,[oso_Data,oso_load,oso_write],false);
  3183. CurrSec.DataPos:=DataPos;
  3184. CurrSec.MemPos:=Offset;
  3185. CurrSec.Size:=Len;
  3186. end;
  3187. ReadSectionContent(ObjData);
  3188. for i:=low(SymbolTable) to high(SymbolTable) do
  3189. with SymbolTable[i] do
  3190. case SymKind of
  3191. byte(SYMTAB_DATA):
  3192. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3193. begin
  3194. objsym:=ObjData.CreateSymbol(SymName);
  3195. objsym.bind:=AB_EXTERNAL;
  3196. objsym.typ:=AT_DATA;
  3197. objsym.objsection:=nil;
  3198. objsym.offset:=0;
  3199. objsym.size:=0;
  3200. end
  3201. else
  3202. begin
  3203. objsym:=ObjData.CreateSymbol(SymName);
  3204. if (SymFlags and WASM_SYM_BINDING_LOCAL)<> 0 then
  3205. objsym.bind:=AB_LOCAL
  3206. else
  3207. objsym.bind:=AB_GLOBAL;
  3208. objsym.typ:=AT_DATA;
  3209. objsym.objsection:=TObjSection(ObjData.ObjSectionList[SymIndex]);
  3210. objsym.offset:=SymOffset;
  3211. objsym.size:=SymSize;
  3212. end;
  3213. byte(SYMTAB_FUNCTION):
  3214. if (SymFlags and WASM_SYM_UNDEFINED)<>0 then
  3215. begin
  3216. if not FuncTypes[SymIndex].IsImport then
  3217. begin
  3218. InputError('WASM_SYM_UNDEFINED set on a SYMTAB_FUNCTION symbol, that is not an import');
  3219. exit;
  3220. end;
  3221. if (SymFlags and WASM_SYM_EXPLICIT_NAME)<>0 then
  3222. begin
  3223. Writeln('Alias: ', SymName, ' -> ', FuncTypes[SymIndex].ImportModName, '.', FuncTypes[SymIndex].ImportName);
  3224. {todo...}
  3225. end
  3226. else
  3227. begin
  3228. objsym:=ObjData.CreateSymbol(FuncTypes[SymIndex].ImportModName + '.' + FuncTypes[SymIndex].ImportName);
  3229. objsym.bind:=AB_EXTERNAL;
  3230. objsym.typ:=AT_FUNCTION;
  3231. objsym.objsection:=nil;
  3232. objsym.offset:=0;
  3233. objsym.size:=0;
  3234. end;
  3235. end
  3236. else
  3237. begin
  3238. if FuncTypes[SymIndex].IsImport then
  3239. begin
  3240. InputError('WASM_SYM_UNDEFINED not set on a SYMTAB_FUNCTION symbol, that is an import');
  3241. exit;
  3242. end;
  3243. {todo...}
  3244. end;
  3245. byte(SYMTAB_GLOBAL),
  3246. byte(SYMTAB_SECTION),
  3247. byte(SYMTAB_EVENT),
  3248. byte(SYMTAB_TABLE):
  3249. {TODO};
  3250. else
  3251. internalerror(2023122701);
  3252. end;
  3253. Result:=True;
  3254. end;
  3255. {****************************************************************************
  3256. TWasmExeOutput
  3257. ****************************************************************************}
  3258. function TWasmExeOutput.writeData: boolean;
  3259. begin
  3260. result:=false;
  3261. {TODO: implement}
  3262. Writer.write(WasmModuleMagic,SizeOf(WasmModuleMagic));
  3263. Writer.write(WasmVersion,SizeOf(WasmVersion));
  3264. result := true;
  3265. end;
  3266. procedure TWasmExeOutput.DoRelocationFixup(objsec: TObjSection);
  3267. begin
  3268. {TODO: implement}
  3269. end;
  3270. constructor TWasmExeOutput.create;
  3271. begin
  3272. inherited create;
  3273. CObjData:=TWasmObjData;
  3274. end;
  3275. {****************************************************************************
  3276. TWasmAssembler
  3277. ****************************************************************************}
  3278. constructor TWasmAssembler.Create(info: pasminfo; smart:boolean);
  3279. begin
  3280. inherited;
  3281. CObjOutput:=TWasmObjOutput;
  3282. end;
  3283. {*****************************************************************************
  3284. Initialize
  3285. *****************************************************************************}
  3286. {$ifdef wasm32}
  3287. const
  3288. as_wasm32_wasm_info : tasminfo =
  3289. (
  3290. id : as_wasm32_wasm;
  3291. idtxt : 'WASM';
  3292. asmbin : '';
  3293. asmcmd : '';
  3294. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  3295. flags : [af_outputbinary,af_smartlink_sections];
  3296. labelprefix : '..@';
  3297. labelmaxlen : -1;
  3298. comment : '; ';
  3299. dollarsign: '$';
  3300. );
  3301. {$endif wasm32}
  3302. initialization
  3303. {$ifdef wasm32}
  3304. RegisterAssembler(as_wasm32_wasm_info,TWasmAssembler);
  3305. {$endif wasm32}
  3306. end.